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/pdfbox/src/test/java/org/apache/pdfbox/pdmodel/edit/TestPDPageContentStream.java b/pdfbox/src/test/java/org/apache/pdfbox/pdmodel/edit/TestPDPageContentStream.java index ff85a72..f27b58a 100644 --- a/pdfbox/src/test/java/org/apache/pdfbox/pdmodel/edit/TestPDPageContentStream.java +++ b/pdfbox/src/test/java/org/apache/pdfbox/pdmodel/edit/TestPDPageContentStream.java @@ -1,96 +1,96 @@ /* * 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.pdfbox.pdmodel.edit; import junit.framework.TestCase; import org.apache.pdfbox.cos.COSFloat; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.pdfparser.PDFStreamParser; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.graphics.color.ColorSpaceCMYK; import org.apache.pdfbox.util.PDFOperator; import java.awt.Color; import java.awt.color.ColorSpace; import java.io.IOException; /** * @author Yegor Kozlov */ public class TestPDPageContentStream extends TestCase { public void testSetCmykColors() throws IOException, COSVisitorException { PDDocument doc = new PDDocument(); ColorSpace colorSpace = new ColorSpaceCMYK(); PDPage page = new PDPage(); doc.addPage(page); - PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false); + PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, true); // pass a non-stroking color in CMYK color space contentStream.setNonStrokingColor( new Color(colorSpace, new float[]{0.1f, 0.2f, 0.3f, 0.4f}, 1.0f)); contentStream.close(); // now read the PDF stream and verify that the CMYK values are correct COSStream stream = page.getContents().getStream(); PDFStreamParser parser = new PDFStreamParser(stream); parser.parse(); java.util.List<Object> pageTokens = parser.getTokens(); // expected five tokens : // [0] = COSFloat{0.1} // [1] = COSFloat{0.2} // [2] = COSFloat{0.3} // [3] = COSFloat{0.4} // [4] = PDFOperator{"k"} assertEquals(0.1f, ((COSFloat)pageTokens.get(0)).floatValue()); assertEquals(0.2f, ((COSFloat)pageTokens.get(1)).floatValue()); assertEquals(0.3f, ((COSFloat)pageTokens.get(2)).floatValue()); assertEquals(0.4f, ((COSFloat)pageTokens.get(3)).floatValue()); assertEquals("k", ((PDFOperator) pageTokens.get(4)).getOperation()); // same as above but for PDPageContentStream#setStrokingColor page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, false, false); // pass a non-stroking color in CMYK color space contentStream.setStrokingColor(new Color(colorSpace, new float[]{0.5f, 0.6f, 0.7f, 0.8f}, 1.0f)); contentStream.close(); // now read the PDF stream and verify that the CMYK values are correct stream = page.getContents().getStream(); parser = new PDFStreamParser(stream); parser.parse(); pageTokens = parser.getTokens(); // expected five tokens : // [0] = COSFloat{0.5} // [1] = COSFloat{0.6} // [2] = COSFloat{0.7} // [3] = COSFloat{0.8} // [4] = PDFOperator{"K"} assertEquals(0.5f, ((COSFloat)pageTokens.get(0)).floatValue()); assertEquals(0.6f, ((COSFloat)pageTokens.get(1)).floatValue()); assertEquals(0.7f, ((COSFloat)pageTokens.get(2)).floatValue()); assertEquals(0.8f, ((COSFloat)pageTokens.get(3)).floatValue()); assertEquals("K", ((PDFOperator)pageTokens.get(4)).getOperation()); } }
true
true
public void testSetCmykColors() throws IOException, COSVisitorException { PDDocument doc = new PDDocument(); ColorSpace colorSpace = new ColorSpaceCMYK(); PDPage page = new PDPage(); doc.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false); // pass a non-stroking color in CMYK color space contentStream.setNonStrokingColor( new Color(colorSpace, new float[]{0.1f, 0.2f, 0.3f, 0.4f}, 1.0f)); contentStream.close(); // now read the PDF stream and verify that the CMYK values are correct COSStream stream = page.getContents().getStream(); PDFStreamParser parser = new PDFStreamParser(stream); parser.parse(); java.util.List<Object> pageTokens = parser.getTokens(); // expected five tokens : // [0] = COSFloat{0.1} // [1] = COSFloat{0.2} // [2] = COSFloat{0.3} // [3] = COSFloat{0.4} // [4] = PDFOperator{"k"} assertEquals(0.1f, ((COSFloat)pageTokens.get(0)).floatValue()); assertEquals(0.2f, ((COSFloat)pageTokens.get(1)).floatValue()); assertEquals(0.3f, ((COSFloat)pageTokens.get(2)).floatValue()); assertEquals(0.4f, ((COSFloat)pageTokens.get(3)).floatValue()); assertEquals("k", ((PDFOperator) pageTokens.get(4)).getOperation()); // same as above but for PDPageContentStream#setStrokingColor page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, false, false); // pass a non-stroking color in CMYK color space contentStream.setStrokingColor(new Color(colorSpace, new float[]{0.5f, 0.6f, 0.7f, 0.8f}, 1.0f)); contentStream.close(); // now read the PDF stream and verify that the CMYK values are correct stream = page.getContents().getStream(); parser = new PDFStreamParser(stream); parser.parse(); pageTokens = parser.getTokens(); // expected five tokens : // [0] = COSFloat{0.5} // [1] = COSFloat{0.6} // [2] = COSFloat{0.7} // [3] = COSFloat{0.8} // [4] = PDFOperator{"K"} assertEquals(0.5f, ((COSFloat)pageTokens.get(0)).floatValue()); assertEquals(0.6f, ((COSFloat)pageTokens.get(1)).floatValue()); assertEquals(0.7f, ((COSFloat)pageTokens.get(2)).floatValue()); assertEquals(0.8f, ((COSFloat)pageTokens.get(3)).floatValue()); assertEquals("K", ((PDFOperator)pageTokens.get(4)).getOperation()); }
public void testSetCmykColors() throws IOException, COSVisitorException { PDDocument doc = new PDDocument(); ColorSpace colorSpace = new ColorSpaceCMYK(); PDPage page = new PDPage(); doc.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, true); // pass a non-stroking color in CMYK color space contentStream.setNonStrokingColor( new Color(colorSpace, new float[]{0.1f, 0.2f, 0.3f, 0.4f}, 1.0f)); contentStream.close(); // now read the PDF stream and verify that the CMYK values are correct COSStream stream = page.getContents().getStream(); PDFStreamParser parser = new PDFStreamParser(stream); parser.parse(); java.util.List<Object> pageTokens = parser.getTokens(); // expected five tokens : // [0] = COSFloat{0.1} // [1] = COSFloat{0.2} // [2] = COSFloat{0.3} // [3] = COSFloat{0.4} // [4] = PDFOperator{"k"} assertEquals(0.1f, ((COSFloat)pageTokens.get(0)).floatValue()); assertEquals(0.2f, ((COSFloat)pageTokens.get(1)).floatValue()); assertEquals(0.3f, ((COSFloat)pageTokens.get(2)).floatValue()); assertEquals(0.4f, ((COSFloat)pageTokens.get(3)).floatValue()); assertEquals("k", ((PDFOperator) pageTokens.get(4)).getOperation()); // same as above but for PDPageContentStream#setStrokingColor page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, false, false); // pass a non-stroking color in CMYK color space contentStream.setStrokingColor(new Color(colorSpace, new float[]{0.5f, 0.6f, 0.7f, 0.8f}, 1.0f)); contentStream.close(); // now read the PDF stream and verify that the CMYK values are correct stream = page.getContents().getStream(); parser = new PDFStreamParser(stream); parser.parse(); pageTokens = parser.getTokens(); // expected five tokens : // [0] = COSFloat{0.5} // [1] = COSFloat{0.6} // [2] = COSFloat{0.7} // [3] = COSFloat{0.8} // [4] = PDFOperator{"K"} assertEquals(0.5f, ((COSFloat)pageTokens.get(0)).floatValue()); assertEquals(0.6f, ((COSFloat)pageTokens.get(1)).floatValue()); assertEquals(0.7f, ((COSFloat)pageTokens.get(2)).floatValue()); assertEquals(0.8f, ((COSFloat)pageTokens.get(3)).floatValue()); assertEquals("K", ((PDFOperator)pageTokens.get(4)).getOperation()); }
diff --git a/odata4j-core/src/main/java/org/odata4j/producer/jpa/JPAProducer.java b/odata4j-core/src/main/java/org/odata4j/producer/jpa/JPAProducer.java index ba32b78..034da4b 100644 --- a/odata4j-core/src/main/java/org/odata4j/producer/jpa/JPAProducer.java +++ b/odata4j-core/src/main/java/org/odata4j/producer/jpa/JPAProducer.java @@ -1,1186 +1,1186 @@ package org.odata4j.producer.jpa; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Locale; import javax.persistence.CascadeType; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityNotFoundException; import javax.persistence.OneToMany; import javax.persistence.Query; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.Attribute.PersistentAttributeType; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.ManagedType; import javax.persistence.metamodel.PluralAttribute; import javax.persistence.metamodel.SingularAttribute; import org.core4j.CoreUtils; import org.core4j.Enumerable; import org.core4j.Func1; import org.core4j.Predicate1; import org.odata4j.core.OEntities; import org.odata4j.core.OEntity; import org.odata4j.core.OEntityKey; import org.odata4j.core.OLink; import org.odata4j.core.OLinks; import org.odata4j.core.OProperties; import org.odata4j.core.OProperty; import org.odata4j.core.ORelatedEntitiesLinkInline; import org.odata4j.core.ORelatedEntityLink; import org.odata4j.core.ORelatedEntityLinkInline; import org.odata4j.edm.EdmDataServices; import org.odata4j.edm.EdmEntitySet; import org.odata4j.edm.EdmMultiplicity; import org.odata4j.edm.EdmNavigationProperty; import org.odata4j.edm.EdmProperty; import org.odata4j.expression.BoolCommonExpression; import org.odata4j.expression.EntitySimpleProperty; import org.odata4j.expression.Expression; import org.odata4j.expression.ExpressionParser; import org.odata4j.expression.ExpressionParser.Token; import org.odata4j.expression.ExpressionParser.TokenType; import org.odata4j.expression.OrderByExpression; import org.odata4j.expression.StringLiteral; import org.odata4j.internal.TypeConverter; import org.odata4j.producer.BaseResponse; import org.odata4j.producer.EntitiesResponse; import org.odata4j.producer.EntityResponse; import org.odata4j.producer.InlineCount; import org.odata4j.producer.ODataProducer; import org.odata4j.producer.PropertyResponse; import org.odata4j.producer.QueryInfo; import org.odata4j.producer.Responses; import org.odata4j.producer.resources.OptionsQueryParser; public class JPAProducer implements ODataProducer { private final EntityManagerFactory emf; private final EntityManager em; private final EdmDataServices metadata; private final int maxResults; public JPAProducer( EntityManagerFactory emf, EdmDataServices metadata, int maxResults) { this.emf = emf; this.maxResults = maxResults; this.metadata = metadata; em = emf.createEntityManager(); // necessary for metamodel } public JPAProducer( EntityManagerFactory emf, String namespace, int maxResults) { this(emf, new JPAEdmGenerator().buildEdm(emf, namespace), maxResults); } @Override public void close() { em.close(); emf.close(); } @Override public EdmDataServices getMetadata() { return metadata; } @Override public EntityResponse getEntity(String entitySetName, Object entityKey) { return common(entitySetName, entityKey, null, new Func1<Context, EntityResponse>() { public EntityResponse apply(Context input) { return getEntity(input); } }); } @Override public EntitiesResponse getEntities(String entitySetName, QueryInfo queryInfo) { return common(entitySetName, null, queryInfo, new Func1<Context, EntitiesResponse>() { public EntitiesResponse apply(Context input) { return getEntities(input); } }); } @Override public BaseResponse getNavProperty( final String entitySetName, final Object entityKey, final String navProp, final QueryInfo queryInfo) { return common( entitySetName, entityKey, queryInfo, new Func1<Context, BaseResponse>() { public BaseResponse apply(Context input) { return getNavProperty(input, navProp); } }); } private static class Context { EntityManager em; EdmEntitySet ees; EntityType<?> jpaEntityType; String keyPropertyName; Object typeSafeEntityKey; QueryInfo query; } private EntityResponse getEntity(final Context context) { Object jpaEntity = context.em.find( context.jpaEntityType.getJavaType(), context.typeSafeEntityKey); if (jpaEntity == null) { throw new EntityNotFoundException( context.jpaEntityType.getJavaType() + " not found with key " + context.typeSafeEntityKey); } OEntity entity = makeEntity( context, jpaEntity); return Responses.entity(entity); } private OEntity makeEntity( Context context, final Object jpaEntity) { return jpaEntityToOEntity( context.ees, context.jpaEntityType, jpaEntity, context.query == null ? null : context.query.expand, context.query == null ? null : context.query.select); } private EntitiesResponse getEntities(final Context context) { final DynamicEntitiesResponse response = enumJpaEntities( context, null); return Responses.entities( response.entities, context.ees, response.inlineCount, response.skipToken); } private BaseResponse getNavProperty(final Context context,String navProp) { DynamicEntitiesResponse response = enumJpaEntities(context,navProp); if (response.responseType.equals(PropertyResponse.class)) return Responses.property(response.property); if (response.responseType.equals(EntityResponse.class)) return Responses.entity(response.entity); if (response.responseType.equals(EntitiesResponse.class)) return Responses.entities( response.entities, context.ees, response.inlineCount, response.skipToken); throw new UnsupportedOperationException("Unknown responseType: " + response.responseType.getName()); } private <T> T common( final String entitySetName, Object entityKey, QueryInfo query, Func1<Context, T> fn) { Context context = new Context(); context.em = emf.createEntityManager(); try { context.ees = metadata.getEdmEntitySet(entitySetName); context.jpaEntityType = findJPAEntityType( context.em, context.ees.type.name); context.keyPropertyName = context.ees.type.keys.get(0); context.typeSafeEntityKey = typeSafeEntityKey( context.em, context.jpaEntityType, entityKey); context.query = query; return fn.apply(context); } finally { context.em.close(); } } private OEntity jpaEntityToOEntity( EdmEntitySet ees, EntityType<?> entityType, Object jpaEntity, List<EntitySimpleProperty> expand, List<EntitySimpleProperty> select) { List<OProperty<?>> properties = new ArrayList<OProperty<?>>(); List<OLink> links = new ArrayList<OLink>(); try { SingularAttribute<?, ?> idAtt = JPAEdmGenerator.getId(entityType); boolean hasEmbeddedCompositeKey = idAtt.getPersistentAttributeType() == PersistentAttributeType.EMBEDDED; Object id = getIdValue(jpaEntity, idAtt, null); // get properties for (EdmProperty ep : ees.type.properties) { if (!isSelected(ep.name, select)) { continue; } // we have a embedded composite key and we want a property from // that key if (hasEmbeddedCompositeKey && ees.type.keys.contains(ep.name)) { Object value = getIdValue(jpaEntity, idAtt, ep.name); properties.add(OProperties.simple( ep.name, ep.type, value, true)); } else { // get the simple attribute Attribute<?, ?> att = entityType.getAttribute(ep.name); Member member = att.getJavaMember(); Object value = getValue(jpaEntity, member); properties.add(OProperties.simple( ep.name, ep.type, value, true)); } } for (final EdmNavigationProperty ep : ees.type.navigationProperties) { ep.selected = isSelected(ep.name, select); } // get the collections if necessary if (expand != null && !expand.isEmpty()) { for (final EntitySimpleProperty propPath : expand) { // split the property path into the first and remaining // parts String[] props = propPath.getPropertyName().split("/", 2); String prop = props[0]; List<EntitySimpleProperty> remainingPropPath = props.length > 1 ? Arrays.asList(org.odata4j.expression.Expression .simpleProperty(props[1])) : null; Attribute<?, ?> att = entityType.getAttribute(prop); if (att.getPersistentAttributeType() == PersistentAttributeType.ONE_TO_MANY || att.getPersistentAttributeType() == PersistentAttributeType.MANY_TO_MANY) { Collection<?> value = getValue( jpaEntity, att.getJavaMember()); List<OEntity> relatedEntities = new ArrayList<OEntity>(); for (Object relatedEntity : value) { EntityType<?> elementEntityType = (EntityType<?>) ((PluralAttribute<?, ?, ?>) att) .getElementType(); EdmEntitySet elementEntitySet = metadata .getEdmEntitySet(JPAEdmGenerator.getEntitySetName(elementEntityType)); relatedEntities.add(jpaEntityToOEntity( elementEntitySet, elementEntityType, relatedEntity, remainingPropPath, null)); } links.add(OLinks.relatedEntitiesInline( null, prop, null, relatedEntities)); } else if (att.getPersistentAttributeType() == PersistentAttributeType.ONE_TO_ONE || att.getPersistentAttributeType() == PersistentAttributeType.MANY_TO_ONE) { EntityType<?> relatedEntityType = (EntityType<?>) ((SingularAttribute<?, ?>) att) .getType(); EdmEntitySet relatedEntitySet = metadata.getEdmEntitySet(JPAEdmGenerator .getEntitySetName(relatedEntityType)); Object relatedEntity = getValue( jpaEntity, att.getJavaMember()); if( relatedEntity == null ) { links.add(OLinks.relatedEntityInline( null, prop, null, null)); }else { links.add(OLinks.relatedEntityInline( null, prop, null, jpaEntityToOEntity( relatedEntitySet, relatedEntityType, relatedEntity, remainingPropPath, null))); } } } } return OEntities.create(ees, OEntityKey.create(id), properties, links); } catch (Exception e) { throw new RuntimeException(e); } } private static boolean isSelected( String name, List<EntitySimpleProperty> select) { if (select != null && !select.isEmpty()) { for (EntitySimpleProperty prop : select) { String sname = prop.getPropertyName(); if (name.equals(sname)) { return true; } } return false; } return true; } private static Object getIdValue( Object jpaEntity, SingularAttribute<?, ?> idAtt, String propName) { try { // get the composite id Member member = idAtt.getJavaMember(); Object key = getValue(jpaEntity, member); if (propName == null) { return key; } // get the property from the key ManagedType<?> keyType = (ManagedType<?>) idAtt.getType(); Attribute<?, ?> att = keyType.getAttribute(propName); member = att.getJavaMember(); if (member == null) { // http://wiki.eclipse.org/EclipseLink/Development/JPA_2.0/metamodel_api#DI_95:_20091017:_Attribute.getJavaMember.28.29_returns_null_for_a_BasicType_on_a_MappedSuperclass_because_of_an_uninitialized_accessor member = getJavaMember(key.getClass(), propName); } return getValue(key, member); } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") private static <T> T getValue(Object obj, Member member) throws Exception { if (member instanceof Field) { Field field = (Field) member; field.setAccessible(true); return (T) field.get(obj); } else if (member instanceof Method) { Method method = (Method) member; method.setAccessible(true); return (T) method.invoke(obj); } else { throw new UnsupportedOperationException("Implement member" + member); } } private static void setValue(Object obj, Member member, Object value) throws Exception { if (member instanceof Field) { Field field = (Field) member; field.setAccessible(true); field.set(obj, value); } else if (member instanceof Method) { throw new UnsupportedOperationException("Implement member" + member + " as field"); } else { throw new UnsupportedOperationException("Implement member" + member); } } private <T extends Annotation> T getAnnotation(Member member, Class<T> annotationClass) { if (member instanceof Method) { Method method = (Method) member; return method.getAnnotation(annotationClass); } else if (member instanceof Field) { Field field = (Field) member; return field.getAnnotation(annotationClass); } else throw new IllegalArgumentException("only methods and fields are allowed"); } private static Member getJavaMember(Class<?> type, String name) { try { Field field = CoreUtils.getField(type, name); field.setAccessible(true); return field; } catch (Exception ignore) { } String methodName = "get" + Character.toUpperCase(name.charAt(0)) + name.substring(1); while (!type.equals(Object.class)) { try { Method method = type.getDeclaredMethod(methodName); method.setAccessible(true); return method; } catch (Exception ignore) { } type = type.getSuperclass(); } return null; } private static EntityType<?> findJPAEntityType( EntityManager em, String jpaEntityTypeName) { for (EntityType<?> et : em.getMetamodel().getEntities()) { if (JPAEdmGenerator.getEntitySetName(et).equals(jpaEntityTypeName)) { return et; } } throw new RuntimeException( "JPA Entity type " + jpaEntityTypeName + " not found"); } private static class DynamicEntitiesResponse { public final Class<?> responseType; public final OProperty<?> property; public final OEntity entity; public final List<OEntity> entities; public final Integer inlineCount; public final String skipToken; public static DynamicEntitiesResponse property(OProperty<?> property){ return new DynamicEntitiesResponse(PropertyResponse.class,property,null,null,null,null); } @SuppressWarnings("unused") // TODO when to call? public static DynamicEntitiesResponse entity(OEntity entity){ return new DynamicEntitiesResponse(EntityResponse.class,null,entity,null,null,null); } public static DynamicEntitiesResponse entities(List<OEntity> entityList,Integer inlineCount,String skipToken){ return new DynamicEntitiesResponse(EntitiesResponse.class,null,null,entityList,inlineCount,skipToken); } private DynamicEntitiesResponse( Class<?> responseType, OProperty<?> property, OEntity entity, List<OEntity> entityList, Integer inlineCount, String skipToken) { this.responseType = responseType; this.property = property; this.entity = entity; this.entities = entityList; this.inlineCount = inlineCount; this.skipToken = skipToken; } } private DynamicEntitiesResponse enumJpaEntities(final Context context, final String navProp) { String alias = "t0"; String from = context.jpaEntityType.getName() + " " + alias; String where = null; Object edmObj = null; if (navProp != null) { where = String.format( "(%s.%s = %s)", alias, context.keyPropertyName, context.typeSafeEntityKey); String prop = null; int propCount = 0; for (String pn : navProp.split("/")) { String[] propSplit = pn.split("\\("); prop = propSplit[0]; propCount++; if (edmObj instanceof EdmProperty) { throw new UnsupportedOperationException( String.format( "The request URI is not valid. Since the segment '%s' " + "refers to a collection, this must be the last segment " + "in the request URI. All intermediate segments must refer " + "to a single resource.", alias)); } edmObj = metadata.findEdmProperty(prop); if (edmObj instanceof EdmNavigationProperty) { EdmNavigationProperty propInfo = (EdmNavigationProperty) edmObj; context.jpaEntityType = findJPAEntityType( context.em, propInfo.toRole.type.name); context.ees = metadata.findEdmEntitySet(JPAEdmGenerator.getEntitySetName(context.jpaEntityType)); prop = alias + "." + prop; alias = "t" + Integer.toString(propCount); from = String.format("%s JOIN %s %s", from, prop, alias); if (propSplit.length > 1) { Object entityKey = OptionsQueryParser.parseIdObject( "(" + propSplit[1]); context.keyPropertyName = JPAEdmGenerator .getId(context.jpaEntityType).getName(); context.typeSafeEntityKey = typeSafeEntityKey( em, context.jpaEntityType, entityKey); where = String.format( "(%s.%s = %s)", alias, context.keyPropertyName, context.typeSafeEntityKey); } } else if (edmObj instanceof EdmProperty) { EdmProperty propInfo = (EdmProperty) edmObj; alias = alias + "." + propInfo.name; // TODO context.ees = null; } if (edmObj == null) { throw new EntityNotFoundException( String.format( "Resource not found for the segment '%s'.", pn)); } } } String jpql = String.format("SELECT %s FROM %s", alias, from); JPQLGenerator jpqlGen = new JPQLGenerator(context.keyPropertyName, alias); if (context.query.filter != null) { String filterPredicate = jpqlGen.toJpql(context.query.filter); where = addWhereExpression(where, filterPredicate, "AND"); } if (context.query.skipToken != null) { String skipPredicate = jpqlGen.toJpql(parseSkipToken(jpqlGen, context.query.orderBy, context.query.skipToken)); where = addWhereExpression(where, skipPredicate, "AND"); } if (where != null) { jpql = String.format("%s WHERE %s", jpql, where); } if (context.query.orderBy != null) { String orders = ""; for (OrderByExpression orderBy : context.query.orderBy) { String field = jpqlGen.toJpql(orderBy.getExpression()); if (orderBy.isAscending()) { orders = orders + field + ","; } else { orders = String.format("%s%s DESC,", orders, field); } } jpql = jpql + " ORDER BY " + orders.substring(0, orders.length() - 1); } - Query tq = em.createQuery(jpql); + Query tq = context.em.createQuery(jpql); Integer inlineCount = context.query.inlineCount == InlineCount.ALLPAGES ? tq.getResultList().size() : null; int queryMaxResult = maxResults; if (context.query.top != null) { if (context.query.top.equals(0)) { return DynamicEntitiesResponse.entities( null, inlineCount, null); } if (context.query.top < maxResults) { queryMaxResult = context.query.top; } } tq = tq.setMaxResults(queryMaxResult + 1); if (context.query.skip != null) { tq = tq.setFirstResult(context.query.skip); } @SuppressWarnings("unchecked") List<Object> results = tq.getResultList(); List<OEntity> entities = new LinkedList<OEntity>(); if (edmObj instanceof EdmProperty) { EdmProperty propInfo = (EdmProperty) edmObj; if (results.size() != 1) throw new RuntimeException("Expected one and only one result for property, found " + results.size()); Object value = results.get(0); OProperty<?> op = OProperties.simple( ((EdmProperty) propInfo).name, ((EdmProperty) propInfo).type, value); return DynamicEntitiesResponse.property(op); } else { entities = Enumerable.create(results) .take(queryMaxResult) .select(new Func1<Object, OEntity>() { public OEntity apply(final Object input) { return makeEntity(context, input); } }).toList(); } boolean useSkipToken = context.query.top != null ? context.query.top > maxResults && results.size() > queryMaxResult : results.size() > queryMaxResult; String skipToken = null; if (useSkipToken) { OEntity last = Enumerable.create(entities).last(); skipToken = createSkipToken(context, last); } return DynamicEntitiesResponse.entities( entities, inlineCount, skipToken); } private static String addWhereExpression( String expression, String nextExpression, String condition) { return expression == null ? nextExpression : String.format( "%s %s %s", expression, condition, nextExpression); } private static String createSkipToken(Context context, OEntity lastEntity) { List<String> values = new LinkedList<String>(); if (context.query.orderBy != null) { for (OrderByExpression ord : context.query.orderBy) { String field = ((EntitySimpleProperty) ord.getExpression()) .getPropertyName(); Object value = lastEntity.getProperty(field).getValue(); if (value instanceof String) { value = "'" + value + "'"; } values.add(value.toString()); } } values.add(lastEntity.getEntityKey().asSingleValue().toString()); return Enumerable.create(values).join(","); } private static BoolCommonExpression parseSkipToken(JPQLGenerator jpqlGen, List<OrderByExpression> orderByList, String skipToken) { if (skipToken == null) { return null; } skipToken = skipToken.replace("'", ""); BoolCommonExpression result = null; if (orderByList == null) { result = Expression.gt( Expression.simpleProperty(jpqlGen.getPrimaryKeyName()), Expression.string(skipToken)); } else { String[] skipTokens = skipToken.split(","); for (int i = 0; i < orderByList.size(); i++) { OrderByExpression exp = orderByList.get(i); StringLiteral value = Expression.string(skipTokens[i]); BoolCommonExpression ordExp = null; if (exp.isAscending()) { ordExp = Expression.ge(exp.getExpression(), value); } else { ordExp = Expression.le(exp.getExpression(), value); } if (result == null) { result = ordExp; } else { result = Expression.and( Expression.boolParen( Expression.or(ordExp, result)), result); } } result = Expression.and( Expression.ne( Expression.simpleProperty(jpqlGen.getPrimaryKeyName()), Expression.string(skipTokens[skipTokens.length - 1])), result); } return result; } private Object createNewJPAEntity( EntityManager em, EntityType<?> jpaEntityType, OEntity oentity, boolean withLinks) { try { Constructor<?> ctor = jpaEntityType.getJavaType() .getDeclaredConstructor(); ctor.setAccessible(true); Object jpaEntity = ctor.newInstance(); applyOProperties(jpaEntityType, oentity.getProperties(), jpaEntity); if (withLinks) { applyOLinks(em, jpaEntityType, oentity.getLinks(), jpaEntity); } return jpaEntity; } catch (Exception e) { throw new RuntimeException(e); } } private void applyOLinks(EntityManager em, EntityType<?> jpaEntityType, List<OLink> links, Object jpaEntity) { try { for (final OLink link : links) { String[] propNameSplit = link.getRelation().split("/"); String propName = propNameSplit[propNameSplit.length - 1]; if (link instanceof ORelatedEntitiesLinkInline) { PluralAttribute<?, ?, ?> att = (PluralAttribute<?, ?, ?>)jpaEntityType.getAttribute(propName); Member member = att.getJavaMember(); EntityType<?> collJpaEntityType = (EntityType<?>)att.getElementType(); OneToMany oneToMany = getAnnotation(member, OneToMany.class); Member backRef = null; if (oneToMany != null && oneToMany.mappedBy() != null && !oneToMany.mappedBy().isEmpty()) { backRef = collJpaEntityType .getAttribute(oneToMany.mappedBy()) .getJavaMember(); } @SuppressWarnings("unchecked") Collection<Object> coll = (Collection<Object>)getValue(jpaEntity, member); for (OEntity oentity : ((ORelatedEntitiesLinkInline)link).getRelatedEntities()) { Object collJpaEntity = createNewJPAEntity(em, collJpaEntityType, oentity, true); if (backRef != null) { setValue(collJpaEntity, backRef, jpaEntity); } em.persist(collJpaEntity); coll.add(collJpaEntity); } } else if (link instanceof ORelatedEntityLinkInline ) { SingularAttribute<?, ?> att = jpaEntityType.getSingularAttribute(propName); Member member = att.getJavaMember(); EntityType<?> relJpaEntityType = (EntityType<?>)att.getType(); Object relJpaEntity = createNewJPAEntity(em, relJpaEntityType, ((ORelatedEntityLinkInline)link).getRelatedEntity(), true); em.persist(relJpaEntity); setValue(jpaEntity, member, relJpaEntity); } else if (link instanceof ORelatedEntityLink ) { SingularAttribute<?, ?> att = jpaEntityType.getSingularAttribute(propName); Member member = att.getJavaMember(); EntityType<?> relJpaEntityType = (EntityType<?>)att.getType(); Object key = typeSafeEntityKey(em, relJpaEntityType, link.getHref()); Object relEntity = em.find(relJpaEntityType.getJavaType(), key); setValue(jpaEntity, member, relEntity); } else { throw new UnsupportedOperationException("binding the new entity to many entities is not supported"); } } } catch (Exception e) { throw new RuntimeException(e); } } private static void applyOProperties(EntityType<?> jpaEntityType, List<OProperty<?>> properties, Object jpaEntity) { try { for (OProperty<?> prop : properties) { // EdmProperty ep = findProperty(ees,prop.getName()); Attribute<?, ?> att = jpaEntityType .getAttribute(prop.getName()); Member member = att.getJavaMember(); if (!(member instanceof Field)) { throw new UnsupportedOperationException("Implement member" + member); } Field field = (Field) member; field.setAccessible(true); Object value = getPropertyValue(prop, field); field.set(jpaEntity, value); } } catch (Exception e) { throw new RuntimeException(e); } } @Override public EntityResponse createEntity(String entitySetName, OEntity entity) { final EdmEntitySet ees = metadata.getEdmEntitySet(entitySetName); EntityManager em = emf.createEntityManager(); try { em.getTransaction().begin(); EntityType<?> jpaEntityType = findJPAEntityType(em, ees.type.name); Object jpaEntity = createNewJPAEntity( em, jpaEntityType, entity, true); em.persist(jpaEntity); em.getTransaction().commit(); // reread the entity in case we had links. This should insure // we get the implicitly set foreign keys. E.g in the Northwind model // creating a new Product with a link to the Category should return // the CategoryID. if (entity.getLinks() != null && !entity.getLinks().isEmpty()) { em.getTransaction().begin(); try { em.refresh(jpaEntity); em.getTransaction().commit(); } finally { if (em.getTransaction().isActive()) em.getTransaction().rollback(); } } final OEntity responseEntity = jpaEntityToOEntity( ees, jpaEntityType, jpaEntity, null, null); return Responses.entity(responseEntity); } finally { em.close(); } } @Override public EntityResponse createEntity(String entitySetName, Object entityKey, final String navProp, OEntity entity) { // get the EdmEntitySet for the parent (fromRole) entity final EdmEntitySet ees = metadata.getEdmEntitySet(entitySetName); // get the navigation property EdmNavigationProperty edmNavProperty = ees.type.getNavigationProperty(navProp); // check whether the navProperty is valid if (edmNavProperty == null || edmNavProperty.toRole.multiplicity != EdmMultiplicity.MANY) { throw new IllegalArgumentException("unknown navigation property " + navProp + " or navigation property toRole Multiplicity is not '*'" ); } EntityManager em = emf.createEntityManager(); try { em.getTransaction().begin(); // get the entity we want the new entity add to EntityType<?> jpaEntityType = findJPAEntityType(em, ees.type.name); Object typeSafeEntityKey = typeSafeEntityKey(em, jpaEntityType, entityKey); Object jpaEntity = em.find(jpaEntityType.getJavaType(), typeSafeEntityKey); // create the new entity EntityType<?> newJpaEntityType = findJPAEntityType(em, edmNavProperty.toRole.type.name); Object newJpaEntity = createNewJPAEntity(em, newJpaEntityType, entity, true); // get the collection attribute and add the new entity to the parent entity @SuppressWarnings({ "rawtypes", "unchecked" }) PluralAttribute attr = Enumerable.create( jpaEntityType.getPluralAttributes()) .firstOrNull(new Predicate1() { @Override public boolean apply(Object input) { PluralAttribute<?, ?, ?> pa = (PluralAttribute<?, ?, ?>)input; System.out.println("pa: " + pa.getName()); return pa.getName().equals(navProp); } }); @SuppressWarnings("unchecked") Collection<Object> collection = (Collection<Object> )getValue(jpaEntity, attr.getJavaMember()); collection.add(newJpaEntity); // TODO handle ManyToMany relationships // set the backreference in bidirectional relationships OneToMany oneToMany = getAnnotation(attr.getJavaMember(), OneToMany.class); if (oneToMany != null && oneToMany.mappedBy() != null && !oneToMany.mappedBy().isEmpty()) { setValue(newJpaEntity, newJpaEntityType .getAttribute(oneToMany.mappedBy()) .getJavaMember(), jpaEntity); } // check whether the EntitManager will persist the // new entity or should we do it if (oneToMany != null && oneToMany.cascade() != null) { List<CascadeType> cascadeTypes = Arrays.asList(oneToMany.cascade()); if (!cascadeTypes.contains(CascadeType.ALL) && !cascadeTypes.contains(CascadeType.PERSIST)) { em.persist(newJpaEntity); } } em.getTransaction().commit(); // prepare the response final EdmEntitySet toRoleees = getMetadata() .getEdmEntitySet(edmNavProperty.toRole.type); final OEntity responseEntity = jpaEntityToOEntity(toRoleees, newJpaEntityType, newJpaEntity, null, null); return Responses.entity(responseEntity); } catch (Exception e) { throw new RuntimeException(e); } finally { em.close(); } } @Override public void deleteEntity(String entitySetName, Object entityKey) { final EdmEntitySet ees = metadata.getEdmEntitySet(entitySetName); EntityManager em = emf.createEntityManager(); try { em.getTransaction().begin(); EntityType<?> jpaEntityType = findJPAEntityType(em, ees.type.name); Object typeSafeEntityKey = typeSafeEntityKey( em, jpaEntityType, entityKey); Object jpaEntity = em.find( jpaEntityType.getJavaType(), typeSafeEntityKey); em.remove(jpaEntity); em.getTransaction().commit(); } finally { em.close(); } } @Override public void mergeEntity(String entitySetName, Object entityKey, OEntity entity) { final EdmEntitySet ees = metadata.getEdmEntitySet(entitySetName); EntityManager em = emf.createEntityManager(); try { em.getTransaction().begin(); EntityType<?> jpaEntityType = findJPAEntityType(em, ees.type.name); Object typeSafeEntityKey = typeSafeEntityKey( em, jpaEntityType, entityKey); Object jpaEntity = em.find( jpaEntityType.getJavaType(), typeSafeEntityKey); applyOProperties(jpaEntityType, entity.getProperties(), jpaEntity); em.getTransaction().commit(); } finally { em.close(); } } @Override public void updateEntity( String entitySetName, Object entityKey, OEntity entity) { final EdmEntitySet ees = metadata.getEdmEntitySet(entitySetName); EntityManager em = emf.createEntityManager(); try { em.getTransaction().begin(); EntityType<?> jpaEntityType = findJPAEntityType(em, ees.type.name); Object jpaEntity = createNewJPAEntity( em, jpaEntityType, entity, true); em.merge(jpaEntity); em.getTransaction().commit(); } finally { em.close(); } } private static Object typeSafeEntityKey( EntityManager em, EntityType<?> jpaEntityType, Object entityKey) { return TypeConverter.convert( entityKey, em.getMetamodel() .entity(jpaEntityType.getJavaType()) .getIdType() .getJavaType()); } private Object typeSafeEntityKey(EntityManager em, EntityType<?> jpaEntityType, String href) throws Exception { String keyString = href.substring(href.lastIndexOf('(') + 1, href.length() - 1); List<Token> keyToken = ExpressionParser.tokenize(keyString); if( keyToken.size() !=0 && ( keyToken.get(0).type == TokenType.QUOTED_STRING || keyToken.get(0).type == TokenType.NUMBER ) ) { Object key; if (keyToken.get(0).type == TokenType.QUOTED_STRING) { String entityKeyStr = keyToken.get(0).value; if (entityKeyStr.length() < 2) { throw new IllegalArgumentException("invalid entity key " + keyToken); } // cut off the quotes key = entityKeyStr.substring(1, entityKeyStr.length() - 1); } else if (keyToken.get(0).type == TokenType.NUMBER) { key = NumberFormat.getInstance(Locale.US) .parseObject(keyToken.get(0).value); } else { throw new IllegalArgumentException( "unsupported key type " + keyString); } return TypeConverter.convert(key, em.getMetamodel() .entity(jpaEntityType.getJavaType()) .getIdType() .getJavaType()); } else { throw new IllegalArgumentException( "only simple entity keys are supported yet"); } } protected static Object getPropertyValue(OProperty<?> prop, Field field) { Object value = prop.getValue(); try { return TypeConverter.convert(value, field.getType()); } catch (UnsupportedOperationException ex) { // let java complain return value; } } }
true
true
private DynamicEntitiesResponse enumJpaEntities(final Context context, final String navProp) { String alias = "t0"; String from = context.jpaEntityType.getName() + " " + alias; String where = null; Object edmObj = null; if (navProp != null) { where = String.format( "(%s.%s = %s)", alias, context.keyPropertyName, context.typeSafeEntityKey); String prop = null; int propCount = 0; for (String pn : navProp.split("/")) { String[] propSplit = pn.split("\\("); prop = propSplit[0]; propCount++; if (edmObj instanceof EdmProperty) { throw new UnsupportedOperationException( String.format( "The request URI is not valid. Since the segment '%s' " + "refers to a collection, this must be the last segment " + "in the request URI. All intermediate segments must refer " + "to a single resource.", alias)); } edmObj = metadata.findEdmProperty(prop); if (edmObj instanceof EdmNavigationProperty) { EdmNavigationProperty propInfo = (EdmNavigationProperty) edmObj; context.jpaEntityType = findJPAEntityType( context.em, propInfo.toRole.type.name); context.ees = metadata.findEdmEntitySet(JPAEdmGenerator.getEntitySetName(context.jpaEntityType)); prop = alias + "." + prop; alias = "t" + Integer.toString(propCount); from = String.format("%s JOIN %s %s", from, prop, alias); if (propSplit.length > 1) { Object entityKey = OptionsQueryParser.parseIdObject( "(" + propSplit[1]); context.keyPropertyName = JPAEdmGenerator .getId(context.jpaEntityType).getName(); context.typeSafeEntityKey = typeSafeEntityKey( em, context.jpaEntityType, entityKey); where = String.format( "(%s.%s = %s)", alias, context.keyPropertyName, context.typeSafeEntityKey); } } else if (edmObj instanceof EdmProperty) { EdmProperty propInfo = (EdmProperty) edmObj; alias = alias + "." + propInfo.name; // TODO context.ees = null; } if (edmObj == null) { throw new EntityNotFoundException( String.format( "Resource not found for the segment '%s'.", pn)); } } } String jpql = String.format("SELECT %s FROM %s", alias, from); JPQLGenerator jpqlGen = new JPQLGenerator(context.keyPropertyName, alias); if (context.query.filter != null) { String filterPredicate = jpqlGen.toJpql(context.query.filter); where = addWhereExpression(where, filterPredicate, "AND"); } if (context.query.skipToken != null) { String skipPredicate = jpqlGen.toJpql(parseSkipToken(jpqlGen, context.query.orderBy, context.query.skipToken)); where = addWhereExpression(where, skipPredicate, "AND"); } if (where != null) { jpql = String.format("%s WHERE %s", jpql, where); } if (context.query.orderBy != null) { String orders = ""; for (OrderByExpression orderBy : context.query.orderBy) { String field = jpqlGen.toJpql(orderBy.getExpression()); if (orderBy.isAscending()) { orders = orders + field + ","; } else { orders = String.format("%s%s DESC,", orders, field); } } jpql = jpql + " ORDER BY " + orders.substring(0, orders.length() - 1); } Query tq = em.createQuery(jpql); Integer inlineCount = context.query.inlineCount == InlineCount.ALLPAGES ? tq.getResultList().size() : null; int queryMaxResult = maxResults; if (context.query.top != null) { if (context.query.top.equals(0)) { return DynamicEntitiesResponse.entities( null, inlineCount, null); } if (context.query.top < maxResults) { queryMaxResult = context.query.top; } } tq = tq.setMaxResults(queryMaxResult + 1); if (context.query.skip != null) { tq = tq.setFirstResult(context.query.skip); } @SuppressWarnings("unchecked") List<Object> results = tq.getResultList(); List<OEntity> entities = new LinkedList<OEntity>(); if (edmObj instanceof EdmProperty) { EdmProperty propInfo = (EdmProperty) edmObj; if (results.size() != 1) throw new RuntimeException("Expected one and only one result for property, found " + results.size()); Object value = results.get(0); OProperty<?> op = OProperties.simple( ((EdmProperty) propInfo).name, ((EdmProperty) propInfo).type, value); return DynamicEntitiesResponse.property(op); } else { entities = Enumerable.create(results) .take(queryMaxResult) .select(new Func1<Object, OEntity>() { public OEntity apply(final Object input) { return makeEntity(context, input); } }).toList(); } boolean useSkipToken = context.query.top != null ? context.query.top > maxResults && results.size() > queryMaxResult : results.size() > queryMaxResult; String skipToken = null; if (useSkipToken) { OEntity last = Enumerable.create(entities).last(); skipToken = createSkipToken(context, last); } return DynamicEntitiesResponse.entities( entities, inlineCount, skipToken); }
private DynamicEntitiesResponse enumJpaEntities(final Context context, final String navProp) { String alias = "t0"; String from = context.jpaEntityType.getName() + " " + alias; String where = null; Object edmObj = null; if (navProp != null) { where = String.format( "(%s.%s = %s)", alias, context.keyPropertyName, context.typeSafeEntityKey); String prop = null; int propCount = 0; for (String pn : navProp.split("/")) { String[] propSplit = pn.split("\\("); prop = propSplit[0]; propCount++; if (edmObj instanceof EdmProperty) { throw new UnsupportedOperationException( String.format( "The request URI is not valid. Since the segment '%s' " + "refers to a collection, this must be the last segment " + "in the request URI. All intermediate segments must refer " + "to a single resource.", alias)); } edmObj = metadata.findEdmProperty(prop); if (edmObj instanceof EdmNavigationProperty) { EdmNavigationProperty propInfo = (EdmNavigationProperty) edmObj; context.jpaEntityType = findJPAEntityType( context.em, propInfo.toRole.type.name); context.ees = metadata.findEdmEntitySet(JPAEdmGenerator.getEntitySetName(context.jpaEntityType)); prop = alias + "." + prop; alias = "t" + Integer.toString(propCount); from = String.format("%s JOIN %s %s", from, prop, alias); if (propSplit.length > 1) { Object entityKey = OptionsQueryParser.parseIdObject( "(" + propSplit[1]); context.keyPropertyName = JPAEdmGenerator .getId(context.jpaEntityType).getName(); context.typeSafeEntityKey = typeSafeEntityKey( em, context.jpaEntityType, entityKey); where = String.format( "(%s.%s = %s)", alias, context.keyPropertyName, context.typeSafeEntityKey); } } else if (edmObj instanceof EdmProperty) { EdmProperty propInfo = (EdmProperty) edmObj; alias = alias + "." + propInfo.name; // TODO context.ees = null; } if (edmObj == null) { throw new EntityNotFoundException( String.format( "Resource not found for the segment '%s'.", pn)); } } } String jpql = String.format("SELECT %s FROM %s", alias, from); JPQLGenerator jpqlGen = new JPQLGenerator(context.keyPropertyName, alias); if (context.query.filter != null) { String filterPredicate = jpqlGen.toJpql(context.query.filter); where = addWhereExpression(where, filterPredicate, "AND"); } if (context.query.skipToken != null) { String skipPredicate = jpqlGen.toJpql(parseSkipToken(jpqlGen, context.query.orderBy, context.query.skipToken)); where = addWhereExpression(where, skipPredicate, "AND"); } if (where != null) { jpql = String.format("%s WHERE %s", jpql, where); } if (context.query.orderBy != null) { String orders = ""; for (OrderByExpression orderBy : context.query.orderBy) { String field = jpqlGen.toJpql(orderBy.getExpression()); if (orderBy.isAscending()) { orders = orders + field + ","; } else { orders = String.format("%s%s DESC,", orders, field); } } jpql = jpql + " ORDER BY " + orders.substring(0, orders.length() - 1); } Query tq = context.em.createQuery(jpql); Integer inlineCount = context.query.inlineCount == InlineCount.ALLPAGES ? tq.getResultList().size() : null; int queryMaxResult = maxResults; if (context.query.top != null) { if (context.query.top.equals(0)) { return DynamicEntitiesResponse.entities( null, inlineCount, null); } if (context.query.top < maxResults) { queryMaxResult = context.query.top; } } tq = tq.setMaxResults(queryMaxResult + 1); if (context.query.skip != null) { tq = tq.setFirstResult(context.query.skip); } @SuppressWarnings("unchecked") List<Object> results = tq.getResultList(); List<OEntity> entities = new LinkedList<OEntity>(); if (edmObj instanceof EdmProperty) { EdmProperty propInfo = (EdmProperty) edmObj; if (results.size() != 1) throw new RuntimeException("Expected one and only one result for property, found " + results.size()); Object value = results.get(0); OProperty<?> op = OProperties.simple( ((EdmProperty) propInfo).name, ((EdmProperty) propInfo).type, value); return DynamicEntitiesResponse.property(op); } else { entities = Enumerable.create(results) .take(queryMaxResult) .select(new Func1<Object, OEntity>() { public OEntity apply(final Object input) { return makeEntity(context, input); } }).toList(); } boolean useSkipToken = context.query.top != null ? context.query.top > maxResults && results.size() > queryMaxResult : results.size() > queryMaxResult; String skipToken = null; if (useSkipToken) { OEntity last = Enumerable.create(entities).last(); skipToken = createSkipToken(context, last); } return DynamicEntitiesResponse.entities( entities, inlineCount, skipToken); }
diff --git a/shell/core/src/main/java/org/crsh/text/ui/TableRenderer.java b/shell/core/src/main/java/org/crsh/text/ui/TableRenderer.java index 31f9ec62..795a36bd 100644 --- a/shell/core/src/main/java/org/crsh/text/ui/TableRenderer.java +++ b/shell/core/src/main/java/org/crsh/text/ui/TableRenderer.java @@ -1,378 +1,378 @@ /* * Copyright (C) 2012 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.crsh.text.ui; import org.crsh.text.LineReader; import org.crsh.text.RenderAppendable; import org.crsh.text.Renderer; import org.crsh.text.Style; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; class TableRenderer extends Renderer { /** . */ final Layout columnLayout; /** . */ final Layout rowLayout; /** . */ final BorderStyle border; /** . */ final BorderStyle separator; /** . */ final Overflow overflow; /** . */ final Style.Composite style; /** Cell padding left. */ final int leftCellPadding; /** Cell padding right. */ final int rightCellPadding; /** . */ private TableRowRenderer head; /** . */ private TableRowRenderer tail; TableRenderer(TableElement table) { this.rowLayout = table.getRowLayout(); this.columnLayout = table.getColumnLayout(); this.border = table.getBorder(); this.style = table.getStyle(); this.separator = table.getSeparator(); this.overflow = table.getOverflow(); this.leftCellPadding = table.getLeftCellPadding(); this.rightCellPadding = table.getRightCellPadding(); // for (RowElement row : table.getRows()) { if (head == null) { head = tail = new TableRowRenderer(this, row); } else { tail = tail.add(new TableRowRenderer(this, row)); } } } private int getMaxColSize() { int n = 0; for (TableRowRenderer row = head;row != null;row = row.next()) { n = Math.max(n, row.getColsSize()); } return n; } @Override public int getMinWidth() { int minWidth = 0; for (TableRowRenderer row = head;row != null;row = row.next()) { minWidth = Math.max(minWidth, row.getMinWidth()); } return minWidth + (border != null ? 2 : 0); } @Override public int getActualWidth() { int actualWidth = 0; for (TableRowRenderer row = head;row != null;row = row.next()) { actualWidth = Math.max(actualWidth, row.getActualWidth()); } return actualWidth + (border != null ? 2 : 0); } @Override public int getActualHeight(int width) { if (border != null) { width -= 2; } int actualHeight = 0; for (TableRowRenderer row = head;row != null;row = row.next()) { actualHeight += row.getActualHeight(width); } if (border != null) { actualHeight += 2; } return actualHeight; } @Override public int getMinHeight(int width) { return border != null ? 2 : 0; } @Override public LineReader reader(int width) { return reader(width, 0); } @Override public LineReader reader(final int width, final int height) { int len = getMaxColSize(); int[] eltWidths = new int[len]; int[] eltMinWidths = new int[len]; // Compute each column as is for (TableRowRenderer row = head;row != null;row = row.next()) { for (int i = 0;i < row.getCols().size();i++) { Renderer renderable = row.getCols().get(i); eltWidths[i] = Math.max(eltWidths[i], renderable.getActualWidth() + row.row.leftCellPadding + row.row.rightCellPadding); - eltMinWidths[i] = Math.max(eltMinWidths[i], renderable.getMinWidth()) + row.row.leftCellPadding + row.row.rightCellPadding; + eltMinWidths[i] = Math.max(eltMinWidths[i], renderable.getMinWidth() + row.row.leftCellPadding + row.row.rightCellPadding); } } // Note that we may have a different widths != eltWidths according to the layout algorithm final int[] widths = columnLayout.compute(separator != null, width - (border != null ? 2 : 0), eltWidths, eltMinWidths); // if (widths != null) { // Compute new widths array final AtomicInteger effectiveWidth = new AtomicInteger(); if (border != null) { effectiveWidth.addAndGet(2); } for (int i = 0;i < widths.length;i++) { effectiveWidth.addAndGet(widths[i]); if (separator != null) { if (i > 0) { effectiveWidth.addAndGet(1); } } } // final int[] heights; if (height > 0) { // Apply vertical layout int size = tail.getSize(); int[] actualHeights = new int[size]; int[] minHeights = new int[size]; for (TableRowRenderer row = head;row != null;row = row.next()) { actualHeights[row.getIndex()] = row.getActualHeight(widths); minHeights[row.getIndex()] = row.getMinHeight(widths); } heights = rowLayout.compute(false, height - (border != null ? 2 : 0), actualHeights, minHeights); if (heights == null) { return null; } } else { heights = new int[tail.getSize()]; Arrays.fill(heights, -1); } // return new LineReader() { /** . */ TableRowReader rHead = null; /** . */ TableRowReader rTail = null; /** . */ int index = 0; /** * 0 -> render top * 1 -> render rows * 2 -> render bottom * 3 -> done */ int status = border != null ? 0 : 1; { // Add all rows for (TableRowRenderer row = head;row != null;row = row.next()) { if (row.getIndex() < heights.length) { int[] what; if (row.getColsSize() == widths.length) { what = widths; } else { // I'm not sure this algorithm is great // perhaps the space should be computed or some kind of merge // that respect the columns should be done // Redistribute space among columns what = new int[row.getColsSize()]; for (int j = 0;j < widths.length;j++) { what[j % what.length] += widths[j]; } // Remove zero length columns to avoid issues int end = what.length; while (end > 0 && what[end - 1] == 0) { end--; } // if (end != what.length) { what = Arrays.copyOf(what, end); } } TableRowReader next = row.renderer(what, heights[row.getIndex()]); if (rHead == null) { rHead = rTail = next; } else { rTail = rTail.add(next); } } else { break; } } } public boolean hasLine() { switch (status) { case 0: case 2: return true; case 1: while (rHead != null) { if (rHead.hasLine()) { return true; } else { rHead = rHead.next(); } } // Update status according to height if (height > 0) { if (border == null) { if (index == height) { status = 3; } } else { if (index == height - 1) { status = 2; } } } else { if (border != null) { status = 2; } else { status = 3; } } // return status < 3; default: return false; } } public void renderLine(RenderAppendable to) { if (!hasLine()) { throw new IllegalStateException(); } switch (status) { case 0: case 2: { to.styleOff(); to.append(border.corner); for (int i = 0;i < widths.length;i++) { if (widths[i] > 0) { if (separator != null && i > 0) { to.append(border.horizontal); } for (int j = 0;j < widths[i];j++) { to.append(border.horizontal); } } } to.append(border.corner); to.styleOn(); for (int i = width - effectiveWidth.get();i > 0;i--) { to.append(' '); } status++; break; } case 1: { // boolean sep = rHead != null && rHead.isSeparator(); if (border != null) { to.styleOff(); to.append(sep ? border.corner : border.vertical); to.styleOn(); } // if (style != null) { to.enterStyle(style); } // if (rHead != null) { // Render row rHead.renderLine(to); } else { // Vertical padding for (int i = 0;i < widths.length;i++) { if (separator != null && i > 0) { to.append(separator.vertical); } for (int j = 0;j < widths[i];j++) { to.append(' '); } } } // if (style != null) { to.leaveStyle(); } // if (border != null) { to.styleOff(); to.append(sep ? border.corner : border.vertical); to.styleOn(); } // Padding for (int i = width - effectiveWidth.get();i > 0;i--) { to.append(' '); } break; } default: throw new AssertionError(); } // Increase vertical index index++; } }; } else { return Renderer.NULL.reader(width); } } }
true
true
public LineReader reader(final int width, final int height) { int len = getMaxColSize(); int[] eltWidths = new int[len]; int[] eltMinWidths = new int[len]; // Compute each column as is for (TableRowRenderer row = head;row != null;row = row.next()) { for (int i = 0;i < row.getCols().size();i++) { Renderer renderable = row.getCols().get(i); eltWidths[i] = Math.max(eltWidths[i], renderable.getActualWidth() + row.row.leftCellPadding + row.row.rightCellPadding); eltMinWidths[i] = Math.max(eltMinWidths[i], renderable.getMinWidth()) + row.row.leftCellPadding + row.row.rightCellPadding; } } // Note that we may have a different widths != eltWidths according to the layout algorithm final int[] widths = columnLayout.compute(separator != null, width - (border != null ? 2 : 0), eltWidths, eltMinWidths); // if (widths != null) { // Compute new widths array final AtomicInteger effectiveWidth = new AtomicInteger(); if (border != null) { effectiveWidth.addAndGet(2); } for (int i = 0;i < widths.length;i++) { effectiveWidth.addAndGet(widths[i]); if (separator != null) { if (i > 0) { effectiveWidth.addAndGet(1); } } } // final int[] heights; if (height > 0) { // Apply vertical layout int size = tail.getSize(); int[] actualHeights = new int[size]; int[] minHeights = new int[size]; for (TableRowRenderer row = head;row != null;row = row.next()) { actualHeights[row.getIndex()] = row.getActualHeight(widths); minHeights[row.getIndex()] = row.getMinHeight(widths); } heights = rowLayout.compute(false, height - (border != null ? 2 : 0), actualHeights, minHeights); if (heights == null) { return null; } } else { heights = new int[tail.getSize()]; Arrays.fill(heights, -1); } // return new LineReader() { /** . */ TableRowReader rHead = null; /** . */ TableRowReader rTail = null; /** . */ int index = 0; /** * 0 -> render top * 1 -> render rows * 2 -> render bottom * 3 -> done */ int status = border != null ? 0 : 1; { // Add all rows for (TableRowRenderer row = head;row != null;row = row.next()) { if (row.getIndex() < heights.length) { int[] what; if (row.getColsSize() == widths.length) { what = widths; } else { // I'm not sure this algorithm is great // perhaps the space should be computed or some kind of merge // that respect the columns should be done // Redistribute space among columns what = new int[row.getColsSize()]; for (int j = 0;j < widths.length;j++) { what[j % what.length] += widths[j]; } // Remove zero length columns to avoid issues int end = what.length; while (end > 0 && what[end - 1] == 0) { end--; } // if (end != what.length) { what = Arrays.copyOf(what, end); } } TableRowReader next = row.renderer(what, heights[row.getIndex()]); if (rHead == null) { rHead = rTail = next; } else { rTail = rTail.add(next); } } else { break; } } } public boolean hasLine() { switch (status) { case 0: case 2: return true; case 1: while (rHead != null) { if (rHead.hasLine()) { return true; } else { rHead = rHead.next(); } } // Update status according to height if (height > 0) { if (border == null) { if (index == height) { status = 3; } } else { if (index == height - 1) { status = 2; } } } else { if (border != null) { status = 2; } else { status = 3; } } // return status < 3; default: return false; } } public void renderLine(RenderAppendable to) { if (!hasLine()) { throw new IllegalStateException(); } switch (status) { case 0: case 2: { to.styleOff(); to.append(border.corner); for (int i = 0;i < widths.length;i++) { if (widths[i] > 0) { if (separator != null && i > 0) { to.append(border.horizontal); } for (int j = 0;j < widths[i];j++) { to.append(border.horizontal); } } } to.append(border.corner); to.styleOn(); for (int i = width - effectiveWidth.get();i > 0;i--) { to.append(' '); } status++; break; } case 1: { // boolean sep = rHead != null && rHead.isSeparator(); if (border != null) { to.styleOff(); to.append(sep ? border.corner : border.vertical); to.styleOn(); } // if (style != null) { to.enterStyle(style); } // if (rHead != null) { // Render row rHead.renderLine(to); } else { // Vertical padding for (int i = 0;i < widths.length;i++) { if (separator != null && i > 0) { to.append(separator.vertical); } for (int j = 0;j < widths[i];j++) { to.append(' '); } } } // if (style != null) { to.leaveStyle(); } // if (border != null) { to.styleOff(); to.append(sep ? border.corner : border.vertical); to.styleOn(); } // Padding for (int i = width - effectiveWidth.get();i > 0;i--) { to.append(' '); } break; } default: throw new AssertionError(); } // Increase vertical index index++; } }; } else { return Renderer.NULL.reader(width); } }
public LineReader reader(final int width, final int height) { int len = getMaxColSize(); int[] eltWidths = new int[len]; int[] eltMinWidths = new int[len]; // Compute each column as is for (TableRowRenderer row = head;row != null;row = row.next()) { for (int i = 0;i < row.getCols().size();i++) { Renderer renderable = row.getCols().get(i); eltWidths[i] = Math.max(eltWidths[i], renderable.getActualWidth() + row.row.leftCellPadding + row.row.rightCellPadding); eltMinWidths[i] = Math.max(eltMinWidths[i], renderable.getMinWidth() + row.row.leftCellPadding + row.row.rightCellPadding); } } // Note that we may have a different widths != eltWidths according to the layout algorithm final int[] widths = columnLayout.compute(separator != null, width - (border != null ? 2 : 0), eltWidths, eltMinWidths); // if (widths != null) { // Compute new widths array final AtomicInteger effectiveWidth = new AtomicInteger(); if (border != null) { effectiveWidth.addAndGet(2); } for (int i = 0;i < widths.length;i++) { effectiveWidth.addAndGet(widths[i]); if (separator != null) { if (i > 0) { effectiveWidth.addAndGet(1); } } } // final int[] heights; if (height > 0) { // Apply vertical layout int size = tail.getSize(); int[] actualHeights = new int[size]; int[] minHeights = new int[size]; for (TableRowRenderer row = head;row != null;row = row.next()) { actualHeights[row.getIndex()] = row.getActualHeight(widths); minHeights[row.getIndex()] = row.getMinHeight(widths); } heights = rowLayout.compute(false, height - (border != null ? 2 : 0), actualHeights, minHeights); if (heights == null) { return null; } } else { heights = new int[tail.getSize()]; Arrays.fill(heights, -1); } // return new LineReader() { /** . */ TableRowReader rHead = null; /** . */ TableRowReader rTail = null; /** . */ int index = 0; /** * 0 -> render top * 1 -> render rows * 2 -> render bottom * 3 -> done */ int status = border != null ? 0 : 1; { // Add all rows for (TableRowRenderer row = head;row != null;row = row.next()) { if (row.getIndex() < heights.length) { int[] what; if (row.getColsSize() == widths.length) { what = widths; } else { // I'm not sure this algorithm is great // perhaps the space should be computed or some kind of merge // that respect the columns should be done // Redistribute space among columns what = new int[row.getColsSize()]; for (int j = 0;j < widths.length;j++) { what[j % what.length] += widths[j]; } // Remove zero length columns to avoid issues int end = what.length; while (end > 0 && what[end - 1] == 0) { end--; } // if (end != what.length) { what = Arrays.copyOf(what, end); } } TableRowReader next = row.renderer(what, heights[row.getIndex()]); if (rHead == null) { rHead = rTail = next; } else { rTail = rTail.add(next); } } else { break; } } } public boolean hasLine() { switch (status) { case 0: case 2: return true; case 1: while (rHead != null) { if (rHead.hasLine()) { return true; } else { rHead = rHead.next(); } } // Update status according to height if (height > 0) { if (border == null) { if (index == height) { status = 3; } } else { if (index == height - 1) { status = 2; } } } else { if (border != null) { status = 2; } else { status = 3; } } // return status < 3; default: return false; } } public void renderLine(RenderAppendable to) { if (!hasLine()) { throw new IllegalStateException(); } switch (status) { case 0: case 2: { to.styleOff(); to.append(border.corner); for (int i = 0;i < widths.length;i++) { if (widths[i] > 0) { if (separator != null && i > 0) { to.append(border.horizontal); } for (int j = 0;j < widths[i];j++) { to.append(border.horizontal); } } } to.append(border.corner); to.styleOn(); for (int i = width - effectiveWidth.get();i > 0;i--) { to.append(' '); } status++; break; } case 1: { // boolean sep = rHead != null && rHead.isSeparator(); if (border != null) { to.styleOff(); to.append(sep ? border.corner : border.vertical); to.styleOn(); } // if (style != null) { to.enterStyle(style); } // if (rHead != null) { // Render row rHead.renderLine(to); } else { // Vertical padding for (int i = 0;i < widths.length;i++) { if (separator != null && i > 0) { to.append(separator.vertical); } for (int j = 0;j < widths[i];j++) { to.append(' '); } } } // if (style != null) { to.leaveStyle(); } // if (border != null) { to.styleOff(); to.append(sep ? border.corner : border.vertical); to.styleOn(); } // Padding for (int i = width - effectiveWidth.get();i > 0;i--) { to.append(' '); } break; } default: throw new AssertionError(); } // Increase vertical index index++; } }; } else { return Renderer.NULL.reader(width); } }
diff --git a/src/com/android/browser/GoogleAccountLogin.java b/src/com/android/browser/GoogleAccountLogin.java index 04b39575..855c407b 100644 --- a/src/com/android/browser/GoogleAccountLogin.java +++ b/src/com/android/browser/GoogleAccountLogin.java @@ -1,216 +1,232 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.browser; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpPost; import org.apache.http.util.EntityUtils; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.net.http.AndroidHttpClient; import android.net.Uri; import android.os.Bundle; import android.webkit.CookieManager; import android.webkit.WebView; import android.webkit.WebViewClient; import java.util.StringTokenizer; public class GoogleAccountLogin extends Thread implements AccountManagerCallback<Bundle>, OnCancelListener { // Url for issuing the uber token. private Uri ISSUE_AUTH_TOKEN_URL = Uri.parse( "https://www.google.com/accounts/IssueAuthToken?service=gaia&Session=false"); // Url for signing into a particular service. private final static Uri TOKEN_AUTH_URL = Uri.parse( "https://www.google.com/accounts/TokenAuth"); // Google account type private final static String GOOGLE = "com.google"; private final Activity mActivity; private final Account mAccount; private final WebView mWebView; private Runnable mRunnable; // SID and LSID retrieval process. private String mSid; private String mLsid; private int mState; // {NONE(0), SID(1), LSID(2)} GoogleAccountLogin(Activity activity, String name) { mActivity = activity; mAccount = new Account(name, GOOGLE); mWebView = new WebView(mActivity); mWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return false; } @Override public void onPageFinished(WebView view, String url) { done(); } }); } // Thread @Override public void run() { String url = ISSUE_AUTH_TOKEN_URL.buildUpon() .appendQueryParameter("SID", mSid) .appendQueryParameter("LSID", mLsid) .build().toString(); + // Check mRunnable to see if the request has been canceled. Otherwise + // we might access a destroyed WebView. + String ua = null; + synchronized (this) { + if (mRunnable == null) { + return; + } + ua = mWebView.getSettings().getUserAgentString(); + } // Intentionally not using Proxy. - AndroidHttpClient client = AndroidHttpClient.newInstance( - mWebView.getSettings().getUserAgentString()); + AndroidHttpClient client = AndroidHttpClient.newInstance(ua); HttpPost request = new HttpPost(url); String result = null; try { HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { done(); return; } HttpEntity entity = response.getEntity(); if (entity == null) { done(); return; } result = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { request.abort(); done(); return; } finally { client.close(); } final String newUrl = TOKEN_AUTH_URL.buildUpon() .appendQueryParameter("source", "android-browser") .appendQueryParameter("auth", result) .appendQueryParameter("continue", BrowserSettings.getFactoryResetHomeUrl(mActivity)) .build().toString(); mActivity.runOnUiThread(new Runnable() { @Override public void run() { - mWebView.loadUrl(newUrl); + // Check mRunnable in case the request has been canceled. This + // is most likely not necessary as run() is the only non-UI + // thread that calls done() but I am paranoid. + synchronized (GoogleAccountLogin.this) { + if (mRunnable == null) { + return; + } + mWebView.loadUrl(newUrl); + } } }); } // AccountManager callbacks. @Override public void run(AccountManagerFuture<Bundle> value) { try { String id = value.getResult().getString( AccountManager.KEY_AUTHTOKEN); switch (mState) { default: case 0: throw new IllegalStateException( "Impossible to get into this state"); case 1: mSid = id; mState = 2; // LSID AccountManager.get(mActivity).getAuthToken( mAccount, "LSID", null, mActivity, this, null); break; case 2: mLsid = id; this.start(); break; } } catch (Exception e) { // For all exceptions load the original signin page. // TODO: toast login failed? done(); } } public void startLogin(Runnable runnable) { mRunnable = runnable; mState = 1; // SID AccountManager.get(mActivity).getAuthToken( mAccount, "SID", null, mActivity, this, null); } // Returns the account name passed in if the account exists, otherwise // returns the default account. public static String validateAccount(Context ctx, String name) { Account[] accounts = getAccounts(ctx); if (accounts.length == 0) { return null; } if (name != null) { // Make sure the account still exists. for (Account a : accounts) { if (a.name.equals(name)) { return name; } } } // Return the first entry. return accounts[0].name; } public static Account[] getAccounts(Context ctx) { return AccountManager.get(ctx).getAccountsByType(GOOGLE); } // Checks for the presence of the SID cookie on google.com. public static boolean isLoggedIn() { String cookies = CookieManager.getInstance().getCookie( "http://www.google.com"); if (cookies != null) { StringTokenizer tokenizer = new StringTokenizer(cookies, ";"); while (tokenizer.hasMoreTokens()) { String cookie = tokenizer.nextToken().trim(); if (cookie.startsWith("SID=")) { return true; } } } return false; } // Used to indicate that the Browser should continue loading the main page. // This can happen on success, error, or timeout. private synchronized void done() { if (mRunnable != null) { mActivity.runOnUiThread(mRunnable); mRunnable = null; mWebView.destroy(); } } // Called by the progress dialog on startup. public void onCancel(DialogInterface unused) { done(); } }
false
true
public void run() { String url = ISSUE_AUTH_TOKEN_URL.buildUpon() .appendQueryParameter("SID", mSid) .appendQueryParameter("LSID", mLsid) .build().toString(); // Intentionally not using Proxy. AndroidHttpClient client = AndroidHttpClient.newInstance( mWebView.getSettings().getUserAgentString()); HttpPost request = new HttpPost(url); String result = null; try { HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { done(); return; } HttpEntity entity = response.getEntity(); if (entity == null) { done(); return; } result = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { request.abort(); done(); return; } finally { client.close(); } final String newUrl = TOKEN_AUTH_URL.buildUpon() .appendQueryParameter("source", "android-browser") .appendQueryParameter("auth", result) .appendQueryParameter("continue", BrowserSettings.getFactoryResetHomeUrl(mActivity)) .build().toString(); mActivity.runOnUiThread(new Runnable() { @Override public void run() { mWebView.loadUrl(newUrl); } }); }
public void run() { String url = ISSUE_AUTH_TOKEN_URL.buildUpon() .appendQueryParameter("SID", mSid) .appendQueryParameter("LSID", mLsid) .build().toString(); // Check mRunnable to see if the request has been canceled. Otherwise // we might access a destroyed WebView. String ua = null; synchronized (this) { if (mRunnable == null) { return; } ua = mWebView.getSettings().getUserAgentString(); } // Intentionally not using Proxy. AndroidHttpClient client = AndroidHttpClient.newInstance(ua); HttpPost request = new HttpPost(url); String result = null; try { HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { done(); return; } HttpEntity entity = response.getEntity(); if (entity == null) { done(); return; } result = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { request.abort(); done(); return; } finally { client.close(); } final String newUrl = TOKEN_AUTH_URL.buildUpon() .appendQueryParameter("source", "android-browser") .appendQueryParameter("auth", result) .appendQueryParameter("continue", BrowserSettings.getFactoryResetHomeUrl(mActivity)) .build().toString(); mActivity.runOnUiThread(new Runnable() { @Override public void run() { // Check mRunnable in case the request has been canceled. This // is most likely not necessary as run() is the only non-UI // thread that calls done() but I am paranoid. synchronized (GoogleAccountLogin.this) { if (mRunnable == null) { return; } mWebView.loadUrl(newUrl); } } }); }
diff --git a/abtest-sample/src/main/java/com/dianping/abtest/sample/IPDistributionStrategy.java b/abtest-sample/src/main/java/com/dianping/abtest/sample/IPDistributionStrategy.java index ca2b413cb..dc8b67637 100644 --- a/abtest-sample/src/main/java/com/dianping/abtest/sample/IPDistributionStrategy.java +++ b/abtest-sample/src/main/java/com/dianping/abtest/sample/IPDistributionStrategy.java @@ -1,62 +1,62 @@ package com.dianping.abtest.sample; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.unidal.helper.Splitters; import org.unidal.lookup.util.StringUtils; import com.dianping.cat.abtest.spi.ABTestContext; import com.dianping.cat.abtest.spi.ABTestEntity; import com.dianping.cat.abtest.spi.ABTestGroupStrategy; public class IPDistributionStrategy implements ABTestGroupStrategy { public static final String ID = "ip-distribution"; public IPDistributionStrategy(){ System.out.println("new " + ID + " created"); } @Override public void apply(ABTestContext ctx) { ABTestEntity entity = ctx.getEntity(); String config = entity.getGroupStrategyConfiguration(); List<String> ips = Splitters.by(',').trim().split(config); HttpServletRequest req = ctx.getHttpServletRequest(); String address = getRemoteAddr(req); for (String ip : ips) { if (ip.equals(address)) { ctx.setGroupName("A"); return; } } } public String getRemoteAddr(HttpServletRequest req) { String ip = req.getHeader("X-Forwarded-For"); if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getHeader("Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getHeader("HTTP_CLIENT_IP"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getHeader("HTTP_X_FORWARDED_FOR"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getRemoteAddr(); - if(ip.equals("127.0.0.1")){ + if(ip.equals("127.0.0.1") && ip.startsWith("0:0:0:0:0:0:0:1")){ ip = IPUtils.getFirstNoLoopbackIP4Address(); } } return ip; } }
true
true
public String getRemoteAddr(HttpServletRequest req) { String ip = req.getHeader("X-Forwarded-For"); if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getHeader("Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getHeader("HTTP_CLIENT_IP"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getHeader("HTTP_X_FORWARDED_FOR"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getRemoteAddr(); if(ip.equals("127.0.0.1")){ ip = IPUtils.getFirstNoLoopbackIP4Address(); } } return ip; }
public String getRemoteAddr(HttpServletRequest req) { String ip = req.getHeader("X-Forwarded-For"); if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getHeader("Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getHeader("HTTP_CLIENT_IP"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getHeader("HTTP_X_FORWARDED_FOR"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = req.getRemoteAddr(); if(ip.equals("127.0.0.1") && ip.startsWith("0:0:0:0:0:0:0:1")){ ip = IPUtils.getFirstNoLoopbackIP4Address(); } } return ip; }
diff --git a/GLWallpaperTest/src/com/glwallpaperservice/testing/wallpapers/nehe/lesson08/objects/Cube.java b/GLWallpaperTest/src/com/glwallpaperservice/testing/wallpapers/nehe/lesson08/objects/Cube.java index f7d5bd9..8d63e70 100644 --- a/GLWallpaperTest/src/com/glwallpaperservice/testing/wallpapers/nehe/lesson08/objects/Cube.java +++ b/GLWallpaperTest/src/com/glwallpaperservice/testing/wallpapers/nehe/lesson08/objects/Cube.java @@ -1,323 +1,323 @@ package com.glwallpaperservice.testing.wallpapers.nehe.lesson08.objects; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import net.markguerra.android.glwallpapertest.R; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLUtils; /** * This class is an object representation of * a Cube containing the vertex information, * texture coordinates, the vertex indices * and drawing functionality, which is called * by the renderer. * * @author Savas Ziplies (nea/INsanityDesign) */ public class Cube { /** The buffer holding the vertices */ private FloatBuffer vertexBuffer; /** The buffer holding the texture coordinates */ private FloatBuffer textureBuffer; /** The buffer holding the indices */ private ByteBuffer indexBuffer; /** The buffer holding the normals */ private FloatBuffer normalBuffer; /** Our texture pointer */ private int[] textures = new int[3]; /** The initial vertex definition */ private float vertices[] = { // Vertices according to faces -1.0f, -1.0f, 1.0f, //v0 1.0f, -1.0f, 1.0f, //v1 -1.0f, 1.0f, 1.0f, //v2 1.0f, 1.0f, 1.0f, //v3 1.0f, -1.0f, 1.0f, //... 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, }; /** The initial normals for the lighting calculations */ private float normals[] = { //Normals 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, }; /** The initial texture coordinates (u, v) */ private float texture[] = { //Mapping coordinates for the vertices 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, }; /** The initial indices definition */ private byte indices[] = { // Faces definition 0, 1, 3, 0, 3, 2, // Face front 4, 5, 7, 4, 7, 6, // Face right 8, 9, 11, 8, 11, 10, // ... 12, 13, 15, 12, 15, 14, 16, 17, 19, 16, 19, 18, 20, 21, 23, 20, 23, 22, }; /** * The Cube constructor. * * Initiate the buffers. */ public Cube() { // ByteBuffer byteBuf = ByteBuffer.allocateDirect(vertices.length * 4); byteBuf.order(ByteOrder.nativeOrder()); vertexBuffer = byteBuf.asFloatBuffer(); vertexBuffer.put(vertices); vertexBuffer.position(0); // byteBuf = ByteBuffer.allocateDirect(texture.length * 4); byteBuf.order(ByteOrder.nativeOrder()); textureBuffer = byteBuf.asFloatBuffer(); textureBuffer.put(texture); textureBuffer.position(0); // byteBuf = ByteBuffer.allocateDirect(normals.length * 4); byteBuf.order(ByteOrder.nativeOrder()); normalBuffer = byteBuf.asFloatBuffer(); normalBuffer.put(normals); normalBuffer.position(0); // indexBuffer = ByteBuffer.allocateDirect(indices.length); indexBuffer.put(indices); indexBuffer.position(0); } /** * The object own drawing function. * Called from the renderer to redraw this instance * with possible changes in values. * * @param gl - The GL Context * @param filter - Which texture filter to be used */ public void draw(GL10 gl, int filter) { //Bind the texture according to the set texture filter gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[filter]); //Enable the vertex, texture and normal state gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); //Set the face rotation gl.glFrontFace(GL10.GL_CCW); //Point to our buffers gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer); gl.glNormalPointer(GL10.GL_FLOAT, 0, normalBuffer); //Draw the vertices as triangles, based on the Index Buffer information gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, GL10.GL_UNSIGNED_BYTE, indexBuffer); //Disable the client state before leaving gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisableClientState(GL10.GL_NORMAL_ARRAY); } /** * Load the textures * * @param gl - The GL Context * @param context - The Activity context */ public void loadGLTexture(GL10 gl, Context context) { //Get the texture from the Android resource directory - InputStream is = context.getResources().openRawResource(R.drawable.android); + InputStream is = context.getResources().openRawResource(R.drawable.nehe_android); Bitmap bitmap = null; try { //BitmapFactory is an Android graphics utility for images bitmap = BitmapFactory.decodeStream(is); } finally { //Always clear and close try { is.close(); is = null; } catch (IOException e) { } } //Generate there texture pointer gl.glGenTextures(3, textures, 0); //Create Nearest Filtered Texture and bind it to texture 0 gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); //Create Linear Filtered Texture and bind it to texture 1 gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[1]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); //Create mipmapped textures and bind it to texture 2 gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[2]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_NEAREST); /* * This is a change to the original tutorial, as buildMipMap does not exist anymore * in the Android SDK. * * We check if the GL context is version 1.1 and generate MipMaps by flag. * Otherwise we call our own buildMipMap implementation */ if(gl instanceof GL11) { gl.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_GENERATE_MIPMAP, GL11.GL_TRUE); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); // } else { buildMipmap(gl, bitmap); } //Clean up bitmap.recycle(); } /** * Our own MipMap generation implementation. * Scale the original bitmap down, always by factor two, * and set it as new mipmap level. * * Thanks to Mike Miller (with minor changes)! * * @param gl - The GL Context * @param bitmap - The bitmap to mipmap */ private void buildMipmap(GL10 gl, Bitmap bitmap) { // int level = 0; // int height = bitmap.getHeight(); int width = bitmap.getWidth(); // while(height >= 1 || width >= 1) { //First of all, generate the texture from our bitmap and set it to the according level GLUtils.texImage2D(GL10.GL_TEXTURE_2D, level, bitmap, 0); // if(height == 1 || width == 1) { break; } //Increase the mipmap level level++; // height /= 2; width /= 2; Bitmap bitmap2 = Bitmap.createScaledBitmap(bitmap, width, height, true); //Clean up bitmap.recycle(); bitmap = bitmap2; } } }
true
true
public void loadGLTexture(GL10 gl, Context context) { //Get the texture from the Android resource directory InputStream is = context.getResources().openRawResource(R.drawable.android); Bitmap bitmap = null; try { //BitmapFactory is an Android graphics utility for images bitmap = BitmapFactory.decodeStream(is); } finally { //Always clear and close try { is.close(); is = null; } catch (IOException e) { } } //Generate there texture pointer gl.glGenTextures(3, textures, 0); //Create Nearest Filtered Texture and bind it to texture 0 gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); //Create Linear Filtered Texture and bind it to texture 1 gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[1]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); //Create mipmapped textures and bind it to texture 2 gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[2]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_NEAREST); /* * This is a change to the original tutorial, as buildMipMap does not exist anymore * in the Android SDK. * * We check if the GL context is version 1.1 and generate MipMaps by flag. * Otherwise we call our own buildMipMap implementation */ if(gl instanceof GL11) { gl.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_GENERATE_MIPMAP, GL11.GL_TRUE); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); // } else { buildMipmap(gl, bitmap); } //Clean up bitmap.recycle(); }
public void loadGLTexture(GL10 gl, Context context) { //Get the texture from the Android resource directory InputStream is = context.getResources().openRawResource(R.drawable.nehe_android); Bitmap bitmap = null; try { //BitmapFactory is an Android graphics utility for images bitmap = BitmapFactory.decodeStream(is); } finally { //Always clear and close try { is.close(); is = null; } catch (IOException e) { } } //Generate there texture pointer gl.glGenTextures(3, textures, 0); //Create Nearest Filtered Texture and bind it to texture 0 gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); //Create Linear Filtered Texture and bind it to texture 1 gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[1]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); //Create mipmapped textures and bind it to texture 2 gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[2]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_NEAREST); /* * This is a change to the original tutorial, as buildMipMap does not exist anymore * in the Android SDK. * * We check if the GL context is version 1.1 and generate MipMaps by flag. * Otherwise we call our own buildMipMap implementation */ if(gl instanceof GL11) { gl.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_GENERATE_MIPMAP, GL11.GL_TRUE); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); // } else { buildMipmap(gl, bitmap); } //Clean up bitmap.recycle(); }
diff --git a/desktop/src/restaurante/UI/Forms/FrmUsers.java b/desktop/src/restaurante/UI/Forms/FrmUsers.java index 8acec2e..7812c74 100644 --- a/desktop/src/restaurante/UI/Forms/FrmUsers.java +++ b/desktop/src/restaurante/UI/Forms/FrmUsers.java @@ -1,332 +1,332 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * FrmUsers.java * * Created on 23/02/2013, 09:40:34 */ package restaurante.UI.Forms; import java.util.logging.Level; import java.util.logging.Logger; import restaurante.Beans.Branches; import restaurante.Beans.Users; import restaurante.Controller.BranchesController; import restaurante.Controller.UsersController; import restaurante.UI.Searchs.FrmUsersSearch; import restaurante.Utils; /** * * @author aluno */ public class FrmUsers extends FrmNavToolbar<Users> { UsersController controller = new UsersController(); /** Creates new form FrmUsers */ public FrmUsers() { initComponents(); initComboBox(); resetList(); initDefaultProperties(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jSeparator1 = new javax.swing.JSeparator(); jPanel1 = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); chkActive = new javax.swing.JCheckBox(); jLabel3 = new javax.swing.JLabel(); txtPasswordExpires = new javax.swing.JSpinner(); cboWorkUnit = new javax.swing.JComboBox(); jLabel4 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); txtName = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); txtId = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); cboAccessLevel = new javax.swing.JComboBox(); txtPassword = new javax.swing.JPasswordField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Usuários"); setLocationByPlatform(true); setMinimumSize(new java.awt.Dimension(267, 251)); jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jPanel1.setMinimumSize(new java.awt.Dimension(267, 195)); jPanel1.setPreferredSize(new java.awt.Dimension(267, 195)); jPanel1.setRequestFocusEnabled(false); jLabel6.setText("Validade de senha"); chkActive.setSelected(true); chkActive.setText("Ativo"); jLabel3.setText("Nome"); cboWorkUnit.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "sfdfds", "tentie1", "aidsjids", "asjdi3ji" })); cboWorkUnit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cboWorkUnitActionPerformed(evt); } }); jLabel4.setText("Senha"); jLabel1.setText("ID"); txtName.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtNameActionPerformed(evt); } }); jLabel2.setText("Nível de acesso"); txtId.setEditable(false); txtId.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtIdActionPerformed(evt); } }); jLabel7.setText("Unidade de Trabalho"); cboAccessLevel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Administrador", "Operador", "Usuário" })); cboAccessLevel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cboAccessLevelActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel7) .addComponent(jLabel6) .addComponent(jLabel2) .addComponent(jLabel1)) .addGap(10, 10, 10) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtPasswordExpires, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(chkActive)) - .addComponent(cboAccessLevel, 0, 134, Short.MAX_VALUE) + .addComponent(cboAccessLevel, 0, 225, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) - .addComponent(txtName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE) - .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE) - .addComponent(cboWorkUnit, 0, 133, Short.MAX_VALUE)) + .addComponent(txtName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE) + .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE) + .addComponent(cboWorkUnit, 0, 224, Short.MAX_VALUE)) .addGap(1, 1, 1))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chkActive) .addComponent(jLabel1)) .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(cboAccessLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(cboWorkUnit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(txtPasswordExpires, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addContainerGap(19, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() - .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) - .addContainerGap(11, Short.MAX_VALUE)) + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE) + .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(56, 56, 56) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtIdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIdActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtIdActionPerformed private void txtNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNameActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtNameActionPerformed private void cboWorkUnitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboWorkUnitActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cboWorkUnitActionPerformed private void cboAccessLevelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboAccessLevelActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cboAccessLevelActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FrmUsers().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox cboAccessLevel; private javax.swing.JComboBox cboWorkUnit; private javax.swing.JCheckBox chkActive; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JSeparator jSeparator1; private javax.swing.JTextField txtId; private javax.swing.JTextField txtName; private javax.swing.JPasswordField txtPassword; private javax.swing.JSpinner txtPasswordExpires; // End of variables declaration//GEN-END:variables @Override public boolean saveRegister() { try { int id = 0; int branchId = 0; branchId = Integer.valueOf(cboWorkUnit.getSelectedItem().toString().split(" - ")[0]); id = !txtId.getText().equals("") ? Integer.valueOf(txtId.getText()) : 0; id = controller.saveRecord(id, cboAccessLevel.getSelectedIndex(), txtName.getText(), txtPassword.getText(), Integer.valueOf(txtPasswordExpires.getValue().toString()), branchId, chkActive.isSelected()); txtId.setText(String.valueOf(id)); Utils.showInfoMessage(this, SAVE_SUCCESS); resetList(); return true; } catch (Exception ex) { Logger.getLogger(FrmCustomers.class.getName()).log(Level.SEVERE, null, ex); Utils.showErrorMessage(this, SAVE_ERROR); } return false; } @Override public boolean deleteRegister() { if(!Utils.showQuestionMessage(this, DELETE_CONFIRMATION)) { return false; } try { controller.inative(Integer.valueOf(txtId.getText())); newRegister(); resetList(); return true; } catch (Exception ex) { Logger.getLogger(FrmCustomers.class.getName()).log(Level.SEVERE, null, ex); Utils.showErrorMessage(this, DELETE_ERROR); return false; } } @Override public void getValues(Users register) { txtId.setText(String.valueOf(register.getId())); cboAccessLevel.setSelectedIndex(register.getAccessLevel().ordinal()); txtName.setText(register.getName()); txtPassword.setText(register.getPassword()); cboWorkUnit.setSelectedItem(register.getBranch().getId() + " - " + register.getBranch().getName()); txtPasswordExpires.setValue(register.getPasswordExpires()); chkActive.setSelected(register.isActive()); controller.setNewRecord(false); } public final void resetList() { try { this.setList(controller.list()); newRegister(); } catch (Exception ex) { Logger.getLogger(FrmCustomers.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void searchRegister() { FrmUsersSearch search = new FrmUsersSearch(); search.show(); try { getValues(controller.findById((Integer)search.getReturnId())); } catch (Exception ex) { Logger.getLogger(FrmCustomers.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void setNewRegisterInController() { controller.setNewRecord(true); } /* * Não é igual para todas as telas */ private void initComboBox() { cboAccessLevel.removeAllItems(); for(String accessLevel : Users.AccessLevel.values) { cboAccessLevel.addItem(accessLevel); } cboWorkUnit.removeAllItems(); try { Branches[] branches = new BranchesController().list(true); for(int i = 0; i < branches.length; i++) { cboWorkUnit.addItem(branches[i].getId() + " - " + branches[i].getName()); } } catch (Exception ex) { Logger.getLogger(FrmUsers.class.getName()).log(Level.SEVERE, null, ex); } } }
false
true
private void initComponents() { jSeparator1 = new javax.swing.JSeparator(); jPanel1 = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); chkActive = new javax.swing.JCheckBox(); jLabel3 = new javax.swing.JLabel(); txtPasswordExpires = new javax.swing.JSpinner(); cboWorkUnit = new javax.swing.JComboBox(); jLabel4 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); txtName = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); txtId = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); cboAccessLevel = new javax.swing.JComboBox(); txtPassword = new javax.swing.JPasswordField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Usuários"); setLocationByPlatform(true); setMinimumSize(new java.awt.Dimension(267, 251)); jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jPanel1.setMinimumSize(new java.awt.Dimension(267, 195)); jPanel1.setPreferredSize(new java.awt.Dimension(267, 195)); jPanel1.setRequestFocusEnabled(false); jLabel6.setText("Validade de senha"); chkActive.setSelected(true); chkActive.setText("Ativo"); jLabel3.setText("Nome"); cboWorkUnit.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "sfdfds", "tentie1", "aidsjids", "asjdi3ji" })); cboWorkUnit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cboWorkUnitActionPerformed(evt); } }); jLabel4.setText("Senha"); jLabel1.setText("ID"); txtName.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtNameActionPerformed(evt); } }); jLabel2.setText("Nível de acesso"); txtId.setEditable(false); txtId.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtIdActionPerformed(evt); } }); jLabel7.setText("Unidade de Trabalho"); cboAccessLevel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Administrador", "Operador", "Usuário" })); cboAccessLevel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cboAccessLevelActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel7) .addComponent(jLabel6) .addComponent(jLabel2) .addComponent(jLabel1)) .addGap(10, 10, 10) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtPasswordExpires, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(chkActive)) .addComponent(cboAccessLevel, 0, 134, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE) .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE) .addComponent(cboWorkUnit, 0, 133, Short.MAX_VALUE)) .addGap(1, 1, 1))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chkActive) .addComponent(jLabel1)) .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(cboAccessLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(cboWorkUnit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(txtPasswordExpires, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addContainerGap(19, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(11, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(56, 56, 56) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { jSeparator1 = new javax.swing.JSeparator(); jPanel1 = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); chkActive = new javax.swing.JCheckBox(); jLabel3 = new javax.swing.JLabel(); txtPasswordExpires = new javax.swing.JSpinner(); cboWorkUnit = new javax.swing.JComboBox(); jLabel4 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); txtName = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); txtId = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); cboAccessLevel = new javax.swing.JComboBox(); txtPassword = new javax.swing.JPasswordField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Usuários"); setLocationByPlatform(true); setMinimumSize(new java.awt.Dimension(267, 251)); jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jPanel1.setMinimumSize(new java.awt.Dimension(267, 195)); jPanel1.setPreferredSize(new java.awt.Dimension(267, 195)); jPanel1.setRequestFocusEnabled(false); jLabel6.setText("Validade de senha"); chkActive.setSelected(true); chkActive.setText("Ativo"); jLabel3.setText("Nome"); cboWorkUnit.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "sfdfds", "tentie1", "aidsjids", "asjdi3ji" })); cboWorkUnit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cboWorkUnitActionPerformed(evt); } }); jLabel4.setText("Senha"); jLabel1.setText("ID"); txtName.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtNameActionPerformed(evt); } }); jLabel2.setText("Nível de acesso"); txtId.setEditable(false); txtId.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtIdActionPerformed(evt); } }); jLabel7.setText("Unidade de Trabalho"); cboAccessLevel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Administrador", "Operador", "Usuário" })); cboAccessLevel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cboAccessLevelActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel7) .addComponent(jLabel6) .addComponent(jLabel2) .addComponent(jLabel1)) .addGap(10, 10, 10) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtPasswordExpires, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(chkActive)) .addComponent(cboAccessLevel, 0, 225, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE) .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE) .addComponent(cboWorkUnit, 0, 224, Short.MAX_VALUE)) .addGap(1, 1, 1))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chkActive) .addComponent(jLabel1)) .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(cboAccessLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(cboWorkUnit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(txtPasswordExpires, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addContainerGap(19, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(56, 56, 56) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/main/java/org/helix/mobile/component/submitcommand/SubmitCommandRenderer.java b/src/main/java/org/helix/mobile/component/submitcommand/SubmitCommandRenderer.java index 0ea67b15..7aae35b1 100644 --- a/src/main/java/org/helix/mobile/component/submitcommand/SubmitCommandRenderer.java +++ b/src/main/java/org/helix/mobile/component/submitcommand/SubmitCommandRenderer.java @@ -1,70 +1,81 @@ /* * Copyright 2009-2011 Prime 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.helix.mobile.component.submitcommand; import java.io.IOException; import java.text.MessageFormat; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import org.primefaces.renderkit.CoreRenderer; public class SubmitCommandRenderer extends CoreRenderer { @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { SubmitCommand cmd = (SubmitCommand) component; this.encodeScript(context, cmd); } protected void encodeScript(FacesContext context, SubmitCommand cmd) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = cmd.getClientId(); StringBuilder actions = new StringBuilder(); + boolean actionWritten = false; actions.append("{"); if (cmd.getSuccessAction() != null) { actions.append("success: function(data, textStatus, jqXHR){ ").append(cmd.getSuccessAction()).append("}"); + actionWritten = true; } - if (cmd.getSuccessAction() != null && cmd.getErrorAction() != null) { + if (actionWritten) { actions.append(","); + actionWritten = false; } if (cmd.getErrorAction() != null) { actions.append("error: function(jqXHR,textStatus,errorThrown){ ").append(cmd.getErrorAction()).append("}"); + actionWritten = true; + } + if (actionWritten) { + actions.append(","); + actionWritten = false; + } + if (cmd.getBeforeSubmit() != null) { + actions.append("beforeSubmit: ").append(cmd.getBeforeSubmit()); } actions.append("}"); startScript(writer, clientId); writer.write("function " + cmd.getName() + "(){ "); // Setup the widget. writer.write(MessageFormat.format("Helix.Ajax.ajaxFormSubmit(''{0}'', ''{1}'', ''{2}'', ''{3}'', ''{4}'', ''{5}'', {6});", new Object[] { cmd.getUrl(), cmd.getForm(), cmd.getStatusTitle() != null ? cmd.getStatusTitle() : "", cmd.getSuccessMessage() != null ? cmd.getSuccessMessage() : "", cmd.getPendingMessage() != null ? cmd.getPendingMessage() : "", cmd.getErrorMessage() != null ? cmd.getErrorMessage() : "", actions.toString() })); writer.write("}"); endScript(writer); } }
false
true
protected void encodeScript(FacesContext context, SubmitCommand cmd) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = cmd.getClientId(); StringBuilder actions = new StringBuilder(); actions.append("{"); if (cmd.getSuccessAction() != null) { actions.append("success: function(data, textStatus, jqXHR){ ").append(cmd.getSuccessAction()).append("}"); } if (cmd.getSuccessAction() != null && cmd.getErrorAction() != null) { actions.append(","); } if (cmd.getErrorAction() != null) { actions.append("error: function(jqXHR,textStatus,errorThrown){ ").append(cmd.getErrorAction()).append("}"); } actions.append("}"); startScript(writer, clientId); writer.write("function " + cmd.getName() + "(){ "); // Setup the widget. writer.write(MessageFormat.format("Helix.Ajax.ajaxFormSubmit(''{0}'', ''{1}'', ''{2}'', ''{3}'', ''{4}'', ''{5}'', {6});", new Object[] { cmd.getUrl(), cmd.getForm(), cmd.getStatusTitle() != null ? cmd.getStatusTitle() : "", cmd.getSuccessMessage() != null ? cmd.getSuccessMessage() : "", cmd.getPendingMessage() != null ? cmd.getPendingMessage() : "", cmd.getErrorMessage() != null ? cmd.getErrorMessage() : "", actions.toString() })); writer.write("}"); endScript(writer); }
protected void encodeScript(FacesContext context, SubmitCommand cmd) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = cmd.getClientId(); StringBuilder actions = new StringBuilder(); boolean actionWritten = false; actions.append("{"); if (cmd.getSuccessAction() != null) { actions.append("success: function(data, textStatus, jqXHR){ ").append(cmd.getSuccessAction()).append("}"); actionWritten = true; } if (actionWritten) { actions.append(","); actionWritten = false; } if (cmd.getErrorAction() != null) { actions.append("error: function(jqXHR,textStatus,errorThrown){ ").append(cmd.getErrorAction()).append("}"); actionWritten = true; } if (actionWritten) { actions.append(","); actionWritten = false; } if (cmd.getBeforeSubmit() != null) { actions.append("beforeSubmit: ").append(cmd.getBeforeSubmit()); } actions.append("}"); startScript(writer, clientId); writer.write("function " + cmd.getName() + "(){ "); // Setup the widget. writer.write(MessageFormat.format("Helix.Ajax.ajaxFormSubmit(''{0}'', ''{1}'', ''{2}'', ''{3}'', ''{4}'', ''{5}'', {6});", new Object[] { cmd.getUrl(), cmd.getForm(), cmd.getStatusTitle() != null ? cmd.getStatusTitle() : "", cmd.getSuccessMessage() != null ? cmd.getSuccessMessage() : "", cmd.getPendingMessage() != null ? cmd.getPendingMessage() : "", cmd.getErrorMessage() != null ? cmd.getErrorMessage() : "", actions.toString() })); writer.write("}"); endScript(writer); }
diff --git a/src/main/java/edu/mayo/cts2/framework/plugin/service/lexevs/bulk/codesystemversion/controller/CodeSystemVersionBulkDownloadController.java b/src/main/java/edu/mayo/cts2/framework/plugin/service/lexevs/bulk/codesystemversion/controller/CodeSystemVersionBulkDownloadController.java index 838e2cd..07da74d 100644 --- a/src/main/java/edu/mayo/cts2/framework/plugin/service/lexevs/bulk/codesystemversion/controller/CodeSystemVersionBulkDownloadController.java +++ b/src/main/java/edu/mayo/cts2/framework/plugin/service/lexevs/bulk/codesystemversion/controller/CodeSystemVersionBulkDownloadController.java @@ -1,223 +1,236 @@ /* * Copyright: (c) Mayo Foundation for Medical Education and * Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the * triple-shield Mayo logo are trademarks and service marks of MFMER. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/lexevs-service/LICENSE.txt for details. */ package edu.mayo.cts2.framework.plugin.service.lexevs.bulk.codesystemversion.controller; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import org.LexGrid.LexBIG.DataModel.Core.types.CodingSchemeVersionStatus; import org.LexGrid.LexBIG.DataModel.InterfaceElements.CodingSchemeRendering; import org.LexGrid.LexBIG.Exceptions.LBException; import org.LexGrid.LexBIG.Exceptions.LBInvocationException; import org.LexGrid.LexBIG.Extensions.Generic.CodingSchemeReference; import org.LexGrid.LexBIG.LexBIGService.LexBIGService; import org.LexGrid.LexBIG.Utility.Constructors; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import edu.mayo.cts2.framework.plugin.service.lexevs.bulk.AbstractBulkDownloadController; import edu.mayo.cts2.framework.plugin.service.lexevs.bulk.codesystemversion.CodeSystemVersionBulkDownloader; import edu.mayo.cts2.framework.plugin.service.lexevs.security.msso.MssoUserValidator; /** * A REST Controller for providing access to bulk downloads. * * @author <a href="mailto:[email protected]">Kevin Peterson</a> */ @Controller("codeSystemVersionBulkDownloadController") public class CodeSystemVersionBulkDownloadController extends AbstractBulkDownloadController implements InitializingBean { private static final String DEFAULT_SEPARATOR = "|"; private static final String DEFAULT_CODING_SCHEMES = CodeSystemVersionBulkDownloader.ALL_CODINGSCHEMES; private static final String DEFAULT_FILE_NAME = "terminology-bulk-download.txt"; private static final String MEDDRA_NAME = "MedDRA"; private static final String NCI_META_NAME = "NCI Metathesaurus"; private static final List<String> DEFAULT_FIELDS = Arrays.asList( CodeSystemVersionBulkDownloader.CODE_FIELD, CodeSystemVersionBulkDownloader.NAMESPACE_FIELD, CodeSystemVersionBulkDownloader.DESCRIPTION_FIELD, CodeSystemVersionBulkDownloader.CODINGSCHEME_NAME_FIELD, CodeSystemVersionBulkDownloader.CODINGSCHEME_URI_FIELD, CodeSystemVersionBulkDownloader.CODINGSCHEME_VERSION_FIELD); @Resource private LexBIGService lexBigService; @Resource private CodeSystemVersionBulkDownloader codeSystemVersionBulkDownloader; @Resource private MssoUserValidator mssoUserValidator; private Set<CodingSchemeReference> meddraExclusions; private Set<CodingSchemeReference> nciMetaExclusions; @Override public void afterPropertiesSet() throws Exception { this.meddraExclusions = this.getMeddraCodingSchemes(); this.nciMetaExclusions = this.getNciMetaCodingSchemes(); } /** * Download. * * @param response the response * @param codingschemes the codingschemes * @param fields the fields * @param separator the separator * @throws LBException the lB exception */ @RequestMapping(value="/exporter/codingscheme") public void download( HttpServletResponse response, @RequestParam(value="meddratoken", defaultValue="") String meddraToken, @RequestParam(value="codingschemes", defaultValue="") String codingschemes, @RequestParam(value="fields", defaultValue="") String fields, @RequestParam(value="separator", defaultValue=DEFAULT_SEPARATOR) char separator, @RequestParam(value="filename", defaultValue=DEFAULT_FILE_NAME) String filename) throws LBException { if(StringUtils.isBlank(codingschemes)){ throw new UserInputException("'codingschemes' parameter is required."); } - boolean isValidMeddraToken = StringUtils.isNotBlank(meddraToken) && this.mssoUserValidator.isValid(meddraToken); + boolean isValidMeddraToken = false; + if(StringUtils.isNotBlank(meddraToken)){ + boolean validates = this.mssoUserValidator.isValid(meddraToken); + if(! validates){ + try { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid MedDRA token."); + return; + } catch (IOException e) { + throw new RuntimeException(e); + } + } else { + isValidMeddraToken = true; + } + } List<String> fieldsList; if(StringUtils.isBlank(fields)){ fieldsList = DEFAULT_FIELDS; } else { fieldsList = Arrays.asList(StringUtils.split(fields, ',')); } this.setHeaders(response, filename); Set<CodingSchemeReference> references = new HashSet<CodingSchemeReference>(); for(String codingScheme : StringUtils.split(codingschemes, ',')){ if(codingScheme.equals(CodeSystemVersionBulkDownloader.ALL_CODINGSCHEMES)){ continue; } String[] parts = StringUtils.split(codingScheme, ':'); CodingSchemeReference reference = new CodingSchemeReference(); reference.setCodingScheme(parts[0]); if(parts.length == 2){ reference.setVersionOrTag( Constructors.createCodingSchemeVersionOrTagFromVersion(parts[1])); } references.add(reference); } Set<CodingSchemeReference> exclusions = new HashSet<CodingSchemeReference>(); exclusions.addAll(this.nciMetaExclusions); if(! isValidMeddraToken){ exclusions.addAll(this.meddraExclusions); } try { this.codeSystemVersionBulkDownloader.download( response.getOutputStream(), references, exclusions, fieldsList, separator); } catch (IOException e) { throw new RuntimeException(e); } try { response.flushBuffer(); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected String getValidParametersMessage() { StringBuilder sb = new StringBuilder(); sb.append("codingschemes - (Optional) CodingSchemes to include (comma-separated). Default: " + DEFAULT_CODING_SCHEMES +"\n"); sb.append("\tFormat: codingSchemeName[:version] - example: 'MyCodingScheme' or 'MyCodingScheme:1.0'\n"); sb.append("\tAvailable: all," + this.getAvailableCodingSchemesString() +"\n"); sb.append("fields - (Optional) Content fields to output. Default: "+ DEFAULT_FIELDS + "\n"); sb.append("separator -(Optional) One character field separator. Default: " + DEFAULT_SEPARATOR +"\n"); sb.append("filename - (Optional) Output file name. Default: " + DEFAULT_FILE_NAME); return sb.toString(); } private Set<CodingSchemeReference> getMeddraCodingSchemes(){ return this.doGetCodingSchemeReferences(MEDDRA_NAME); } private Set<CodingSchemeReference> getNciMetaCodingSchemes(){ return this.doGetCodingSchemeReferences(NCI_META_NAME); } private Set<CodingSchemeReference> doGetCodingSchemeReferences(String name){ Set<CodingSchemeReference> references = new HashSet<CodingSchemeReference>(); try { for(CodingSchemeRendering scheme : lexBigService.getSupportedCodingSchemes().getCodingSchemeRendering()){ if(scheme.getCodingSchemeSummary().getLocalName().equals(name)){ CodingSchemeReference reference = new CodingSchemeReference(); reference.setCodingScheme( scheme.getCodingSchemeSummary().getCodingSchemeURI()); reference.setVersionOrTag( Constructors.createCodingSchemeVersionOrTagFromVersion(scheme.getCodingSchemeSummary().getRepresentsVersion())); references.add(reference); } } } catch (LBInvocationException e) { return null; } return references; } private String getAvailableCodingSchemesString(){ List<String> schemes = new ArrayList<String>(); try { for(CodingSchemeRendering scheme : lexBigService.getSupportedCodingSchemes().getCodingSchemeRendering()){ if(scheme.getRenderingDetail().getVersionStatus().equals(CodingSchemeVersionStatus.ACTIVE)){ String name = scheme.getCodingSchemeSummary().getLocalName(); String version = scheme.getCodingSchemeSummary().getRepresentsVersion(); schemes.add(name + "[:" + version + "]"); } } } catch (LBInvocationException e) { return ""; } return StringUtils.join(schemes, ","); } @Override public Object getController() { return this; } }
true
true
public void download( HttpServletResponse response, @RequestParam(value="meddratoken", defaultValue="") String meddraToken, @RequestParam(value="codingschemes", defaultValue="") String codingschemes, @RequestParam(value="fields", defaultValue="") String fields, @RequestParam(value="separator", defaultValue=DEFAULT_SEPARATOR) char separator, @RequestParam(value="filename", defaultValue=DEFAULT_FILE_NAME) String filename) throws LBException { if(StringUtils.isBlank(codingschemes)){ throw new UserInputException("'codingschemes' parameter is required."); } boolean isValidMeddraToken = StringUtils.isNotBlank(meddraToken) && this.mssoUserValidator.isValid(meddraToken); List<String> fieldsList; if(StringUtils.isBlank(fields)){ fieldsList = DEFAULT_FIELDS; } else { fieldsList = Arrays.asList(StringUtils.split(fields, ',')); } this.setHeaders(response, filename); Set<CodingSchemeReference> references = new HashSet<CodingSchemeReference>(); for(String codingScheme : StringUtils.split(codingschemes, ',')){ if(codingScheme.equals(CodeSystemVersionBulkDownloader.ALL_CODINGSCHEMES)){ continue; } String[] parts = StringUtils.split(codingScheme, ':'); CodingSchemeReference reference = new CodingSchemeReference(); reference.setCodingScheme(parts[0]); if(parts.length == 2){ reference.setVersionOrTag( Constructors.createCodingSchemeVersionOrTagFromVersion(parts[1])); } references.add(reference); } Set<CodingSchemeReference> exclusions = new HashSet<CodingSchemeReference>(); exclusions.addAll(this.nciMetaExclusions); if(! isValidMeddraToken){ exclusions.addAll(this.meddraExclusions); } try { this.codeSystemVersionBulkDownloader.download( response.getOutputStream(), references, exclusions, fieldsList, separator); } catch (IOException e) { throw new RuntimeException(e); } try { response.flushBuffer(); } catch (IOException e) { throw new RuntimeException(e); } }
public void download( HttpServletResponse response, @RequestParam(value="meddratoken", defaultValue="") String meddraToken, @RequestParam(value="codingschemes", defaultValue="") String codingschemes, @RequestParam(value="fields", defaultValue="") String fields, @RequestParam(value="separator", defaultValue=DEFAULT_SEPARATOR) char separator, @RequestParam(value="filename", defaultValue=DEFAULT_FILE_NAME) String filename) throws LBException { if(StringUtils.isBlank(codingschemes)){ throw new UserInputException("'codingschemes' parameter is required."); } boolean isValidMeddraToken = false; if(StringUtils.isNotBlank(meddraToken)){ boolean validates = this.mssoUserValidator.isValid(meddraToken); if(! validates){ try { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid MedDRA token."); return; } catch (IOException e) { throw new RuntimeException(e); } } else { isValidMeddraToken = true; } } List<String> fieldsList; if(StringUtils.isBlank(fields)){ fieldsList = DEFAULT_FIELDS; } else { fieldsList = Arrays.asList(StringUtils.split(fields, ',')); } this.setHeaders(response, filename); Set<CodingSchemeReference> references = new HashSet<CodingSchemeReference>(); for(String codingScheme : StringUtils.split(codingschemes, ',')){ if(codingScheme.equals(CodeSystemVersionBulkDownloader.ALL_CODINGSCHEMES)){ continue; } String[] parts = StringUtils.split(codingScheme, ':'); CodingSchemeReference reference = new CodingSchemeReference(); reference.setCodingScheme(parts[0]); if(parts.length == 2){ reference.setVersionOrTag( Constructors.createCodingSchemeVersionOrTagFromVersion(parts[1])); } references.add(reference); } Set<CodingSchemeReference> exclusions = new HashSet<CodingSchemeReference>(); exclusions.addAll(this.nciMetaExclusions); if(! isValidMeddraToken){ exclusions.addAll(this.meddraExclusions); } try { this.codeSystemVersionBulkDownloader.download( response.getOutputStream(), references, exclusions, fieldsList, separator); } catch (IOException e) { throw new RuntimeException(e); } try { response.flushBuffer(); } catch (IOException e) { throw new RuntimeException(e); } }
diff --git a/webapp/app/controllers/FacebookLoggedInController.java b/webapp/app/controllers/FacebookLoggedInController.java index 55e3a91..1531e52 100644 --- a/webapp/app/controllers/FacebookLoggedInController.java +++ b/webapp/app/controllers/FacebookLoggedInController.java @@ -1,29 +1,29 @@ package controllers; import models.User; import play.modules.facebook.FbGraph; import play.modules.facebook.FbGraphException; import play.mvc.Before; import play.mvc.Controller; import play.mvc.Scope.Session; public class FacebookLoggedInController extends Controller{ @Before public static void checkAccess() throws Throwable { FbGraph.init(); try { User fbUser = FacebookSecurity.getCurrentFbUser(); if(fbUser == null){ Wall.index(); } renderArgs.put("fbuser", fbUser); // put the email into the session (for the Secure module) } catch (FbGraphException fbge) { - flash.error("Sorry, we can't find you Facebook account. Please try logging in again"); + flash.error("Sorry, we can't find your Facebook account. Please try logging in again"); if (fbge.getType() != null && fbge.getType().equals("OAuthException")) { Session.current().remove("fbuserid"); } Wall.index(); } } }
true
true
public static void checkAccess() throws Throwable { FbGraph.init(); try { User fbUser = FacebookSecurity.getCurrentFbUser(); if(fbUser == null){ Wall.index(); } renderArgs.put("fbuser", fbUser); // put the email into the session (for the Secure module) } catch (FbGraphException fbge) { flash.error("Sorry, we can't find you Facebook account. Please try logging in again"); if (fbge.getType() != null && fbge.getType().equals("OAuthException")) { Session.current().remove("fbuserid"); } Wall.index(); } }
public static void checkAccess() throws Throwable { FbGraph.init(); try { User fbUser = FacebookSecurity.getCurrentFbUser(); if(fbUser == null){ Wall.index(); } renderArgs.put("fbuser", fbUser); // put the email into the session (for the Secure module) } catch (FbGraphException fbge) { flash.error("Sorry, we can't find your Facebook account. Please try logging in again"); if (fbge.getType() != null && fbge.getType().equals("OAuthException")) { Session.current().remove("fbuserid"); } Wall.index(); } }
diff --git a/src/main/java/pl/llp/aircasting/helper/CSVHelper.java b/src/main/java/pl/llp/aircasting/helper/CSVHelper.java index dd0f65a9..a972c592 100644 --- a/src/main/java/pl/llp/aircasting/helper/CSVHelper.java +++ b/src/main/java/pl/llp/aircasting/helper/CSVHelper.java @@ -1,133 +1,134 @@ /** AirCasting - Share your Air! Copyright (C) 2011-2012 HabitatMap, Inc. 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/>. You can contact the authors by email at <[email protected]> */ package pl.llp.aircasting.helper; import pl.llp.aircasting.guice.GsonProvider; import pl.llp.aircasting.model.Measurement; import pl.llp.aircasting.model.MeasurementStream; import pl.llp.aircasting.model.Session; import android.content.Context; import android.net.Uri; import com.csvreader.CsvWriter; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.SimpleDateFormat; import static com.google.common.io.Closeables.closeQuietly; import static java.lang.String.valueOf; public class CSVHelper { // Gmail app hack - it requires all file attachments to begin with /mnt/sdcard public static final String BASE_PATH = "/mnt/sdcard/../.."; public static final String SESSION_TEMP_FILE = "session.csv"; public Uri prepareCSV(Context context, Session session) throws IOException { OutputStream outputStream = null; try { - outputStream = context.openFileOutput(SESSION_TEMP_FILE, Context.MODE_WORLD_READABLE); + File file = new File(getTarget(context), SESSION_TEMP_FILE); + outputStream = context.openFileOutput(file.getAbsolutePath(), Context.MODE_WORLD_READABLE); Writer writer = new OutputStreamWriter(outputStream); CsvWriter csvWriter = new CsvWriter(writer, ','); csvWriter.write("sensor:model"); csvWriter.write("sensor:package"); csvWriter.write("sensor:capability"); csvWriter.write("Date"); csvWriter.write("Time"); csvWriter.write("Timestamp"); csvWriter.write("geo:lat"); csvWriter.write("geo:long"); csvWriter.write("sensor:units"); csvWriter.write("Value"); csvWriter.endRecord(); write(session).toWriter(csvWriter); + csvWriter.flush(); csvWriter.close(); - File file = getTarget(context); return Uri.fromFile(file); } finally { closeQuietly(outputStream); } } private File getTarget(Context context) { String path = new StringBuilder(BASE_PATH) .append(context.getFilesDir()) .append("/") .append(SESSION_TEMP_FILE) .toString(); return new File(path); } private SessionWriter write(Session session) { return new SessionWriter(session); } } class SessionWriter { final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss"); final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy"); final SimpleDateFormat TIMESTAMP_FORMAT = new SimpleDateFormat(GsonProvider.ISO_8601); Session session; SessionWriter(Session session) { this.session = session; } void toWriter(CsvWriter writer) throws IOException { Iterable<MeasurementStream> streams = session.getActiveMeasurementStreams(); for (MeasurementStream stream : streams) { for (Measurement measurement : stream.getMeasurements()) { writer.write(stream.getSensorName()); writer.write(stream.getPackageName()); writer.write(stream.getMeasurementType()); writer.write(DATE_FORMAT.format(measurement.getTime())); writer.write(TIME_FORMAT.format(measurement.getTime())); writer.write(TIMESTAMP_FORMAT.format(measurement.getTime())); writer.write(valueOf(measurement.getLongitude())); writer.write(valueOf(measurement.getLatitude())); writer.write(valueOf(stream.getUnit())); writer.write(valueOf(measurement.getValue())); writer.endRecord(); } } } }
false
true
public Uri prepareCSV(Context context, Session session) throws IOException { OutputStream outputStream = null; try { outputStream = context.openFileOutput(SESSION_TEMP_FILE, Context.MODE_WORLD_READABLE); Writer writer = new OutputStreamWriter(outputStream); CsvWriter csvWriter = new CsvWriter(writer, ','); csvWriter.write("sensor:model"); csvWriter.write("sensor:package"); csvWriter.write("sensor:capability"); csvWriter.write("Date"); csvWriter.write("Time"); csvWriter.write("Timestamp"); csvWriter.write("geo:lat"); csvWriter.write("geo:long"); csvWriter.write("sensor:units"); csvWriter.write("Value"); csvWriter.endRecord(); write(session).toWriter(csvWriter); csvWriter.close(); File file = getTarget(context); return Uri.fromFile(file); } finally { closeQuietly(outputStream); } }
public Uri prepareCSV(Context context, Session session) throws IOException { OutputStream outputStream = null; try { File file = new File(getTarget(context), SESSION_TEMP_FILE); outputStream = context.openFileOutput(file.getAbsolutePath(), Context.MODE_WORLD_READABLE); Writer writer = new OutputStreamWriter(outputStream); CsvWriter csvWriter = new CsvWriter(writer, ','); csvWriter.write("sensor:model"); csvWriter.write("sensor:package"); csvWriter.write("sensor:capability"); csvWriter.write("Date"); csvWriter.write("Time"); csvWriter.write("Timestamp"); csvWriter.write("geo:lat"); csvWriter.write("geo:long"); csvWriter.write("sensor:units"); csvWriter.write("Value"); csvWriter.endRecord(); write(session).toWriter(csvWriter); csvWriter.flush(); csvWriter.close(); return Uri.fromFile(file); } finally { closeQuietly(outputStream); } }
diff --git a/src/main/java/org/browsermob/proxy/BrowserMobProxyHandler.java b/src/main/java/org/browsermob/proxy/BrowserMobProxyHandler.java index be02f63..9b8ef14 100644 --- a/src/main/java/org/browsermob/proxy/BrowserMobProxyHandler.java +++ b/src/main/java/org/browsermob/proxy/BrowserMobProxyHandler.java @@ -1,394 +1,394 @@ package org.browsermob.proxy; import org.apache.http.Header; import org.apache.http.NoHttpResponseException; import org.apache.http.StatusLine; import org.apache.http.conn.ConnectTimeoutException; import org.browsermob.proxy.http.*; import org.browsermob.proxy.jetty.http.*; import org.browsermob.proxy.jetty.jetty.Server; import org.browsermob.proxy.jetty.util.InetAddrPort; import org.browsermob.proxy.jetty.util.URI; import org.browsermob.proxy.selenium.SeleniumProxyHandler; import org.browsermob.proxy.util.Log; import java.io.IOException; import java.io.InputStream; import java.net.*; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; public class BrowserMobProxyHandler extends SeleniumProxyHandler { private static final Log LOG = new Log(); private static final int HEADER_BUFFER_DEFAULT = 2; private Server jettyServer; private int headerBufferMultiplier = HEADER_BUFFER_DEFAULT; private BrowserMobHttpClient httpClient; protected final Set<SslRelay> sslRelays = new HashSet<SslRelay>(); public BrowserMobProxyHandler() { super(true, "", "", false, false); setShutdownLock(new Object()); // set the tunnel timeout to something larger than the default 30 seconds // we're doing this because SSL connections taking longer than this timeout // will result in a socket connection close that does NOT get handled by the // normal socket connection closing reportError(). Further, it has been seen // that Firefox will actually retry the connection, causing very strange // behavior observed in case http://browsermob.assistly.com/agent/case/27843 // // You can also reproduce it by simply finding some slow loading SSL site // that takes greater than 30 seconds to response. // // Finally, it should be noted that we're setting this timeout to some value // that we anticipate will be larger than any reasonable response time of a // real world request. We don't set it to -1 because the underlying ProxyHandler // will not use it if it's <= 0. We also don't set it to Long.MAX_VALUE because // we don't yet know if this will cause a serious resource drain, so we're // going to try something like 5 minutes for now. setTunnelTimeoutMs(300000); } @Override public void handleConnect(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { URI uri = request.getURI(); String original = uri.toString(); String host = original; String port = null; int colon = original.indexOf(':'); if (colon != -1) { host = original.substring(0, colon); port = original.substring(colon + 1); } String altHost = httpClient.remappedHost(host); if (altHost != null) { if (port != null) { uri.setURI(altHost + ":" + port); } else { uri.setURI(altHost); } } super.handleConnect(pathInContext, pathParams, request, response); } @Override protected void wireUpSslWithCyberVilliansCA(String host, SeleniumProxyHandler.SslRelay listener) { List<String> originalHosts = httpClient.originalHosts(host); if (originalHosts != null && !originalHosts.isEmpty()) { if (originalHosts.size() == 1) { host = originalHosts.get(0); } else { // Warning: this is NASTY, but people rarely even run across this and those that do are solved by this // ok, this really isn't legal in real SSL land, but we'll make an exception and just pretend it's a wildcard String first = originalHosts.get(0); host = "*" + first.substring(first.indexOf('.')); } } super.wireUpSslWithCyberVilliansCA(host, listener); } @Override protected SslRelay getSslRelayOrCreateNew(URI uri, InetAddrPort addrPort, HttpServer server) throws Exception { SslRelay relay = super.getSslRelayOrCreateNew(uri, addrPort, server); relay.setNukeDirOrFile(null); synchronized (sslRelays) { sslRelays.add(relay); } if (!relay.isStarted()) { server.addListener(relay); startRelayWithPortTollerance(server, relay, 1); } return relay; } private void startRelayWithPortTollerance(HttpServer server, SslRelay relay, int tries) throws Exception { if (tries >= 5) { throw new BindException("Unable to bind to several ports, most recently " + relay.getPort() + ". Giving up"); } try { if (server.isStarted()) { relay.start(); } else { throw new RuntimeException("Can't start SslRelay: server is not started (perhaps it was just shut down?)"); } } catch (BindException e) { // doh - the port is being used up, let's pick a new port LOG.info("Unable to bind to port %d, going to try port %d now", relay.getPort(), relay.getPort() + 1); relay.setPort(relay.getPort() + 1); startRelayWithPortTollerance(server, relay, tries + 1); } } @Override protected HttpTunnel newHttpTunnel(HttpRequest httpRequest, HttpResponse httpResponse, InetAddress inetAddress, int i, int i1) throws IOException { // we're opening up a new tunnel, so let's make sure that the associated SslRelay (which may or may not be new) has the proper buffer settings adjustListenerBuffers(); return super.newHttpTunnel(httpRequest, httpResponse, inetAddress, i, i1); } @SuppressWarnings({"unchecked"}) protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams, HttpRequest request, final HttpResponse response) throws IOException { try { String urlStr = url.toString(); - // We don't want localhost or selenium-related showing up in the detailed transaction logs - if (urlStr.startsWith("http://localhost") || urlStr.contains("/selenium-server/")) { + // We don't want selenium-related showing up in the detailed transaction logs + if (urlStr.contains("/selenium-server/")) { return super.proxyPlainTextRequest(url, pathInContext, pathParams, request, response); } // we also don't URLs that Firefox always loads on startup showing up, or even wasting bandwidth. // so for these we just nuke them right on the spot! if (urlStr.startsWith("https://sb-ssl.google.com:443/safebrowsing") || urlStr.startsWith("http://en-us.fxfeeds.mozilla.com/en-US/firefox/headlines.xml") || urlStr.startsWith("http://fxfeeds.mozilla.com/firefox/headlines.xml") || urlStr.startsWith("http://fxfeeds.mozilla.com/en-US/firefox/headlines.xml") || urlStr.startsWith("http://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml")) { // don't even xfer these! request.setHandled(true); return -1; } // this request must have come in just as we were shutting down, since there is no more associted http client // so let's just handle it like we do any other request we don't know what to do with :) if (httpClient == null) { // don't even xfer these! request.setHandled(true); return -1; // for debugging purposes, NOT to be used in product! // httpClient = new BrowserMobHttpClient(Integer.MAX_VALUE); // httpClient.setDecompress(false); // httpClient.setFollowRedirects(false); } BrowserMobHttpRequest httpReq = null; if ("GET".equals(request.getMethod())) { httpReq = httpClient.newGet(urlStr); } else if ("POST".equals(request.getMethod())) { httpReq = httpClient.newPost(urlStr); } else if ("PUT".equals(request.getMethod())) { httpReq = httpClient.newPut(urlStr); } else if ("DELETE".equals(request.getMethod())) { httpReq = httpClient.newDelete(urlStr); } else if ("OPTIONS".equals(request.getMethod())) { httpReq = httpClient.newOptions(urlStr); } else if ("HEAD".equals(request.getMethod())) { httpReq = httpClient.newHead(urlStr); } else { LOG.warn("Unexpected request method %s, giving up", request.getMethod()); request.setHandled(true); return -1; } // copy request headers boolean isGet = "GET".equals(request.getMethod()); boolean hasContent = false; Enumeration enm = request.getFieldNames(); long contentLength = 0; while (enm.hasMoreElements()) { String hdr = (String) enm.nextElement(); if (!isGet && HttpFields.__ContentType.equals(hdr)) { hasContent = true; } if (!isGet && HttpFields.__ContentLength.equals(hdr)) { contentLength = Long.parseLong(request.getField(hdr)); continue; } Enumeration vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { if ("User-Agent".equals(hdr)) { val = updateUserAgent(val); } // don't proxy Referer headers if the referer is Selenium! if ("Referer".equals(hdr) && (-1 != val.indexOf("/selenium-server/"))) { continue; } if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) { hasContent = true; } httpReq.addRequestHeader(hdr, val); } } } try { // do input thang! InputStream in = request.getInputStream(); if (hasContent) { httpReq.setRequestInputStream(in, contentLength); } } catch (Exception e) { LOG.fine(e.getMessage(), e); } // execute the request httpReq.setOutputStream(response.getOutputStream()); httpReq.setRequestCallback(new RequestCallback() { @Override public void handleStatusLine(StatusLine statusLine) { response.setStatus(statusLine.getStatusCode()); response.setReason(statusLine.getReasonPhrase()); } @Override public void handleHeaders(Header[] headers) { for (Header header : headers) { if (reportHeader(header)) { response.addField(header.getName(), header.getValue()); } } } @Override public boolean reportHeader(Header header) { // don't pass in things like Transfer-Encoding and other headers that are being masked by the underlying HttpClient impl return !_DontProxyHeaders.containsKey(header.getName()) && !_ProxyAuthHeaders.containsKey(header.getName()); } @Override public void reportError(Exception e) { BrowserMobProxyHandler.reportError(e, url, response); } }); BrowserMobHttpResponse httpRes = httpReq.execute(); // ALWAYS mark the request as handled if we actually handled it. Otherwise, Jetty will think non 2xx responses // mean it wasn't actually handled, resulting in totally valid 304 Not Modified requests turning in to 404 responses // from Jetty. NOT good :( request.setHandled(true); return httpRes.getEntry().getResponse().getBodySize(); } catch (BadURIException e) { // this is a known error case (see MOB-93) LOG.info(e.getMessage()); BrowserMobProxyHandler.reportError(e, url, response); return -1; } catch (Exception e) { LOG.info("Exception while proxying " + url, e); BrowserMobProxyHandler.reportError(e, url, response); return -1; } } private static void reportError(Exception e, URL url, HttpResponse response) { FirefoxErrorContent error = FirefoxErrorContent.GENERIC; if (e instanceof UnknownHostException) { error = FirefoxErrorContent.DNS_NOT_FOUND; } else if (e instanceof ConnectException) { error = FirefoxErrorContent.CONN_FAILURE; } else if (e instanceof ConnectTimeoutException) { error = FirefoxErrorContent.NET_TIMEOUT; } else if (e instanceof NoHttpResponseException) { error = FirefoxErrorContent.NET_RESET; } else if (e instanceof EOFException) { error = FirefoxErrorContent.NET_INTERRUPT; } else if (e instanceof IllegalArgumentException && e.getMessage().startsWith("Host name may not be null")){ error = FirefoxErrorContent.DNS_NOT_FOUND; } else if (e instanceof BadURIException){ error = FirefoxErrorContent.MALFORMED_URI; } String shortDesc = String.format(error.getShortDesc(), url.getHost()); String text = String.format(FirefoxErrorConstants.ERROR_PAGE, error.getTitle(), shortDesc, error.getLongDesc()); try { response.setStatus(HttpResponse.__502_Bad_Gateway); response.setContentLength(text.length()); response.getOutputStream().write(text.getBytes()); } catch (IOException e1) { LOG.warn("IOException while trying to report an HTTP error"); } } private static String updateUserAgent(String ua) { int start = ua.indexOf(")"); if (start > -1) { ua = ua.substring(0, start) + "; BrowserMob RBU" + ua.substring(start); } return ua; } public void autoBasicAuthorization(String domain, String username, String password) { httpClient.autoBasicAuthorization(domain, username, password); } public void rewriteUrl(String match, String replace) { httpClient.rewriteUrl(match, replace); } public void remapHost(String source, String target) { httpClient.remapHost(source, target); } public void setJettyServer(Server jettyServer) { this.jettyServer = jettyServer; } public void adjustListenerBuffers(int headerBufferMultiplier) { // limit to 10 so there can't be any out of control memory consumption by a rogue script if (headerBufferMultiplier > 10) { headerBufferMultiplier = 10; } this.headerBufferMultiplier = headerBufferMultiplier; adjustListenerBuffers(); } public void resetListenerBuffers() { this.headerBufferMultiplier = HEADER_BUFFER_DEFAULT; adjustListenerBuffers(); } public void adjustListenerBuffers() { // configure the listeners to have larger buffers. We do this because we've seen cases where the header is // too large. Normally this would happen on "meaningless" JS includes for ad networks, but we eventually saw // it in a way that caused a Selenium script not to work due to too many headers (see [email protected]) HttpListener[] listeners = jettyServer.getListeners(); for (HttpListener listener : listeners) { if (listener instanceof SocketListener) { SocketListener sl = (SocketListener) listener; if (sl.getBufferReserve() != 512 * headerBufferMultiplier) { sl.setBufferReserve(512 * headerBufferMultiplier); } if (sl.getBufferSize() != 8192 * headerBufferMultiplier) { sl.setBufferSize(8192 * headerBufferMultiplier); } } } } public void setHttpClient(BrowserMobHttpClient httpClient) { this.httpClient = httpClient; } public void cleanup() { synchronized (sslRelays) { for (SslRelay relay : sslRelays) { if (relay.getHttpServer() != null && relay.isStarted()) { relay.getHttpServer().removeListener(relay); } } sslRelays.clear(); } } }
true
true
protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams, HttpRequest request, final HttpResponse response) throws IOException { try { String urlStr = url.toString(); // We don't want localhost or selenium-related showing up in the detailed transaction logs if (urlStr.startsWith("http://localhost") || urlStr.contains("/selenium-server/")) { return super.proxyPlainTextRequest(url, pathInContext, pathParams, request, response); } // we also don't URLs that Firefox always loads on startup showing up, or even wasting bandwidth. // so for these we just nuke them right on the spot! if (urlStr.startsWith("https://sb-ssl.google.com:443/safebrowsing") || urlStr.startsWith("http://en-us.fxfeeds.mozilla.com/en-US/firefox/headlines.xml") || urlStr.startsWith("http://fxfeeds.mozilla.com/firefox/headlines.xml") || urlStr.startsWith("http://fxfeeds.mozilla.com/en-US/firefox/headlines.xml") || urlStr.startsWith("http://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml")) { // don't even xfer these! request.setHandled(true); return -1; } // this request must have come in just as we were shutting down, since there is no more associted http client // so let's just handle it like we do any other request we don't know what to do with :) if (httpClient == null) { // don't even xfer these! request.setHandled(true); return -1; // for debugging purposes, NOT to be used in product! // httpClient = new BrowserMobHttpClient(Integer.MAX_VALUE); // httpClient.setDecompress(false); // httpClient.setFollowRedirects(false); } BrowserMobHttpRequest httpReq = null; if ("GET".equals(request.getMethod())) { httpReq = httpClient.newGet(urlStr); } else if ("POST".equals(request.getMethod())) { httpReq = httpClient.newPost(urlStr); } else if ("PUT".equals(request.getMethod())) { httpReq = httpClient.newPut(urlStr); } else if ("DELETE".equals(request.getMethod())) { httpReq = httpClient.newDelete(urlStr); } else if ("OPTIONS".equals(request.getMethod())) { httpReq = httpClient.newOptions(urlStr); } else if ("HEAD".equals(request.getMethod())) { httpReq = httpClient.newHead(urlStr); } else { LOG.warn("Unexpected request method %s, giving up", request.getMethod()); request.setHandled(true); return -1; } // copy request headers boolean isGet = "GET".equals(request.getMethod()); boolean hasContent = false; Enumeration enm = request.getFieldNames(); long contentLength = 0; while (enm.hasMoreElements()) { String hdr = (String) enm.nextElement(); if (!isGet && HttpFields.__ContentType.equals(hdr)) { hasContent = true; } if (!isGet && HttpFields.__ContentLength.equals(hdr)) { contentLength = Long.parseLong(request.getField(hdr)); continue; } Enumeration vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { if ("User-Agent".equals(hdr)) { val = updateUserAgent(val); } // don't proxy Referer headers if the referer is Selenium! if ("Referer".equals(hdr) && (-1 != val.indexOf("/selenium-server/"))) { continue; } if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) { hasContent = true; } httpReq.addRequestHeader(hdr, val); } } } try { // do input thang! InputStream in = request.getInputStream(); if (hasContent) { httpReq.setRequestInputStream(in, contentLength); } } catch (Exception e) { LOG.fine(e.getMessage(), e); } // execute the request httpReq.setOutputStream(response.getOutputStream()); httpReq.setRequestCallback(new RequestCallback() { @Override public void handleStatusLine(StatusLine statusLine) { response.setStatus(statusLine.getStatusCode()); response.setReason(statusLine.getReasonPhrase()); } @Override public void handleHeaders(Header[] headers) { for (Header header : headers) { if (reportHeader(header)) { response.addField(header.getName(), header.getValue()); } } } @Override public boolean reportHeader(Header header) { // don't pass in things like Transfer-Encoding and other headers that are being masked by the underlying HttpClient impl return !_DontProxyHeaders.containsKey(header.getName()) && !_ProxyAuthHeaders.containsKey(header.getName()); } @Override public void reportError(Exception e) { BrowserMobProxyHandler.reportError(e, url, response); } }); BrowserMobHttpResponse httpRes = httpReq.execute(); // ALWAYS mark the request as handled if we actually handled it. Otherwise, Jetty will think non 2xx responses // mean it wasn't actually handled, resulting in totally valid 304 Not Modified requests turning in to 404 responses // from Jetty. NOT good :( request.setHandled(true); return httpRes.getEntry().getResponse().getBodySize(); } catch (BadURIException e) { // this is a known error case (see MOB-93) LOG.info(e.getMessage()); BrowserMobProxyHandler.reportError(e, url, response); return -1; } catch (Exception e) { LOG.info("Exception while proxying " + url, e); BrowserMobProxyHandler.reportError(e, url, response); return -1; } }
protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams, HttpRequest request, final HttpResponse response) throws IOException { try { String urlStr = url.toString(); // We don't want selenium-related showing up in the detailed transaction logs if (urlStr.contains("/selenium-server/")) { return super.proxyPlainTextRequest(url, pathInContext, pathParams, request, response); } // we also don't URLs that Firefox always loads on startup showing up, or even wasting bandwidth. // so for these we just nuke them right on the spot! if (urlStr.startsWith("https://sb-ssl.google.com:443/safebrowsing") || urlStr.startsWith("http://en-us.fxfeeds.mozilla.com/en-US/firefox/headlines.xml") || urlStr.startsWith("http://fxfeeds.mozilla.com/firefox/headlines.xml") || urlStr.startsWith("http://fxfeeds.mozilla.com/en-US/firefox/headlines.xml") || urlStr.startsWith("http://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml")) { // don't even xfer these! request.setHandled(true); return -1; } // this request must have come in just as we were shutting down, since there is no more associted http client // so let's just handle it like we do any other request we don't know what to do with :) if (httpClient == null) { // don't even xfer these! request.setHandled(true); return -1; // for debugging purposes, NOT to be used in product! // httpClient = new BrowserMobHttpClient(Integer.MAX_VALUE); // httpClient.setDecompress(false); // httpClient.setFollowRedirects(false); } BrowserMobHttpRequest httpReq = null; if ("GET".equals(request.getMethod())) { httpReq = httpClient.newGet(urlStr); } else if ("POST".equals(request.getMethod())) { httpReq = httpClient.newPost(urlStr); } else if ("PUT".equals(request.getMethod())) { httpReq = httpClient.newPut(urlStr); } else if ("DELETE".equals(request.getMethod())) { httpReq = httpClient.newDelete(urlStr); } else if ("OPTIONS".equals(request.getMethod())) { httpReq = httpClient.newOptions(urlStr); } else if ("HEAD".equals(request.getMethod())) { httpReq = httpClient.newHead(urlStr); } else { LOG.warn("Unexpected request method %s, giving up", request.getMethod()); request.setHandled(true); return -1; } // copy request headers boolean isGet = "GET".equals(request.getMethod()); boolean hasContent = false; Enumeration enm = request.getFieldNames(); long contentLength = 0; while (enm.hasMoreElements()) { String hdr = (String) enm.nextElement(); if (!isGet && HttpFields.__ContentType.equals(hdr)) { hasContent = true; } if (!isGet && HttpFields.__ContentLength.equals(hdr)) { contentLength = Long.parseLong(request.getField(hdr)); continue; } Enumeration vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { if ("User-Agent".equals(hdr)) { val = updateUserAgent(val); } // don't proxy Referer headers if the referer is Selenium! if ("Referer".equals(hdr) && (-1 != val.indexOf("/selenium-server/"))) { continue; } if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) { hasContent = true; } httpReq.addRequestHeader(hdr, val); } } } try { // do input thang! InputStream in = request.getInputStream(); if (hasContent) { httpReq.setRequestInputStream(in, contentLength); } } catch (Exception e) { LOG.fine(e.getMessage(), e); } // execute the request httpReq.setOutputStream(response.getOutputStream()); httpReq.setRequestCallback(new RequestCallback() { @Override public void handleStatusLine(StatusLine statusLine) { response.setStatus(statusLine.getStatusCode()); response.setReason(statusLine.getReasonPhrase()); } @Override public void handleHeaders(Header[] headers) { for (Header header : headers) { if (reportHeader(header)) { response.addField(header.getName(), header.getValue()); } } } @Override public boolean reportHeader(Header header) { // don't pass in things like Transfer-Encoding and other headers that are being masked by the underlying HttpClient impl return !_DontProxyHeaders.containsKey(header.getName()) && !_ProxyAuthHeaders.containsKey(header.getName()); } @Override public void reportError(Exception e) { BrowserMobProxyHandler.reportError(e, url, response); } }); BrowserMobHttpResponse httpRes = httpReq.execute(); // ALWAYS mark the request as handled if we actually handled it. Otherwise, Jetty will think non 2xx responses // mean it wasn't actually handled, resulting in totally valid 304 Not Modified requests turning in to 404 responses // from Jetty. NOT good :( request.setHandled(true); return httpRes.getEntry().getResponse().getBodySize(); } catch (BadURIException e) { // this is a known error case (see MOB-93) LOG.info(e.getMessage()); BrowserMobProxyHandler.reportError(e, url, response); return -1; } catch (Exception e) { LOG.info("Exception while proxying " + url, e); BrowserMobProxyHandler.reportError(e, url, response); return -1; } }
diff --git a/wingx/src/java/org/wingx/plaf/css/CalendarCG.java b/wingx/src/java/org/wingx/plaf/css/CalendarCG.java index 67ebfc2..f7c90a1 100644 --- a/wingx/src/java/org/wingx/plaf/css/CalendarCG.java +++ b/wingx/src/java/org/wingx/plaf/css/CalendarCG.java @@ -1,216 +1,216 @@ /* * CalendarCG.java * * Created on 12. Juni 2006, 09:03 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.wingx.plaf.css; import org.wings.*; import org.wings.header.Header; import org.wings.header.SessionHeaders; import org.wings.plaf.Update; import org.wings.plaf.css.AbstractComponentCG; import org.wings.plaf.css.AbstractUpdate; import org.wings.plaf.css.UpdateHandler; import org.wings.plaf.css.Utils; import org.wings.plaf.css.script.OnHeadersLoadedScript; import org.wings.session.Browser; import org.wings.session.BrowserType; import org.wings.session.ScriptManager; import org.wings.session.SessionManager; import org.wings.util.SStringBuilder; import org.wingx.XCalendar; import java.text.DateFormat; import java.text.Format; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Collections; /** * * * @author <a href="mailto:[email protected]">Erik Habicht</a> */ public class CalendarCG extends AbstractComponentCG implements org.wingx.plaf.CalendarCG { protected final static List<Header> headers; static { String[] images = new String [] { "org/wingx/calendar/calcd.gif", "org/wingx/calendar/cally.gif", "org/wingx/calendar/calry.gif" }; for ( int x = 0, y = images.length ; x < y ; x++ ) { new SResourceIcon(images[x]).getId(); // hack to externalize } List<Header> headerList = new ArrayList<Header>(); headerList.add(Utils.createExternalizedCSSHeaderFromProperty(Utils.CSS_YUI_ASSETS_CALENDAR)); headerList.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_YUI_CALENDAR)); headerList.add(Utils.createExternalizedJSHeader("org/wingx/calendar/xcalendar.js")); headers = Collections.unmodifiableList(headerList); } public CalendarCG() { } public void installCG(final SComponent component) { super.installCG(component); SessionHeaders.getInstance().registerHeaders(headers); } public void uninstallCG(SComponent component) { super.uninstallCG(component); SessionHeaders.getInstance().deregisterHeaders(headers); } public void writeInternal(org.wings.io.Device device, org.wings.SComponent _c ) throws java.io.IOException { final XCalendar component = (org.wingx.XCalendar) _c; final String id_hidden = "hidden" + component.getName(); final String id_button = "button" + component.getName(); final String id_cal = "cal"+component.getName(); SFormattedTextField fTextField = component.getFormattedTextField(); SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); dateFormat.setTimeZone( component.getTimeZone() ); device.print("<table"); Utils.writeAllAttributes(device, component); device.print("><tr><td class=\"tf\" width=\"*\""); int oversizePadding = Utils.calculateHorizontalOversize(fTextField, true); if (oversizePadding != 0) Utils.optAttribute(device, "oversize", oversizePadding); device.print('>'); SDimension preferredSize = component.getPreferredSize(); if (preferredSize != null && preferredSize.getWidth() != null && "auto".equals(preferredSize.getWidth())) fTextField.setPreferredSize(SDimension.FULLWIDTH); fTextField.setEnabled( component.isEnabled() ); fTextField.write(device); device.print("\n</td><td class=\"b\" width=\"1\">\n"); device.print("<input type=\"hidden\" id=\"").print(id_hidden) .print("\" name=\"").print(id_hidden) .print("\" value=\"").print( format(dateFormat, component.getDate() ) ) .print("\">\n"); device.print("<div style=\"display:inline;position:absolute;\" id=\"r").print(id_cal) .print("\"></div>"); - device.print("<img class=\"XCalendarButton\" id=\"").print(id_button) + device.print("<img id=\"").print(id_button) .print("\" src=\"").print( component.getEditIcon().getURL() ) .print("\" />\n"); String position = "fixed"; Browser browser = SessionManager.getSession().getUserAgent(); if (browser.getBrowserType() == BrowserType.IE && browser.getMajorVersion() < 7) { position = "absolute"; } device.print("<div style=\"display:none;position:").print(position) .print(";z-index:1001\" id=\"").print(id_cal).print("\"></div>"); writeTableSuffix(device, component); if ( component.isEnabled() ) { SimpleDateFormat format_months_long = new SimpleDateFormat("MMMMM"); format_months_long.setTimeZone( component.getTimeZone() ); SimpleDateFormat format_weekdays_short = new SimpleDateFormat("EE"); format_weekdays_short.setTimeZone( component.getTimeZone() ); SStringBuilder newXCalendar = new SStringBuilder("new YAHOO.widget.XCalendar("); newXCalendar.append('"').append( id_cal ).append("\","); newXCalendar.append("{close:true,"); newXCalendar.append("months_long:").append(createMonthsString( format_months_long ) ).append(','); newXCalendar.append("weekdays_short:").append(createWeekdaysString( format_weekdays_short ) ).append(','); newXCalendar.append("start_weekday:").append( (Calendar.getInstance().getFirstDayOfWeek()-1) ).append("},"); newXCalendar.append('"').append( component.getName() ).append("\","); newXCalendar.append('"').append( id_button ).append("\","); newXCalendar.append('"').append( id_hidden ).append('"'); newXCalendar.append( ");"); ScriptManager.getInstance().addScriptListener(new OnHeadersLoadedScript( newXCalendar.toString(), true)); } } private String createMonthsString ( Format format ) { SStringBuilder stringBuilder = new SStringBuilder(); stringBuilder.append('['); Calendar cal = new GregorianCalendar(); cal.set( Calendar.MONTH, cal.JANUARY ); for ( int x = 0, y = 12; x < y ; x++ ) { stringBuilder.append('"'); stringBuilder.append( format.format( cal.getTime() ) ); stringBuilder.append( "\","); cal.add( Calendar.MONTH, 1 ); } stringBuilder.deleteCharAt( stringBuilder.length()-1 ); stringBuilder.append(']'); return stringBuilder.toString(); } private String createWeekdaysString ( Format format ) { SStringBuilder stringBuilder = new SStringBuilder(); stringBuilder.append('['); Calendar cal = new GregorianCalendar(); cal.set( Calendar.DAY_OF_WEEK, Calendar.SUNDAY ); for ( int x = 0, y = 7; x < y ; x++ ) { stringBuilder.append('"'); stringBuilder.append( format.format( cal.getTime() ) ); stringBuilder.append( "\","); cal.add( Calendar.DAY_OF_WEEK, 1 ); } stringBuilder.deleteCharAt( stringBuilder.length()-1 ); stringBuilder.append(']'); return stringBuilder.toString(); } private String format(DateFormat dateFormat, Date date) { return date != null ? dateFormat.format( date ) : ""; } public Update getHiddenUpdate(XCalendar cal, Date date) { return new HiddenUpdate(cal, date); } protected static class HiddenUpdate extends AbstractUpdate { private Date date; public HiddenUpdate(XCalendar cal, Date date) { super(cal); this.date = date; } public Handler getHandler() { UpdateHandler handler = new UpdateHandler("value"); handler.addParameter("hidden"+component.getName()); final SimpleDateFormat dateFormatForHidden = new SimpleDateFormat("MM/dd/yyyy"); handler.addParameter(date == null ? "" : dateFormatForHidden.format( date ) ); return handler; } } }
true
true
public void writeInternal(org.wings.io.Device device, org.wings.SComponent _c ) throws java.io.IOException { final XCalendar component = (org.wingx.XCalendar) _c; final String id_hidden = "hidden" + component.getName(); final String id_button = "button" + component.getName(); final String id_cal = "cal"+component.getName(); SFormattedTextField fTextField = component.getFormattedTextField(); SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); dateFormat.setTimeZone( component.getTimeZone() ); device.print("<table"); Utils.writeAllAttributes(device, component); device.print("><tr><td class=\"tf\" width=\"*\""); int oversizePadding = Utils.calculateHorizontalOversize(fTextField, true); if (oversizePadding != 0) Utils.optAttribute(device, "oversize", oversizePadding); device.print('>'); SDimension preferredSize = component.getPreferredSize(); if (preferredSize != null && preferredSize.getWidth() != null && "auto".equals(preferredSize.getWidth())) fTextField.setPreferredSize(SDimension.FULLWIDTH); fTextField.setEnabled( component.isEnabled() ); fTextField.write(device); device.print("\n</td><td class=\"b\" width=\"1\">\n"); device.print("<input type=\"hidden\" id=\"").print(id_hidden) .print("\" name=\"").print(id_hidden) .print("\" value=\"").print( format(dateFormat, component.getDate() ) ) .print("\">\n"); device.print("<div style=\"display:inline;position:absolute;\" id=\"r").print(id_cal) .print("\"></div>"); device.print("<img class=\"XCalendarButton\" id=\"").print(id_button) .print("\" src=\"").print( component.getEditIcon().getURL() ) .print("\" />\n"); String position = "fixed"; Browser browser = SessionManager.getSession().getUserAgent(); if (browser.getBrowserType() == BrowserType.IE && browser.getMajorVersion() < 7) { position = "absolute"; } device.print("<div style=\"display:none;position:").print(position) .print(";z-index:1001\" id=\"").print(id_cal).print("\"></div>"); writeTableSuffix(device, component); if ( component.isEnabled() ) { SimpleDateFormat format_months_long = new SimpleDateFormat("MMMMM"); format_months_long.setTimeZone( component.getTimeZone() ); SimpleDateFormat format_weekdays_short = new SimpleDateFormat("EE"); format_weekdays_short.setTimeZone( component.getTimeZone() ); SStringBuilder newXCalendar = new SStringBuilder("new YAHOO.widget.XCalendar("); newXCalendar.append('"').append( id_cal ).append("\","); newXCalendar.append("{close:true,"); newXCalendar.append("months_long:").append(createMonthsString( format_months_long ) ).append(','); newXCalendar.append("weekdays_short:").append(createWeekdaysString( format_weekdays_short ) ).append(','); newXCalendar.append("start_weekday:").append( (Calendar.getInstance().getFirstDayOfWeek()-1) ).append("},"); newXCalendar.append('"').append( component.getName() ).append("\","); newXCalendar.append('"').append( id_button ).append("\","); newXCalendar.append('"').append( id_hidden ).append('"'); newXCalendar.append( ");"); ScriptManager.getInstance().addScriptListener(new OnHeadersLoadedScript( newXCalendar.toString(), true)); } }
public void writeInternal(org.wings.io.Device device, org.wings.SComponent _c ) throws java.io.IOException { final XCalendar component = (org.wingx.XCalendar) _c; final String id_hidden = "hidden" + component.getName(); final String id_button = "button" + component.getName(); final String id_cal = "cal"+component.getName(); SFormattedTextField fTextField = component.getFormattedTextField(); SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); dateFormat.setTimeZone( component.getTimeZone() ); device.print("<table"); Utils.writeAllAttributes(device, component); device.print("><tr><td class=\"tf\" width=\"*\""); int oversizePadding = Utils.calculateHorizontalOversize(fTextField, true); if (oversizePadding != 0) Utils.optAttribute(device, "oversize", oversizePadding); device.print('>'); SDimension preferredSize = component.getPreferredSize(); if (preferredSize != null && preferredSize.getWidth() != null && "auto".equals(preferredSize.getWidth())) fTextField.setPreferredSize(SDimension.FULLWIDTH); fTextField.setEnabled( component.isEnabled() ); fTextField.write(device); device.print("\n</td><td class=\"b\" width=\"1\">\n"); device.print("<input type=\"hidden\" id=\"").print(id_hidden) .print("\" name=\"").print(id_hidden) .print("\" value=\"").print( format(dateFormat, component.getDate() ) ) .print("\">\n"); device.print("<div style=\"display:inline;position:absolute;\" id=\"r").print(id_cal) .print("\"></div>"); device.print("<img id=\"").print(id_button) .print("\" src=\"").print( component.getEditIcon().getURL() ) .print("\" />\n"); String position = "fixed"; Browser browser = SessionManager.getSession().getUserAgent(); if (browser.getBrowserType() == BrowserType.IE && browser.getMajorVersion() < 7) { position = "absolute"; } device.print("<div style=\"display:none;position:").print(position) .print(";z-index:1001\" id=\"").print(id_cal).print("\"></div>"); writeTableSuffix(device, component); if ( component.isEnabled() ) { SimpleDateFormat format_months_long = new SimpleDateFormat("MMMMM"); format_months_long.setTimeZone( component.getTimeZone() ); SimpleDateFormat format_weekdays_short = new SimpleDateFormat("EE"); format_weekdays_short.setTimeZone( component.getTimeZone() ); SStringBuilder newXCalendar = new SStringBuilder("new YAHOO.widget.XCalendar("); newXCalendar.append('"').append( id_cal ).append("\","); newXCalendar.append("{close:true,"); newXCalendar.append("months_long:").append(createMonthsString( format_months_long ) ).append(','); newXCalendar.append("weekdays_short:").append(createWeekdaysString( format_weekdays_short ) ).append(','); newXCalendar.append("start_weekday:").append( (Calendar.getInstance().getFirstDayOfWeek()-1) ).append("},"); newXCalendar.append('"').append( component.getName() ).append("\","); newXCalendar.append('"').append( id_button ).append("\","); newXCalendar.append('"').append( id_hidden ).append('"'); newXCalendar.append( ");"); ScriptManager.getInstance().addScriptListener(new OnHeadersLoadedScript( newXCalendar.toString(), true)); } }
diff --git a/src/io/FileMonitor.java b/src/io/FileMonitor.java index 359ea3d..cd2e541 100644 --- a/src/io/FileMonitor.java +++ b/src/io/FileMonitor.java @@ -1,110 +1,110 @@ /** * */ package io; import java.io.*; import java.util.Observable; import java.util.Timer; import java.util.TimerTask; import general.Config; import general.Debug; /** * @author Michi * Ueberwacht einen Pfad, ob eine spezifizierte Datei existiert */ public class FileMonitor extends Observable { private File filePath; private Timer monitor; /** * Der TimerTask zum Ueberpruefen, ob eine Serverantwort in Form einer XML-Datei existiert * @author Michi * */ class CheckFileTask extends TimerTask { /** * Funktion die periodische nach Starten des Timers aufgerufen wird */ public void run() { if (filePath != null) { try { if (filePath.canRead()) { Debug.log(3, "Datei wurde gefunden und kann gelesen werden!"); ServerResponse serverResponse = new SimpleXMLParser(filePath).parse(); if (serverResponse != null) { // alle Oberserver informieren setChanged(); notifyObservers(serverResponse); //Stoppe Timer this.cancel(); //loesche Datei if (filePath.delete()) { - Debug.log(3, "Ursprungsdatei erfolgreich gel�scht!"); + Debug.log(3, "Ursprungsdatei erfolgreich geloescht!"); } - else Debug.error("Ursprungsdatei konnte nicht gel�scht werden!"); + else Debug.error("Ursprungsdatei konnte nicht geloescht werden!"); } } else { Debug.log(3, "Keine Datei unter angegebenem Pfad gefunden."); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { Debug.error("Error: Pfad zur zu ueberwachenden Datei nicht angegeben!"); } } } /** * Konstrukor * @param filePath Der Pfad, der ueberwacht werden soll */ public FileMonitor(File filePath) { this.filePath = filePath; } /** * Startet die Ueberwachung des Pfades */ public void startMonitoring() { // Timer starten monitor = new Timer(); monitor.schedule(new CheckFileTask(), 0, 1000//Config.TIMERINTERVALL ); Debug.log(3, "Monitoring gestartet!"); } /** * Stoppt die Ueberwachung des Pfades */ public void stopMonitoring() { if (this.monitor != null) { this.monitor.cancel(); Debug.log(3, "Monitoring gestoppt!"); } } public File getFilePath() { return filePath; } public void setFilePath(File filePath) { this.filePath = filePath; Debug.log(2, "Zu ueberwachenden Pfad geaendert in: " +filePath.toString()); } }
false
true
public void run() { if (filePath != null) { try { if (filePath.canRead()) { Debug.log(3, "Datei wurde gefunden und kann gelesen werden!"); ServerResponse serverResponse = new SimpleXMLParser(filePath).parse(); if (serverResponse != null) { // alle Oberserver informieren setChanged(); notifyObservers(serverResponse); //Stoppe Timer this.cancel(); //loesche Datei if (filePath.delete()) { Debug.log(3, "Ursprungsdatei erfolgreich gel�scht!"); } else Debug.error("Ursprungsdatei konnte nicht gel�scht werden!"); } } else { Debug.log(3, "Keine Datei unter angegebenem Pfad gefunden."); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { Debug.error("Error: Pfad zur zu ueberwachenden Datei nicht angegeben!"); } }
public void run() { if (filePath != null) { try { if (filePath.canRead()) { Debug.log(3, "Datei wurde gefunden und kann gelesen werden!"); ServerResponse serverResponse = new SimpleXMLParser(filePath).parse(); if (serverResponse != null) { // alle Oberserver informieren setChanged(); notifyObservers(serverResponse); //Stoppe Timer this.cancel(); //loesche Datei if (filePath.delete()) { Debug.log(3, "Ursprungsdatei erfolgreich geloescht!"); } else Debug.error("Ursprungsdatei konnte nicht geloescht werden!"); } } else { Debug.log(3, "Keine Datei unter angegebenem Pfad gefunden."); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { Debug.error("Error: Pfad zur zu ueberwachenden Datei nicht angegeben!"); } }
diff --git a/src/butterseal/src/edu/smcm/gamedev/butterseal/BSMap.java b/src/butterseal/src/edu/smcm/gamedev/butterseal/BSMap.java index f49c782..866e7e1 100644 --- a/src/butterseal/src/edu/smcm/gamedev/butterseal/BSMap.java +++ b/src/butterseal/src/edu/smcm/gamedev/butterseal/BSMap.java @@ -1,256 +1,257 @@ package edu.smcm.gamedev.butterseal; import java.util.Map; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.maps.MapLayer; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TiledMapTile; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; public enum BSMap { ICE_CAVE_ENTRY(BSAsset.ICE_CAVE_ENTRY, "ice-cave-entry", new BSGameStateActor() { @Override public void act(BSGameState state) { } @Override public void update(BSGameState state) { } @Override public void reset(BSGameState state) { } @Override public void load(BSGameState state) { } }), ICE_CAVE(BSAsset.ICE_CAVE, "ice-cave", new BSGameStateActor() { @Override public void act(BSGameState state) { BSMap m = state.currentMap; TiledMapTileLayer dark = m.getLayer("dark"); TiledMapTileLayer light = m.getLayer("light"); + TiledMapTileLayer wall = m.getLayer("wall"); TiledMapTile invis = BSTile.getTileForProperty(m, "invisible", "true"); if(state.currentTile.hasProperty(m, light, "beacon", "on")) { // Clear the surrounding tiles for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { BSTile lookingAt = new BSTile(state.currentTile); lookingAt.transpose(i, j); if(lookingAt.isContainedIn(dark)) { Cell point = lookingAt.getCell(dark); if(!point.getTile().equals(invis)) { if(ButterSeal.DEBUG > 2) { System.out.printf("Clearing tile %d,%d%n", lookingAt.x, lookingAt.y); } point.setTile(invis); } } } } // Clear the rank and file for(BSDirection d : BSDirection.values()) { if(ButterSeal.DEBUG > 2) { System.out.println("Clearing " + d); } BSTile point = new BSTile(state.currentTile); while(point.isContainedIn(dark) && - !point.hasProperty(m, m.playerLevel, "wall", "true")) { + !point.hasProperty(m, wall, "wall", "true")) { point.getCell(dark).setTile(invis); point.transpose(d.dx, d.dy); } if(point.isContainedIn(dark)) { Cell i = point.getCell(dark); i.setTile(invis); } } } } @Override public void update(BSGameState state) { BSMap m = state.currentMap; TiledMapTileLayer light = m.getLayer("light"); TiledMapTile beacon_on = BSTile.getTileForProperty(m, "beacon", "on"); // update beacon state if (state.isUsingPower && state.selectedPower == BSPower.FIRE) { if (state.currentTile.hasProperty(m, light, "beacon", "off")) { state.currentTile.setProperty(light, "beacon", "on"); if(ButterSeal.DEBUG > 2) { System.out.println("Lighting beacon."); } state.currentTile.getCell(light).setTile(beacon_on); } state.isUsingPower = false; } if (state.currentTile.hasProperty(m, m.playerLevel, "objective", "true")) { if (state.isUsingPower && state.selectedPower == BSPower.ACTION) { if(!m.objectiveReached) { m.objectiveReached = true; state.setMusic(BSAsset.SECOND_MUSIC); state.world.addRoute(BSMap.ICE_CAVE, BSMap.ICE_CAVE_EXIT, null); if(!state.available_powers.contains(BSPower.LIGHT)) { state.available_powers.add(BSPower.LIGHT); } } } } } @Override public void reset(BSGameState state) { } @Override public void load(BSGameState state) { if(!state.available_powers.contains(BSPower.FIRE)) { state.available_powers.add(BSPower.FIRE); } BSMap m = state.nextMap; TiledMapTileLayer dark = m.getLayer("dark"); TiledMapTileLayer light = m.getLayer("light"); TiledMapTile invis = BSTile.getTileForProperty(m, "invisible", "true"); for(int row = 0; row < m.playerLevel.getHeight(); row++) { for(int col = 0; col < m.playerLevel.getWidth(); col++) { BSTile curr = new BSTile(row, col); if(curr.hasProperty(m, light, "light", "torch")) { if(ButterSeal.DEBUG > 3) { System.out.println("found torch"); } for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { Cell point = new BSTile(row + i, col + j).getCell(dark); if(!point.getTile().equals(invis)) { if(ButterSeal.DEBUG > 2) { System.out.printf("Clearing tile %d,%d%n", row + i, col + j); } point.setTile(invis); } } } } } } } }), ICE_CAVE_EXIT(BSAsset.ICE_CAVE_EXIT, "ice-cave-exit", new BSGameStateActor() { @Override public void act(BSGameState state) { } @Override public void update(BSGameState state) { } @Override public void reset(BSGameState state) { } @Override public void load(BSGameState state) { } }), HOUSE(BSAsset.HOUSE, "house", new BSGameStateActor() { @Override public void act(BSGameState state) { } @Override public void update(BSGameState state) { } @Override public void reset(BSGameState state) { } @Override public void load(BSGameState state) { } }), MAZE (BSAsset.MAZE, "maze", new BSGameStateActor() { @Override public void act(BSGameState state) { } @Override public void update(BSGameState state) { } @Override public void reset(BSGameState state) { } @Override public void load(BSGameState state) { } }); static final float PIXELS_PER_TILE = 64; TiledMap map; OrthogonalTiledMapRenderer renderer; BSAsset asset; String key; BSGameStateActor update; TiledMapTileLayer playerLevel; boolean objectiveReached; BSMap(BSAsset asset, String key, BSGameStateActor update) { this.map = new TmxMapLoader().load(asset.assetPath); this.renderer = new OrthogonalTiledMapRenderer(this.map, 1f/BSMap.PIXELS_PER_TILE); this.asset = asset; this.key = key; this.update = update; this.playerLevel = this.getLayer("player"); this.SetNullsToInvisible(); } void draw(OrthographicCamera camera) { this.renderer.setView(camera); this.renderer.render(); } BSTile getPlayer(String key) { BSTile ret = null; int h = playerLevel.getHeight(); int w = playerLevel.getWidth(); for(int row = 0; row < h; row++) { for(int col = 0; col < w; col++) { ret = new BSTile(row, col); Map<String, String> prop = ret.getProperties(this).get("player"); if (prop != null && prop.containsKey("player") && prop.get("player").equals(key)) { return ret; } } } return ret; } public static BSMap getByKey(String key) { for (BSMap m : BSMap.values()) { if (m.key.equals(key)) { return m; } } return null; } public void usePower(BSGameState state) { update.update(state); update.act(state); } public TiledMapTileLayer getLayer(String name) { return (TiledMapTileLayer) this.map.getLayers().get(name); } public void reset(BSGameState state) { this.update.reset(state); } public void load(BSGameState state) { this.update.load(state); } private void SetNullsToInvisible() { TiledMapTile invis = BSTile.getTileForProperty(this, "invisible", "true"); Cell c = new Cell(); c.setTile(invis); for(MapLayer layer : this.map.getLayers()) { TiledMapTileLayer l = (TiledMapTileLayer) layer; int h = l.getHeight(); int w = l.getWidth(); for(int row = 0; row < w; row++) { for(int col = 0; col < h; col++) { if(l.getCell(row, col) == null) { l.setCell(row, col, c); } } } } } } // Local Variables: // indent-tabs-mode: nil // End:
false
true
public void act(BSGameState state) { BSMap m = state.currentMap; TiledMapTileLayer dark = m.getLayer("dark"); TiledMapTileLayer light = m.getLayer("light"); TiledMapTile invis = BSTile.getTileForProperty(m, "invisible", "true"); if(state.currentTile.hasProperty(m, light, "beacon", "on")) { // Clear the surrounding tiles for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { BSTile lookingAt = new BSTile(state.currentTile); lookingAt.transpose(i, j); if(lookingAt.isContainedIn(dark)) { Cell point = lookingAt.getCell(dark); if(!point.getTile().equals(invis)) { if(ButterSeal.DEBUG > 2) { System.out.printf("Clearing tile %d,%d%n", lookingAt.x, lookingAt.y); } point.setTile(invis); } } } } // Clear the rank and file for(BSDirection d : BSDirection.values()) { if(ButterSeal.DEBUG > 2) { System.out.println("Clearing " + d); } BSTile point = new BSTile(state.currentTile); while(point.isContainedIn(dark) && !point.hasProperty(m, m.playerLevel, "wall", "true")) { point.getCell(dark).setTile(invis); point.transpose(d.dx, d.dy); } if(point.isContainedIn(dark)) { Cell i = point.getCell(dark); i.setTile(invis); } } } }
public void act(BSGameState state) { BSMap m = state.currentMap; TiledMapTileLayer dark = m.getLayer("dark"); TiledMapTileLayer light = m.getLayer("light"); TiledMapTileLayer wall = m.getLayer("wall"); TiledMapTile invis = BSTile.getTileForProperty(m, "invisible", "true"); if(state.currentTile.hasProperty(m, light, "beacon", "on")) { // Clear the surrounding tiles for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { BSTile lookingAt = new BSTile(state.currentTile); lookingAt.transpose(i, j); if(lookingAt.isContainedIn(dark)) { Cell point = lookingAt.getCell(dark); if(!point.getTile().equals(invis)) { if(ButterSeal.DEBUG > 2) { System.out.printf("Clearing tile %d,%d%n", lookingAt.x, lookingAt.y); } point.setTile(invis); } } } } // Clear the rank and file for(BSDirection d : BSDirection.values()) { if(ButterSeal.DEBUG > 2) { System.out.println("Clearing " + d); } BSTile point = new BSTile(state.currentTile); while(point.isContainedIn(dark) && !point.hasProperty(m, wall, "wall", "true")) { point.getCell(dark).setTile(invis); point.transpose(d.dx, d.dy); } if(point.isContainedIn(dark)) { Cell i = point.getCell(dark); i.setTile(invis); } } } }
diff --git a/org.dojotoolkit.optimizer/src/org/dojotoolkit/optimizer/CachingJSOptimizer.java b/org.dojotoolkit.optimizer/src/org/dojotoolkit/optimizer/CachingJSOptimizer.java index 4222d25..2bfc7fe 100644 --- a/org.dojotoolkit.optimizer/src/org/dojotoolkit/optimizer/CachingJSOptimizer.java +++ b/org.dojotoolkit.optimizer/src/org/dojotoolkit/optimizer/CachingJSOptimizer.java @@ -1,61 +1,62 @@ /* Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ package org.dojotoolkit.optimizer; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public abstract class CachingJSOptimizer implements JSOptimizer { private static Logger logger = Logger.getLogger("org.dojotoolkit.optimizer"); protected Map<String, JSAnalysisDataImpl> cache = null; protected Map<String, Object> lockMap = null; public CachingJSOptimizer() { cache = Collections.synchronizedMap(new HashMap<String, JSAnalysisDataImpl>()); lockMap = new HashMap<String, Object>(); } public JSAnalysisData getAnalysisData(String[] modules) throws IOException { String key = getKey(modules); logger.logp(Level.FINE, getClass().getName(), "getAnalysisData", "modules ["+key+"] in"); Object lock = null; synchronized (lockMap) { lock = lockMap.get(key); if (lock == null) { lock = new Object(); lockMap.put(key, lock); } } JSAnalysisDataImpl jsAnalysisData = null; synchronized (lock) { logger.logp(Level.FINE, getClass().getName(), "getAnalysisData", "modules ["+key+"] in lock"); jsAnalysisData = cache.get(key); if (jsAnalysisData == null || jsAnalysisData.isStale()) { - jsAnalysisData = _getAnalysisData(modules, false); + boolean useCache = jsAnalysisData == null ? true : !jsAnalysisData.isStale(); + jsAnalysisData = _getAnalysisData(modules, useCache); } cache.put(key, jsAnalysisData); logger.logp(Level.FINE, getClass().getName(), "getAnalysisData", "modules ["+key+"] out lock"); } logger.logp(Level.FINE, getClass().getName(), "getAnalysisData", "modules ["+key+"] out"); return jsAnalysisData; } protected abstract JSAnalysisDataImpl _getAnalysisData(String[] modules, boolean useCache) throws IOException; private static String getKey(String[] keyValues) { StringBuffer key = new StringBuffer(); for (String keyValue : keyValues) { key.append(keyValue); } return key.toString(); } }
true
true
public JSAnalysisData getAnalysisData(String[] modules) throws IOException { String key = getKey(modules); logger.logp(Level.FINE, getClass().getName(), "getAnalysisData", "modules ["+key+"] in"); Object lock = null; synchronized (lockMap) { lock = lockMap.get(key); if (lock == null) { lock = new Object(); lockMap.put(key, lock); } } JSAnalysisDataImpl jsAnalysisData = null; synchronized (lock) { logger.logp(Level.FINE, getClass().getName(), "getAnalysisData", "modules ["+key+"] in lock"); jsAnalysisData = cache.get(key); if (jsAnalysisData == null || jsAnalysisData.isStale()) { jsAnalysisData = _getAnalysisData(modules, false); } cache.put(key, jsAnalysisData); logger.logp(Level.FINE, getClass().getName(), "getAnalysisData", "modules ["+key+"] out lock"); } logger.logp(Level.FINE, getClass().getName(), "getAnalysisData", "modules ["+key+"] out"); return jsAnalysisData; }
public JSAnalysisData getAnalysisData(String[] modules) throws IOException { String key = getKey(modules); logger.logp(Level.FINE, getClass().getName(), "getAnalysisData", "modules ["+key+"] in"); Object lock = null; synchronized (lockMap) { lock = lockMap.get(key); if (lock == null) { lock = new Object(); lockMap.put(key, lock); } } JSAnalysisDataImpl jsAnalysisData = null; synchronized (lock) { logger.logp(Level.FINE, getClass().getName(), "getAnalysisData", "modules ["+key+"] in lock"); jsAnalysisData = cache.get(key); if (jsAnalysisData == null || jsAnalysisData.isStale()) { boolean useCache = jsAnalysisData == null ? true : !jsAnalysisData.isStale(); jsAnalysisData = _getAnalysisData(modules, useCache); } cache.put(key, jsAnalysisData); logger.logp(Level.FINE, getClass().getName(), "getAnalysisData", "modules ["+key+"] out lock"); } logger.logp(Level.FINE, getClass().getName(), "getAnalysisData", "modules ["+key+"] out"); return jsAnalysisData; }
diff --git a/src/net/blockscape/helper/DrawingAndLogicHelper.java b/src/net/blockscape/helper/DrawingAndLogicHelper.java index 8c49c52..0e1505d 100644 --- a/src/net/blockscape/helper/DrawingAndLogicHelper.java +++ b/src/net/blockscape/helper/DrawingAndLogicHelper.java @@ -1,71 +1,71 @@ package net.blockscape.helper; import net.blockscape.BlockScape; import net.blockscape.Player; import net.blockscape.block.Block; import net.blockscape.world.World; import net.blockscape.world.WorldBlock; import processing.core.PApplet; public class DrawingAndLogicHelper { static float rotSinTim; /** * Called every time the game loops * @param host the game window */ public static void draw(PApplet host){ host.textFont(host.createFont("Arial",14,true)); for(WorldBlock b: World.getWorld()){ b.updateAndDraw(); } rotSinTim += 0.05; Player.setYvelocity(Player.getYvelocity() + 0.1F); BlockScape.distBetweenPlayerAndMouse = PApplet.dist(Player.getX()+Player.getWidth()/2, Player.getY()+Player.getHeight()/2, host.mouseX, host.mouseY)/16; - if(BlockScape.distBetweenPlayerAndMouse< BlockScape.maxReachDistance){ + if(BlockScape.distBetweenPlayerAndMouse< BlockScape.maxReachDistance && BlockScape.distBetweenPlayerAndMouse > 1){ BlockScape.canPlaceOrRemoveBlock = true; }else{ BlockScape.canPlaceOrRemoveBlock = false; } Player.update(); Player.draw(); if(((BlockScape)host).selectedBlock != null){ float r = PApplet.map(PApplet.sin(rotSinTim), -1, 1, -16, 16); host.pushMatrix(); host.translate(175, 24); host.imageMode(PApplet.CENTER); host.rectMode(PApplet.CENTER); host.rotate(PApplet.radians(r)); host.image(((BlockScape)host).selectedBlock.getTexture(),0, 0, 16, 16); if(!BlockScape.canPlaceOrRemoveBlock){ host.fill(0,100); host.rect(0, 0, 16, 16); } host.popMatrix(); host.rectMode(PApplet.CORNER); host.fill(0); host.text("Currently Selected Block:", 1, 30); host.fill(BlockScape.canPlaceOrRemoveBlock ? 200: 0); host.text(((BlockScape)host).selectedBlock.getName(), 190, 30); host.rectMode(PApplet.CORNER); }else{ ((BlockScape)host).selectedBlock = Block.blockStone; } //Check for block placement and removal if (host.mousePressed && host.mouseButton==PApplet.RIGHT && BlockScape.canPlaceOrRemoveBlock) { World.addBlockWithoutReplacing(new WorldBlock(host.mouseX/16, (host.height - host.mouseY)/16, ((BlockScape)host).selectedBlock, host)); } if (host.mousePressed && host.mouseButton==PApplet.LEFT && BlockScape.canPlaceOrRemoveBlock) { World.removeBlockFromWorld(host.mouseX/16, (host.height - host.mouseY)/16); } } }
true
true
public static void draw(PApplet host){ host.textFont(host.createFont("Arial",14,true)); for(WorldBlock b: World.getWorld()){ b.updateAndDraw(); } rotSinTim += 0.05; Player.setYvelocity(Player.getYvelocity() + 0.1F); BlockScape.distBetweenPlayerAndMouse = PApplet.dist(Player.getX()+Player.getWidth()/2, Player.getY()+Player.getHeight()/2, host.mouseX, host.mouseY)/16; if(BlockScape.distBetweenPlayerAndMouse< BlockScape.maxReachDistance){ BlockScape.canPlaceOrRemoveBlock = true; }else{ BlockScape.canPlaceOrRemoveBlock = false; } Player.update(); Player.draw(); if(((BlockScape)host).selectedBlock != null){ float r = PApplet.map(PApplet.sin(rotSinTim), -1, 1, -16, 16); host.pushMatrix(); host.translate(175, 24); host.imageMode(PApplet.CENTER); host.rectMode(PApplet.CENTER); host.rotate(PApplet.radians(r)); host.image(((BlockScape)host).selectedBlock.getTexture(),0, 0, 16, 16); if(!BlockScape.canPlaceOrRemoveBlock){ host.fill(0,100); host.rect(0, 0, 16, 16); } host.popMatrix(); host.rectMode(PApplet.CORNER); host.fill(0); host.text("Currently Selected Block:", 1, 30); host.fill(BlockScape.canPlaceOrRemoveBlock ? 200: 0); host.text(((BlockScape)host).selectedBlock.getName(), 190, 30); host.rectMode(PApplet.CORNER); }else{ ((BlockScape)host).selectedBlock = Block.blockStone; } //Check for block placement and removal if (host.mousePressed && host.mouseButton==PApplet.RIGHT && BlockScape.canPlaceOrRemoveBlock) { World.addBlockWithoutReplacing(new WorldBlock(host.mouseX/16, (host.height - host.mouseY)/16, ((BlockScape)host).selectedBlock, host)); } if (host.mousePressed && host.mouseButton==PApplet.LEFT && BlockScape.canPlaceOrRemoveBlock) { World.removeBlockFromWorld(host.mouseX/16, (host.height - host.mouseY)/16); } }
public static void draw(PApplet host){ host.textFont(host.createFont("Arial",14,true)); for(WorldBlock b: World.getWorld()){ b.updateAndDraw(); } rotSinTim += 0.05; Player.setYvelocity(Player.getYvelocity() + 0.1F); BlockScape.distBetweenPlayerAndMouse = PApplet.dist(Player.getX()+Player.getWidth()/2, Player.getY()+Player.getHeight()/2, host.mouseX, host.mouseY)/16; if(BlockScape.distBetweenPlayerAndMouse< BlockScape.maxReachDistance && BlockScape.distBetweenPlayerAndMouse > 1){ BlockScape.canPlaceOrRemoveBlock = true; }else{ BlockScape.canPlaceOrRemoveBlock = false; } Player.update(); Player.draw(); if(((BlockScape)host).selectedBlock != null){ float r = PApplet.map(PApplet.sin(rotSinTim), -1, 1, -16, 16); host.pushMatrix(); host.translate(175, 24); host.imageMode(PApplet.CENTER); host.rectMode(PApplet.CENTER); host.rotate(PApplet.radians(r)); host.image(((BlockScape)host).selectedBlock.getTexture(),0, 0, 16, 16); if(!BlockScape.canPlaceOrRemoveBlock){ host.fill(0,100); host.rect(0, 0, 16, 16); } host.popMatrix(); host.rectMode(PApplet.CORNER); host.fill(0); host.text("Currently Selected Block:", 1, 30); host.fill(BlockScape.canPlaceOrRemoveBlock ? 200: 0); host.text(((BlockScape)host).selectedBlock.getName(), 190, 30); host.rectMode(PApplet.CORNER); }else{ ((BlockScape)host).selectedBlock = Block.blockStone; } //Check for block placement and removal if (host.mousePressed && host.mouseButton==PApplet.RIGHT && BlockScape.canPlaceOrRemoveBlock) { World.addBlockWithoutReplacing(new WorldBlock(host.mouseX/16, (host.height - host.mouseY)/16, ((BlockScape)host).selectedBlock, host)); } if (host.mousePressed && host.mouseButton==PApplet.LEFT && BlockScape.canPlaceOrRemoveBlock) { World.removeBlockFromWorld(host.mouseX/16, (host.height - host.mouseY)/16); } }
diff --git a/assignment4/Constraint.java b/assignment4/Constraint.java index 0114058..cc28828 100644 --- a/assignment4/Constraint.java +++ b/assignment4/Constraint.java @@ -1,69 +1,69 @@ import java.io.* ; import java.util.* ; import java.lang.* ; public class Constraint { // first operand private String first ; // second operand private String second ; // relation between operands private String op ; // create a constraint from a string // such as "a > b" public Constraint ( String s ) { if ( s.indexOf ( ">=" ) > 0 ) op = ">=" ; if ( s.indexOf ( "<=" ) > 0 ) op = "<=" ; - if ( s.indexOf ( "<=" ) > 0 ) - op = "<=" ; + if ( s.indexOf ( "=>" ) > 0 ) + op = "=>" ; if ( s.indexOf ( "=<" ) > 0 ) op = "=<" ; if ( s.indexOf ( "!=" ) > 0 ) op = "!=" ; if ( s.indexOf ( ">=" ) == -1 && s.indexOf ( "<=" ) == -1 && s.indexOf ( "<=" ) == -1 && s.indexOf ( "=<" ) == -1 && s.indexOf ( "!=" ) == -1 ) { if ( s.indexOf ( "<" ) > 0 ) op = "<" ; if ( s.indexOf ( "=" ) > 0 ) op = "=" ; if ( s.indexOf ( ">" ) > 0 ) op = ">" ; } StringTokenizer tok = new StringTokenizer ( s, " <>=!" ) ; first = tok.nextToken () ; second = tok.nextToken () ; } // return the first operand public String getFirst () { return first ; } // return the second operand public String getSecond () { return second ; } // return the relation public String getOperation () { return op ; } public String toString () { return "Constraint: " + first + " " + op + " " + second ; } }
true
true
public Constraint ( String s ) { if ( s.indexOf ( ">=" ) > 0 ) op = ">=" ; if ( s.indexOf ( "<=" ) > 0 ) op = "<=" ; if ( s.indexOf ( "<=" ) > 0 ) op = "<=" ; if ( s.indexOf ( "=<" ) > 0 ) op = "=<" ; if ( s.indexOf ( "!=" ) > 0 ) op = "!=" ; if ( s.indexOf ( ">=" ) == -1 && s.indexOf ( "<=" ) == -1 && s.indexOf ( "<=" ) == -1 && s.indexOf ( "=<" ) == -1 && s.indexOf ( "!=" ) == -1 ) { if ( s.indexOf ( "<" ) > 0 ) op = "<" ; if ( s.indexOf ( "=" ) > 0 ) op = "=" ; if ( s.indexOf ( ">" ) > 0 ) op = ">" ; } StringTokenizer tok = new StringTokenizer ( s, " <>=!" ) ; first = tok.nextToken () ; second = tok.nextToken () ; }
public Constraint ( String s ) { if ( s.indexOf ( ">=" ) > 0 ) op = ">=" ; if ( s.indexOf ( "<=" ) > 0 ) op = "<=" ; if ( s.indexOf ( "=>" ) > 0 ) op = "=>" ; if ( s.indexOf ( "=<" ) > 0 ) op = "=<" ; if ( s.indexOf ( "!=" ) > 0 ) op = "!=" ; if ( s.indexOf ( ">=" ) == -1 && s.indexOf ( "<=" ) == -1 && s.indexOf ( "<=" ) == -1 && s.indexOf ( "=<" ) == -1 && s.indexOf ( "!=" ) == -1 ) { if ( s.indexOf ( "<" ) > 0 ) op = "<" ; if ( s.indexOf ( "=" ) > 0 ) op = "=" ; if ( s.indexOf ( ">" ) > 0 ) op = ">" ; } StringTokenizer tok = new StringTokenizer ( s, " <>=!" ) ; first = tok.nextToken () ; second = tok.nextToken () ; }
diff --git a/Pigeon/trunk/src/pigeon/report/Utilities.java b/Pigeon/trunk/src/pigeon/report/Utilities.java index 12d4463..d05add7 100644 --- a/Pigeon/trunk/src/pigeon/report/Utilities.java +++ b/Pigeon/trunk/src/pigeon/report/Utilities.java @@ -1,151 +1,151 @@ /* Copyright (C) 2005, 2006, 2007 Paul Richards. 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 pigeon.report; import java.io.BufferedReader; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import java.util.TreeSet; import pigeon.model.Clock; import pigeon.model.Constants; import pigeon.model.Distance; import pigeon.model.Organization; import pigeon.model.Race; import pigeon.model.Time; /** Shared HTML bits. */ public final class Utilities { // Non-Creatable private Utilities() { } public static PrintStream writeHtmlHeader(OutputStream stream, String title) throws IOException { PrintStream out = new PrintStream(stream, false, "UTF-8"); out.print("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); out.print("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"); out.print("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); out.print("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); out.print("<head>\n"); out.print(" <title>" + title + "</title>\n"); out.print(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"); out.print(" <style type=\"text/css\">\n"); - out.print(" body { font-family: Verdana, sans-serif; }\n"); + out.print(" body { font-family: Verdana, sans-serif; white-space: nowrap; font-size: 8pt; }\n"); out.print(" .outer { text-align:center; page-break-after: always; }\n"); out.print(" .outer.last { page-break-after: auto; }\n"); out.print(" h1 { margin-bottom:10px; font-size:18pt; }\n"); out.print(" h2 { font-size:16pt; }\n"); out.print(" h3 { font-size:14pt; }\n"); out.print(" h2, h3 { margin-top:0; margin-bottom:5px; }\n"); out.print(" table { width:95%; border:1px solid #000000; border-collapse:collapse; font-size:10pt; margin-top:20px; }\n"); out.print(" th { border-bottom:3px solid #000000; text-align: left; }\n"); out.print(" td { border-bottom:1px solid #000000; page-break-inside:avoid; padding:3px 0 3px 0; }\n"); out.print(" </style>\n"); out.print("</head>\n"); out.print("<body>\n"); if (out.checkError()) { throw new IOException(); } return out; } public static void writeHtmlFooter(PrintStream out) throws IOException { out.print("</body>\n"); out.print("</html>\n"); out.flush(); if (out.checkError()) { throw new IOException(); } } /** Returns a list of the sections that were involved in a race, or an empty collection if no section information is available. */ public static List<String> participatingSections(Race race) { Set<String> result = new TreeSet<String>(); for (Clock clock: race.getClocks()) { String section = clock.getMember().getSection(); if (section != null) { result.add(section); } } return new ArrayList<String>(result); } public static String stringPrintf(String format, Object... args) { StringWriter buffer = new StringWriter(); PrintWriter writer = new PrintWriter(buffer); writer.printf(format, args); writer.flush(); return buffer.toString(); } public static BirdResult calculateVelocity(Organization club, Race race, Clock clock, Time time) { Date correctedClockTime = clock.convertMemberTimeToMasterTime(new Date(time.getMemberTime()), race); int nightsSpentSleeping = (int)(time.getMemberTime() / Constants.MILLISECONDS_PER_DAY); long timeSpentSleeping = nightsSpentSleeping * race.getLengthOfDarknessEachNight(); double flyTimeInSeconds = (correctedClockTime.getTime() - race.getLiberationDate().getTime() - timeSpentSleeping) / 1000.0; Distance distance = club.getDistanceEntry(clock.getMember(), race.getRacepoint()).getDistance(); double velocityInMetresPerSecond = distance.getMetres() / flyTimeInSeconds; return new BirdResult(velocityInMetresPerSecond, time, correctedClockTime, distance); } /** Takes a multi-line string and makes it ready for HTML output by inserting the required "br" tags. */ public static String insertBrTags(final String lines) { try { BufferedReader reader = new BufferedReader(new StringReader(lines)); StringBuffer result = new StringBuffer(); boolean firstLine = true; String line; while ((line = reader.readLine()) != null) { if (!firstLine) { result.append("<br/>"); } result.append(line); firstLine = false; } return result.toString(); } catch (IOException e) { throw new IllegalArgumentException("Not expecting any IOExceptions"); } } }
true
true
public static PrintStream writeHtmlHeader(OutputStream stream, String title) throws IOException { PrintStream out = new PrintStream(stream, false, "UTF-8"); out.print("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); out.print("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"); out.print("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); out.print("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); out.print("<head>\n"); out.print(" <title>" + title + "</title>\n"); out.print(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"); out.print(" <style type=\"text/css\">\n"); out.print(" body { font-family: Verdana, sans-serif; }\n"); out.print(" .outer { text-align:center; page-break-after: always; }\n"); out.print(" .outer.last { page-break-after: auto; }\n"); out.print(" h1 { margin-bottom:10px; font-size:18pt; }\n"); out.print(" h2 { font-size:16pt; }\n"); out.print(" h3 { font-size:14pt; }\n"); out.print(" h2, h3 { margin-top:0; margin-bottom:5px; }\n"); out.print(" table { width:95%; border:1px solid #000000; border-collapse:collapse; font-size:10pt; margin-top:20px; }\n"); out.print(" th { border-bottom:3px solid #000000; text-align: left; }\n"); out.print(" td { border-bottom:1px solid #000000; page-break-inside:avoid; padding:3px 0 3px 0; }\n"); out.print(" </style>\n"); out.print("</head>\n"); out.print("<body>\n"); if (out.checkError()) { throw new IOException(); } return out; }
public static PrintStream writeHtmlHeader(OutputStream stream, String title) throws IOException { PrintStream out = new PrintStream(stream, false, "UTF-8"); out.print("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); out.print("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"); out.print("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); out.print("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); out.print("<head>\n"); out.print(" <title>" + title + "</title>\n"); out.print(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"); out.print(" <style type=\"text/css\">\n"); out.print(" body { font-family: Verdana, sans-serif; white-space: nowrap; font-size: 8pt; }\n"); out.print(" .outer { text-align:center; page-break-after: always; }\n"); out.print(" .outer.last { page-break-after: auto; }\n"); out.print(" h1 { margin-bottom:10px; font-size:18pt; }\n"); out.print(" h2 { font-size:16pt; }\n"); out.print(" h3 { font-size:14pt; }\n"); out.print(" h2, h3 { margin-top:0; margin-bottom:5px; }\n"); out.print(" table { width:95%; border:1px solid #000000; border-collapse:collapse; font-size:10pt; margin-top:20px; }\n"); out.print(" th { border-bottom:3px solid #000000; text-align: left; }\n"); out.print(" td { border-bottom:1px solid #000000; page-break-inside:avoid; padding:3px 0 3px 0; }\n"); out.print(" </style>\n"); out.print("</head>\n"); out.print("<body>\n"); if (out.checkError()) { throw new IOException(); } return out; }
diff --git a/src/main/java/com/github/ucchyocean/ct/DelayedTeleportTask.java b/src/main/java/com/github/ucchyocean/ct/DelayedTeleportTask.java index fb64b83..fcd0cab 100644 --- a/src/main/java/com/github/ucchyocean/ct/DelayedTeleportTask.java +++ b/src/main/java/com/github/ucchyocean/ct/DelayedTeleportTask.java @@ -1,88 +1,89 @@ /* * @author ucchy * @license LGPLv3 * @copyright Copyright ucchy 2013 */ package com.github.ucchyocean.ct; import java.util.HashMap; import java.util.concurrent.ArrayBlockingQueue; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; /** * 遅延つきテレポート実行タスク * @author ucchy */ public class DelayedTeleportTask extends BukkitRunnable { private HashMap<Player, Location> locationMap; private ArrayBlockingQueue<Player> players; private int delay; private BukkitTask task; /** * コンストラクタ * @param locationMap * @param delay */ public DelayedTeleportTask(HashMap<Player, Location> locationMap, int delay) { this.locationMap = locationMap; this.delay = delay; players = new ArrayBlockingQueue<Player>(locationMap.size()); for ( Player p : locationMap.keySet() ) { players.add(p); } } /** * タスクを開始する */ public void startTask() { task = Bukkit.getScheduler().runTaskTimer(ColorTeaming.instance, this, delay, delay); } /** * @see java.lang.Runnable#run() */ @Override public void run() { if ( players.isEmpty() ) { // プレイヤー表示パケットを送信する (see issue #78) int packetDelay = ColorTeaming.instance.getCTConfig().getTeleportVisiblePacketSendDelay(); if ( packetDelay > 0 ) { Bukkit.getScheduler().runTaskLater(ColorTeaming.instance, new BukkitRunnable() { public void run() { for ( Player playerA : locationMap.keySet() ) { for ( Player playerB : locationMap.keySet() ) { + playerA.hidePlayer(playerB); playerA.showPlayer(playerB); } } } }, packetDelay); } // 自己キャンセル if ( task != null ) { Bukkit.getScheduler().cancelTask(task.getTaskId()); } return; } Player player = players.poll(); Location location = locationMap.get(player); if ( player != null && location != null ) { player.teleport(location, TeleportCause.PLUGIN); } } }
true
true
public void run() { if ( players.isEmpty() ) { // プレイヤー表示パケットを送信する (see issue #78) int packetDelay = ColorTeaming.instance.getCTConfig().getTeleportVisiblePacketSendDelay(); if ( packetDelay > 0 ) { Bukkit.getScheduler().runTaskLater(ColorTeaming.instance, new BukkitRunnable() { public void run() { for ( Player playerA : locationMap.keySet() ) { for ( Player playerB : locationMap.keySet() ) { playerA.showPlayer(playerB); } } } }, packetDelay); } // 自己キャンセル if ( task != null ) { Bukkit.getScheduler().cancelTask(task.getTaskId()); } return; } Player player = players.poll(); Location location = locationMap.get(player); if ( player != null && location != null ) { player.teleport(location, TeleportCause.PLUGIN); } }
public void run() { if ( players.isEmpty() ) { // プレイヤー表示パケットを送信する (see issue #78) int packetDelay = ColorTeaming.instance.getCTConfig().getTeleportVisiblePacketSendDelay(); if ( packetDelay > 0 ) { Bukkit.getScheduler().runTaskLater(ColorTeaming.instance, new BukkitRunnable() { public void run() { for ( Player playerA : locationMap.keySet() ) { for ( Player playerB : locationMap.keySet() ) { playerA.hidePlayer(playerB); playerA.showPlayer(playerB); } } } }, packetDelay); } // 自己キャンセル if ( task != null ) { Bukkit.getScheduler().cancelTask(task.getTaskId()); } return; } Player player = players.poll(); Location location = locationMap.get(player); if ( player != null && location != null ) { player.teleport(location, TeleportCause.PLUGIN); } }
diff --git a/fidget/src/main/java/org/opf_labs/fmts/fidget/SigGenCommand.java b/fidget/src/main/java/org/opf_labs/fmts/fidget/SigGenCommand.java index b1a641e..49e2f6d 100644 --- a/fidget/src/main/java/org/opf_labs/fmts/fidget/SigGenCommand.java +++ b/fidget/src/main/java/org/opf_labs/fmts/fidget/SigGenCommand.java @@ -1,132 +1,132 @@ /** * Copyright (C) 2012 Andrew Jackson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ package org.opf_labs.fmts.fidget; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.xml.bind.JAXBException; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.tika.mime.MimeTypeException; import org.opf_labs.fmts.fidget.droid.PRONOMSigGenerator; import org.opf_labs.fmts.fidget.droid.SigDefSubmission; import org.opf_labs.fmts.mimeinfo.MimeInfo; import org.opf_labs.fmts.mimeinfo.MimeInfoUtils; /** * @author Andrew Jackson <[email protected]> * */ public class SigGenCommand { @SuppressWarnings("static-access") public static void main( String[] args ) throws MimeTypeException, IOException { // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); // Main option, setting the signature file options.addOption( OptionBuilder.withLongOpt( "sig-file" ) .withDescription( "use this mime-info signature file" ) .hasArg() .withArgName("FILE") .create("s") ); // options.addOption( "A", "alone", false, "use only the supplied signature file, do not load the embedded ones" ); options.addOption( "C", "convert-to-droid", false, "convert supplied signature file into DROID form" ); options.addOption( "l", "list", false, "list all known types."); - options.addOption( "h", "help", false, "print help message"); + options.addOption( "?", "help", false, "print help message"); HelpFormatter formatter = new HelpFormatter(); try { // parse the command line arguments CommandLine line = parser.parse( options, args ); // validate that sig-file has been set String sigfile = null; if( line.hasOption( "sig-file" ) ) { // print the value of sig-file sigfile = line.getOptionValue( "sig-file" ); } // Check mode: if( line.hasOption("?") ) { // HELP mode: formatter.printHelp( "fidget [OPTION]... [FILE]...", options ); } else if( line.hasOption("C") ) { // Convert mode: if( sigfile == null ) { System.err.println("No signature file argument found!"); return; } System.out.println("Generate DROID signature..."); MimeInfo mi = null; try { mi = MimeInfoUtils.parser( new FileInputStream(sigfile) ); } catch (JAXBException e) { e.printStackTrace(); return; } SigDefSubmission sigdef = MimeInfoUtils.toDroidSigDef(mi); // TODO Make is possible to print out the signature submission definition? // This just creates a submission template, but we could output a PRONOM record too. PRONOMSigGenerator.generatePRONOMSigFile(sigdef); } else if( line.hasOption("l") ) { // Set up Tika: TikaSigTester tst = SigGenCommand.tikaStarter(sigfile, line.hasOption("A")); tst.printTypes(); } else { // We are in file identification mode: if( line.getArgList().size() == 0 ) { System.err.println("No identification test file found!"); return; } // Set up Tika: TikaSigTester tst = SigGenCommand.tikaStarter(sigfile, line.hasOption("A")); // Return result: System.out.println(""+tst.identify( new FileInputStream(""+line.getArgList().get(0)))); return; } } catch( ParseException exp ) { System.out.println( "Unexpected exception:" + exp.getMessage() ); } } private static TikaSigTester tikaStarter( String sigfile, boolean sigfileAlone ) throws MimeTypeException, IOException { TikaSigTester tst = new TikaSigTester(); if( sigfile != null ) { tst = new TikaSigTester( new File(sigfile), !sigfileAlone ); } return tst; } }
true
true
public static void main( String[] args ) throws MimeTypeException, IOException { // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); // Main option, setting the signature file options.addOption( OptionBuilder.withLongOpt( "sig-file" ) .withDescription( "use this mime-info signature file" ) .hasArg() .withArgName("FILE") .create("s") ); // options.addOption( "A", "alone", false, "use only the supplied signature file, do not load the embedded ones" ); options.addOption( "C", "convert-to-droid", false, "convert supplied signature file into DROID form" ); options.addOption( "l", "list", false, "list all known types."); options.addOption( "h", "help", false, "print help message"); HelpFormatter formatter = new HelpFormatter(); try { // parse the command line arguments CommandLine line = parser.parse( options, args ); // validate that sig-file has been set String sigfile = null; if( line.hasOption( "sig-file" ) ) { // print the value of sig-file sigfile = line.getOptionValue( "sig-file" ); } // Check mode: if( line.hasOption("?") ) { // HELP mode: formatter.printHelp( "fidget [OPTION]... [FILE]...", options ); } else if( line.hasOption("C") ) { // Convert mode: if( sigfile == null ) { System.err.println("No signature file argument found!"); return; } System.out.println("Generate DROID signature..."); MimeInfo mi = null; try { mi = MimeInfoUtils.parser( new FileInputStream(sigfile) ); } catch (JAXBException e) { e.printStackTrace(); return; } SigDefSubmission sigdef = MimeInfoUtils.toDroidSigDef(mi); // TODO Make is possible to print out the signature submission definition? // This just creates a submission template, but we could output a PRONOM record too. PRONOMSigGenerator.generatePRONOMSigFile(sigdef); } else if( line.hasOption("l") ) { // Set up Tika: TikaSigTester tst = SigGenCommand.tikaStarter(sigfile, line.hasOption("A")); tst.printTypes(); } else { // We are in file identification mode: if( line.getArgList().size() == 0 ) { System.err.println("No identification test file found!"); return; } // Set up Tika: TikaSigTester tst = SigGenCommand.tikaStarter(sigfile, line.hasOption("A")); // Return result: System.out.println(""+tst.identify( new FileInputStream(""+line.getArgList().get(0)))); return; } } catch( ParseException exp ) { System.out.println( "Unexpected exception:" + exp.getMessage() ); } }
public static void main( String[] args ) throws MimeTypeException, IOException { // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); // Main option, setting the signature file options.addOption( OptionBuilder.withLongOpt( "sig-file" ) .withDescription( "use this mime-info signature file" ) .hasArg() .withArgName("FILE") .create("s") ); // options.addOption( "A", "alone", false, "use only the supplied signature file, do not load the embedded ones" ); options.addOption( "C", "convert-to-droid", false, "convert supplied signature file into DROID form" ); options.addOption( "l", "list", false, "list all known types."); options.addOption( "?", "help", false, "print help message"); HelpFormatter formatter = new HelpFormatter(); try { // parse the command line arguments CommandLine line = parser.parse( options, args ); // validate that sig-file has been set String sigfile = null; if( line.hasOption( "sig-file" ) ) { // print the value of sig-file sigfile = line.getOptionValue( "sig-file" ); } // Check mode: if( line.hasOption("?") ) { // HELP mode: formatter.printHelp( "fidget [OPTION]... [FILE]...", options ); } else if( line.hasOption("C") ) { // Convert mode: if( sigfile == null ) { System.err.println("No signature file argument found!"); return; } System.out.println("Generate DROID signature..."); MimeInfo mi = null; try { mi = MimeInfoUtils.parser( new FileInputStream(sigfile) ); } catch (JAXBException e) { e.printStackTrace(); return; } SigDefSubmission sigdef = MimeInfoUtils.toDroidSigDef(mi); // TODO Make is possible to print out the signature submission definition? // This just creates a submission template, but we could output a PRONOM record too. PRONOMSigGenerator.generatePRONOMSigFile(sigdef); } else if( line.hasOption("l") ) { // Set up Tika: TikaSigTester tst = SigGenCommand.tikaStarter(sigfile, line.hasOption("A")); tst.printTypes(); } else { // We are in file identification mode: if( line.getArgList().size() == 0 ) { System.err.println("No identification test file found!"); return; } // Set up Tika: TikaSigTester tst = SigGenCommand.tikaStarter(sigfile, line.hasOption("A")); // Return result: System.out.println(""+tst.identify( new FileInputStream(""+line.getArgList().get(0)))); return; } } catch( ParseException exp ) { System.out.println( "Unexpected exception:" + exp.getMessage() ); } }
diff --git a/src/com/axelby/podax/QueueActivity.java b/src/com/axelby/podax/QueueActivity.java index f5eaf07..2d5200f 100644 --- a/src/com/axelby/podax/QueueActivity.java +++ b/src/com/axelby/podax/QueueActivity.java @@ -1,262 +1,256 @@ package com.axelby.podax; import android.app.ListActivity; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.View.OnTouchListener; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.ResourceCursorAdapter; import android.widget.TextView; import android.widget.ViewSwitcher; public class QueueActivity extends ListActivity implements OnTouchListener { static final int OPTION_REMOVEFROMQUEUE = 1; static final int OPTION_PLAY = 2; Uri queueUri = Uri.withAppendedPath(PodcastProvider.URI, "queue"); String[] projection = new String[] { PodcastProvider.COLUMN_ID, PodcastProvider.COLUMN_TITLE, PodcastProvider.COLUMN_SUBSCRIPTION_TITLE, PodcastProvider.COLUMN_QUEUE_POSITION, PodcastProvider.COLUMN_MEDIA_URL, PodcastProvider.COLUMN_FILE_SIZE, }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.queue); Cursor cursor = managedQuery(queueUri, projection, null, null, null); setListAdapter(new QueueListAdapter(this, cursor)); getListView().setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(QueueActivity.this, PodcastDetailActivity.class); intent.putExtra("com.axelby.podax.podcastId", (int)id); startActivity(intent); } }); getListView().setOnCreateContextMenuListener(new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterContextMenuInfo mi = (AdapterContextMenuInfo) menuInfo; Cursor c = (Cursor) getListAdapter().getItem(mi.position); PodcastCursor podcast = new PodcastCursor(QueueActivity.this, c); menu.add(ContextMenu.NONE, OPTION_REMOVEFROMQUEUE, ContextMenu.NONE, R.string.remove_from_queue); if (podcast.isDownloaded()) menu.add(ContextMenu.NONE, OPTION_PLAY, ContextMenu.NONE, R.string.play); } }); getListView().setOnTouchListener(this); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo(); Cursor cursor = (Cursor)getListAdapter().getItem(info.position); PodcastCursor podcast = new PodcastCursor(this, cursor); switch (item.getItemId()) { case OPTION_REMOVEFROMQUEUE: podcast.removeFromQueue(); break; case OPTION_PLAY: PodaxApp.getApp().play(podcast); } return true; } public boolean onTouch(View v, MotionEvent event) { QueueListAdapter adapter = (QueueListAdapter)getListAdapter(); if (adapter.getHeldPodcastId() == null) return false; ListView listView = getListView(); if (event.getAction() == MotionEvent.ACTION_UP) { adapter.unholdPodcast(); return true; } if (event.getAction() == MotionEvent.ACTION_MOVE) { int position = listView.pointToPosition((int) event.getX(), (int) event.getY()); if (position == -1) return true; for (int i = listView.getFirstVisiblePosition(); i <= listView.getLastVisiblePosition(); ++i) { Rect bounds = new Rect(); listView.getChildAt(i - listView.getFirstVisiblePosition()).getHitRect(bounds); dragLog(String.format("position %d: top: %d, bottom: %d, height %d, centerY: %d", i, bounds.top, bounds.bottom, bounds.height(), bounds.centerY())); } dragLog(String.format("pointing to y %f, position %d", event.getY(), position)); View listItem = listView.getChildAt(position - listView.getFirstVisiblePosition()); // no listview means we're below the last one if (listItem == null) { dragLogEnd(String.format("moving to last position: %d", getListAdapter().getCount())); adapter.setQueuePosition(getListAdapter().getCount()); return true; } // don't change anything if we're hovering over this one if (position == adapter.getHeldQueuePosition()) { dragLogEnd("hovering over held podcast"); return true; } // remove hidden podcast from ordering dragLog(String.format("comparing position %d and geld position %d", position, adapter.getHeldQueuePosition())); if (position >= adapter.getHeldQueuePosition()) { dragLog("subtracting 1 because we're past held"); position -= 1; } // move podcast to proper position Rect bounds = new Rect(); listItem.getHitRect(bounds); dragLog(String.format("height: %d, centerY: %d, eventY: %f", bounds.height(), bounds.centerY(), event.getY())); - // don't move podcast if it's in middle 20% to avoid jumping - if (event.getY() >= bounds.centerY() - bounds.height() * 0.1f && - event.getY() <= bounds.centerY() + bounds.height() * 0.1f) { - dragLogEnd("middle 20%"); - return true; - } // if pointer is in top half of item then put separator above, // otherwise below if (event.getY() > bounds.centerY()) position += 1; dragLogEnd(String.format("moving to position %d", position)); adapter.setQueuePosition(position); return true; } return false; } private final boolean logDragMessages = false; private void dragLog(String message) { if (logDragMessages) { Log.d("Podax", message); } } private void dragLogEnd(String message) { if (logDragMessages) { Log.d("Podax", message); Log.d("Podax", " "); } } private class QueueListAdapter extends ResourceCursorAdapter { private OnTouchListener downListener = new OnTouchListener() { public boolean onTouch(View view, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { int position = getListView().getPositionForView(view); position -= getListView().getFirstVisiblePosition(); dragLog(String.format("holding podcast at position %d", position)); QueueListAdapter.this.holdPodcast(position); return true; } return false; } }; private Long _heldPodcastId = null; private int _heldQueuePosition; public QueueListAdapter(Context context, Cursor cursor) { super(context, R.layout.queue_list_item, cursor); } @Override public void bindView(View view, Context context, Cursor cursor) { ViewSwitcher switcher = (ViewSwitcher)view; switcher.setMeasureAllChildren(false); View btn = view.findViewById(R.id.dragable); btn.setOnTouchListener(downListener); PodcastCursor podcast = new PodcastCursor(QueueActivity.this, cursor); view.setTag(podcast.getId()); TextView queueText = (TextView) view.findViewById(R.id.title); queueText.setText(podcast.getTitle()); TextView subscriptionText = (TextView) view .findViewById(R.id.subscription); subscriptionText.setText(podcast.getSubscriptionTitle()); if (_heldPodcastId != null && (long)podcast.getId() == (long)_heldPodcastId && switcher.getDisplayedChild() == 0) switcher.showNext(); if ((_heldPodcastId == null || (long)podcast.getId() != (long)_heldPodcastId) && switcher.getDisplayedChild() == 1) switcher.showPrevious(); } public void holdPodcast(int position) { _heldQueuePosition = position; _heldPodcastId = (Long)getListView().getChildAt(position).getTag(); notifyDataSetChanged(); } public void unholdPodcast() { _heldPodcastId = null; notifyDataSetChanged(); } public Long getHeldPodcastId() { return _heldPodcastId; } public int getHeldQueuePosition() { return _heldQueuePosition; } public void setQueuePosition(int position) { if (_heldPodcastId == null || _heldQueuePosition == position) return; // update the held cursor to have the new queue position // the queue will automatically reorder ContentValues heldValues = new ContentValues(); heldValues.put(PodcastProvider.COLUMN_QUEUE_POSITION, position + 1); Uri podcastUri = ContentUris.withAppendedId(PodcastProvider.URI, _heldPodcastId); getContentResolver().update(podcastUri, heldValues, null, null); _heldQueuePosition = position; getCursor().close(); changeCursor(managedQuery(queueUri, projection, null, null, null)); } } }
true
true
public boolean onTouch(View v, MotionEvent event) { QueueListAdapter adapter = (QueueListAdapter)getListAdapter(); if (adapter.getHeldPodcastId() == null) return false; ListView listView = getListView(); if (event.getAction() == MotionEvent.ACTION_UP) { adapter.unholdPodcast(); return true; } if (event.getAction() == MotionEvent.ACTION_MOVE) { int position = listView.pointToPosition((int) event.getX(), (int) event.getY()); if (position == -1) return true; for (int i = listView.getFirstVisiblePosition(); i <= listView.getLastVisiblePosition(); ++i) { Rect bounds = new Rect(); listView.getChildAt(i - listView.getFirstVisiblePosition()).getHitRect(bounds); dragLog(String.format("position %d: top: %d, bottom: %d, height %d, centerY: %d", i, bounds.top, bounds.bottom, bounds.height(), bounds.centerY())); } dragLog(String.format("pointing to y %f, position %d", event.getY(), position)); View listItem = listView.getChildAt(position - listView.getFirstVisiblePosition()); // no listview means we're below the last one if (listItem == null) { dragLogEnd(String.format("moving to last position: %d", getListAdapter().getCount())); adapter.setQueuePosition(getListAdapter().getCount()); return true; } // don't change anything if we're hovering over this one if (position == adapter.getHeldQueuePosition()) { dragLogEnd("hovering over held podcast"); return true; } // remove hidden podcast from ordering dragLog(String.format("comparing position %d and geld position %d", position, adapter.getHeldQueuePosition())); if (position >= adapter.getHeldQueuePosition()) { dragLog("subtracting 1 because we're past held"); position -= 1; } // move podcast to proper position Rect bounds = new Rect(); listItem.getHitRect(bounds); dragLog(String.format("height: %d, centerY: %d, eventY: %f", bounds.height(), bounds.centerY(), event.getY())); // don't move podcast if it's in middle 20% to avoid jumping if (event.getY() >= bounds.centerY() - bounds.height() * 0.1f && event.getY() <= bounds.centerY() + bounds.height() * 0.1f) { dragLogEnd("middle 20%"); return true; } // if pointer is in top half of item then put separator above, // otherwise below if (event.getY() > bounds.centerY()) position += 1; dragLogEnd(String.format("moving to position %d", position)); adapter.setQueuePosition(position); return true; } return false; }
public boolean onTouch(View v, MotionEvent event) { QueueListAdapter adapter = (QueueListAdapter)getListAdapter(); if (adapter.getHeldPodcastId() == null) return false; ListView listView = getListView(); if (event.getAction() == MotionEvent.ACTION_UP) { adapter.unholdPodcast(); return true; } if (event.getAction() == MotionEvent.ACTION_MOVE) { int position = listView.pointToPosition((int) event.getX(), (int) event.getY()); if (position == -1) return true; for (int i = listView.getFirstVisiblePosition(); i <= listView.getLastVisiblePosition(); ++i) { Rect bounds = new Rect(); listView.getChildAt(i - listView.getFirstVisiblePosition()).getHitRect(bounds); dragLog(String.format("position %d: top: %d, bottom: %d, height %d, centerY: %d", i, bounds.top, bounds.bottom, bounds.height(), bounds.centerY())); } dragLog(String.format("pointing to y %f, position %d", event.getY(), position)); View listItem = listView.getChildAt(position - listView.getFirstVisiblePosition()); // no listview means we're below the last one if (listItem == null) { dragLogEnd(String.format("moving to last position: %d", getListAdapter().getCount())); adapter.setQueuePosition(getListAdapter().getCount()); return true; } // don't change anything if we're hovering over this one if (position == adapter.getHeldQueuePosition()) { dragLogEnd("hovering over held podcast"); return true; } // remove hidden podcast from ordering dragLog(String.format("comparing position %d and geld position %d", position, adapter.getHeldQueuePosition())); if (position >= adapter.getHeldQueuePosition()) { dragLog("subtracting 1 because we're past held"); position -= 1; } // move podcast to proper position Rect bounds = new Rect(); listItem.getHitRect(bounds); dragLog(String.format("height: %d, centerY: %d, eventY: %f", bounds.height(), bounds.centerY(), event.getY())); // if pointer is in top half of item then put separator above, // otherwise below if (event.getY() > bounds.centerY()) position += 1; dragLogEnd(String.format("moving to position %d", position)); adapter.setQueuePosition(position); return true; } return false; }
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/jres/LibraryStandin.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/jres/LibraryStandin.java index 1e5c6095c..756a349a7 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/jres/LibraryStandin.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/jres/LibraryStandin.java @@ -1,189 +1,189 @@ /******************************************************************************* * Copyright (c) 2000, 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 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.debug.ui.jres; import java.net.URL; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.debug.ui.IJavaDebugUIConstants; import org.eclipse.jdt.launching.LibraryLocation; /** * Wrapper for an original library location, to support editing. * */ public final class LibraryStandin { private IPath fSystemLibrary; private IPath fSystemLibrarySource; private IPath fPackageRootPath; private URL fJavadocLocation; /** * Creates a new library standin on the given library location. */ public LibraryStandin(LibraryLocation libraryLocation) { fSystemLibrary= libraryLocation.getSystemLibraryPath(); setSystemLibrarySourcePath(libraryLocation.getSystemLibrarySourcePath()); setPackageRootPath(libraryLocation.getPackageRootPath()); setJavadocLocation(libraryLocation.getJavadocLocation()); } /** * Returns the JRE library jar location. * * @return The JRE library jar location. */ public IPath getSystemLibraryPath() { return fSystemLibrary; } /** * Returns the JRE library source zip location. * * @return The JRE library source zip location. */ public IPath getSystemLibrarySourcePath() { return fSystemLibrarySource; } /** * Sets the source location for this library. * * @param path path source archive or Path.EMPTY if none */ void setSystemLibrarySourcePath(IPath path) { fSystemLibrarySource = path; } /** * Returns the path to the default package in the sources zip file * * @return The path to the default package in the sources zip file. */ public IPath getPackageRootPath() { return fPackageRootPath; } /** * Sets the root source location within source archive. * * @param path path to root source location or Path.EMPTY if none */ void setPackageRootPath(IPath path) { fPackageRootPath = path; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (obj instanceof LibraryStandin) { LibraryStandin lib = (LibraryStandin)obj; return getSystemLibraryPath().equals(lib.getSystemLibraryPath()) && equals(getSystemLibrarySourcePath(), lib.getSystemLibrarySourcePath()) && equals(getPackageRootPath(), lib.getPackageRootPath()) && equalsOrNull(getJavadocLocation(), lib.getJavadocLocation()); } return false; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return getSystemLibraryPath().hashCode(); } /** * Returns whether the given paths are equal - either may be <code>null</code>. * @param path1 path to be compared * @param path2 path to be compared * @return whether the given paths are equal */ protected boolean equals(IPath path1, IPath path2) { return equalsOrNull(path1, path2); } /** * Returns whether the given objects are equal - either may be <code>null</code>. * @param o1 object to be compared * @param o2 object to be compared * @return whether the given objects are equal or both null * @since 3.1 */ private boolean equalsOrNull(Object o1, Object o2) { if (o1 == null) { return o2 == null; } if (o2 == null) { return false; } return o1.equals(o2); } /** * Returns the Javadoc location associated with this Library location. * * @return a url pointing to the Javadoc location associated with * this Library location, or <code>null</code> if none * @since 3.1 */ public URL getJavadocLocation() { return fJavadocLocation; } /** * Sets the javadoc location of this library. * * @param url The location of the javadoc for <code>library</code> or <code>null</code> * if none */ void setJavadocLocation(URL url) { fJavadocLocation = url; } /** * Returns an equivalent library location. * * @return library location */ LibraryLocation toLibraryLocation() { return new LibraryLocation(getSystemLibraryPath(), getSystemLibrarySourcePath(), getPackageRootPath(), getJavadocLocation()); } /** * Returns a status for this library describing any error states * * @return */ IStatus validate() { if (!getSystemLibraryPath().toFile().exists()) { return new Status(IStatus.ERROR, IJavaDebugUIConstants.PLUGIN_ID, IJavaDebugUIConstants.INTERNAL_ERROR,"System library does not exist: " + getSystemLibraryPath().toOSString(), null); //$NON-NLS-1$ } IPath path = getSystemLibrarySourcePath(); if (!path.isEmpty()) { if (!path.toFile().exists()) { // check for workspace resource IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(path); - if (resource == null && resource.exists()) { + if (resource == null || !resource.exists()) { return new Status(IStatus.ERROR, IJavaDebugUIConstants.PLUGIN_ID, IJavaDebugUIConstants.INTERNAL_ERROR, "Source attachment does not exist: " + path.toOSString(), null); //$NON-NLS-1$ } } } return Status.OK_STATUS; } }
true
true
IStatus validate() { if (!getSystemLibraryPath().toFile().exists()) { return new Status(IStatus.ERROR, IJavaDebugUIConstants.PLUGIN_ID, IJavaDebugUIConstants.INTERNAL_ERROR,"System library does not exist: " + getSystemLibraryPath().toOSString(), null); //$NON-NLS-1$ } IPath path = getSystemLibrarySourcePath(); if (!path.isEmpty()) { if (!path.toFile().exists()) { // check for workspace resource IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(path); if (resource == null && resource.exists()) { return new Status(IStatus.ERROR, IJavaDebugUIConstants.PLUGIN_ID, IJavaDebugUIConstants.INTERNAL_ERROR, "Source attachment does not exist: " + path.toOSString(), null); //$NON-NLS-1$ } } } return Status.OK_STATUS; }
IStatus validate() { if (!getSystemLibraryPath().toFile().exists()) { return new Status(IStatus.ERROR, IJavaDebugUIConstants.PLUGIN_ID, IJavaDebugUIConstants.INTERNAL_ERROR,"System library does not exist: " + getSystemLibraryPath().toOSString(), null); //$NON-NLS-1$ } IPath path = getSystemLibrarySourcePath(); if (!path.isEmpty()) { if (!path.toFile().exists()) { // check for workspace resource IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(path); if (resource == null || !resource.exists()) { return new Status(IStatus.ERROR, IJavaDebugUIConstants.PLUGIN_ID, IJavaDebugUIConstants.INTERNAL_ERROR, "Source attachment does not exist: " + path.toOSString(), null); //$NON-NLS-1$ } } } return Status.OK_STATUS; }
diff --git a/src/com/yahoo/platform/yui/compressor/CssCompressor.java b/src/com/yahoo/platform/yui/compressor/CssCompressor.java index 35e1b0c..55056ce 100644 --- a/src/com/yahoo/platform/yui/compressor/CssCompressor.java +++ b/src/com/yahoo/platform/yui/compressor/CssCompressor.java @@ -1,447 +1,447 @@ /* * YUI Compressor * http://developer.yahoo.com/yui/compressor/ * Author: Julien Lecomte - http://www.julienlecomte.net/ * Author: Isaac Schlueter - http://foohack.com/ * Author: Stoyan Stefanov - http://phpied.com/ * Contributor: Dan Beam - http://danbeam.org/ * Copyright (c) 2012 Yahoo! Inc. All rights reserved. * The copyrights embodied in the content of this file are licensed * by Yahoo! Inc. under the BSD (revised) open source license. */ package com.yahoo.platform.yui.compressor; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.ArrayList; public class CssCompressor { private StringBuffer srcsb = new StringBuffer(); public CssCompressor(Reader in) throws IOException { // Read the stream... int c; while ((c = in.read()) != -1) { srcsb.append((char) c); } } // Leave data urls alone to increase parse performance. protected String extractDataUrls(String css, ArrayList preservedTokens) { int maxIndex = css.length() - 1; int appendIndex = 0; StringBuffer sb = new StringBuffer(); Pattern p = Pattern.compile("(?i)url\\(\\s*([\"']?)data\\:"); Matcher m = p.matcher(css); /* * Since we need to account for non-base64 data urls, we need to handle * ' and ) being part of the data string. Hence switching to indexOf, * to determine whether or not we have matching string terminators and * handling sb appends directly, instead of using matcher.append* methods. */ while (m.find()) { int startIndex = m.start() + 4; // "url(".length() String terminator = m.group(1); // ', " or empty (not quoted) if (terminator.length() == 0) { terminator = ")"; } boolean foundTerminator = false; int endIndex = m.end() - 1; while(foundTerminator == false && endIndex+1 <= maxIndex) { endIndex = css.indexOf(terminator, endIndex+1); if ((endIndex > 0) && (css.charAt(endIndex-1) != '\\')) { foundTerminator = true; if (!")".equals(terminator)) { endIndex = css.indexOf(")", endIndex); } } } // Enough searching, start moving stuff over to the buffer sb.append(css.substring(appendIndex, m.start())); if (foundTerminator) { String token = css.substring(startIndex, endIndex); token = token.replaceAll("\\s+", ""); preservedTokens.add(token); String preserver = "url(___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___)"; sb.append(preserver); appendIndex = endIndex + 1; } else { // No end terminator found, re-add the whole match. Should we throw/warn here? sb.append(css.substring(m.start(), m.end())); appendIndex = m.end(); } } sb.append(css.substring(appendIndex)); return sb.toString(); } public void compress(Writer out, int linebreakpos) throws IOException { Pattern p; Matcher m; String css = srcsb.toString(); int startIndex = 0; int endIndex = 0; int i = 0; int max = 0; ArrayList preservedTokens = new ArrayList(0); ArrayList comments = new ArrayList(0); String token; int totallen = css.length(); String placeholder; css = this.extractDataUrls(css, preservedTokens); StringBuffer sb = new StringBuffer(css); // collect all comment blocks... while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) { endIndex = sb.indexOf("*/", startIndex + 2); if (endIndex < 0) { endIndex = totallen; } token = sb.substring(startIndex + 2, endIndex); comments.add(token); sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___"); startIndex += 2; } css = sb.toString(); // preserve strings so their content doesn't get accidentally minified sb = new StringBuffer(); p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')"); m = p.matcher(css); while (m.find()) { token = m.group(); char quote = token.charAt(0); token = token.substring(1, token.length() - 1); // maybe the string contains a comment-like substring? // one, maybe more? put'em back then if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) { for (i = 0, max = comments.size(); i < max; i += 1) { token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString()); } } // minify alpha opacity in filter strings token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity="); preservedTokens.add(token); String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote; m.appendReplacement(sb, preserver); } m.appendTail(sb); css = sb.toString(); // strings are safe, now wrestle the comments for (i = 0, max = comments.size(); i < max; i += 1) { token = comments.get(i).toString(); placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___"; // ! in the first position of the comment means preserve // so push to the preserved tokens while stripping the ! if (token.startsWith("!")) { preservedTokens.add(token); css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___"); continue; } // \ in the last position looks like hack for Mac/IE5 // shorten that to /*\*/ and the next one to /**/ if (token.endsWith("\\")) { preservedTokens.add("\\"); css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___"); i = i + 1; // attn: advancing the loop preservedTokens.add(""); css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___"); continue; } // keep empty comments after child selectors (IE7 hack) // e.g. html >/**/ body if (token.length() == 0) { startIndex = css.indexOf(placeholder); if (startIndex > 2) { if (css.charAt(startIndex - 3) == '>') { preservedTokens.add(""); css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___"); } } } // in all other cases kill the comment css = css.replace("/*" + placeholder + "*/", ""); } // Normalize all whitespace strings to single spaces. Easier to work with that way. css = css.replaceAll("\\s+", " "); // Remove the spaces before the things that should not have spaces before them. // But, be careful not to turn "p :link {...}" into "p:link{...}" // Swap out any pseudo-class colons with the token, and then swap back. sb = new StringBuffer(); p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)"); m = p.matcher(css); while (m.find()) { String s = m.group(); s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___"); s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" ); m.appendReplacement(sb, s); } m.appendTail(sb); css = sb.toString(); // Remove spaces before the things that should not have spaces before them. css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1"); // bring back the colon css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":"); // retain space for special IE6 cases sb = new StringBuffer(); p = Pattern.compile("(?i):first\\-(line|letter)(\\{|,)"); m = p.matcher(css); while (m.find()) { - m.appendReplacement(sb, ":first-" + m.group(1).toLowerCase() + " " + m.group(2)); + m.appendReplacement(sb, ":first-" + m.group(1).toLowerCase() + " " + m.group(2)); } m.appendTail(sb); css = sb.toString(); // no space after the end of a preserved comment css = css.replaceAll("\\*/ ", "*/"); // If there are multiple @charset directives, push them to the top of the file. sb = new StringBuffer(); p = Pattern.compile("(?i)^(.*)(@charset)( \"[^\"]*\";)"); m = p.matcher(css); while (m.find()) { - m.appendReplacement(sb, m.group(2).toLowerCase() + m.group(3) + m.group(1)); + m.appendReplacement(sb, m.group(2).toLowerCase() + m.group(3) + m.group(1)); } m.appendTail(sb); css = sb.toString(); // When all @charset are at the top, remove the second and after (as they are completely ignored). sb = new StringBuffer(); p = Pattern.compile("(?i)^((\\s*)(@charset)( [^;]+;\\s*))+"); m = p.matcher(css); while (m.find()) { - m.appendReplacement(sb, m.group(2) + m.group(3).toLowerCase() + m.group(4)); + m.appendReplacement(sb, m.group(2) + m.group(3).toLowerCase() + m.group(4)); } m.appendTail(sb); css = sb.toString(); // lowercase some popular @directives (@charset is done right above) sb = new StringBuffer(); p = Pattern.compile("(?i)@(font-face|import|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?keyframe|media|page|namespace)"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, '@' + m.group(1).toLowerCase()); } m.appendTail(sb); css = sb.toString(); // lowercase some more common pseudo-elements sb = new StringBuffer(); p = Pattern.compile("(?i):(active|after|before|checked|disabled|empty|enabled|first-(?:child|of-type)|focus|hover|last-(?:child|of-type)|link|only-(?:child|of-type)|root|:selection|target|visited)"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, ':' + m.group(1).toLowerCase()); } m.appendTail(sb); css = sb.toString(); // lowercase some more common functions sb = new StringBuffer(); p = Pattern.compile("(?i):(lang|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|(?:-(?:moz|webkit)-)?any)\\("); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, ':' + m.group(1).toLowerCase() + '('); } m.appendTail(sb); css = sb.toString(); // lower case some common function that can be values // NOTE: rgb() isn't useful as we replace with #hex later, as well as and() is already done for us right after this sb = new StringBuffer(); p = Pattern.compile("(?i)([:,\\( ]\\s*)(attr|color-stop|from|rgba|to|url|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?(?:calc|max|min|(?:repeating-)?(?:linear|radial)-gradient)|-webkit-gradient)"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, m.group(1) + m.group(2).toLowerCase()); } m.appendTail(sb); css = sb.toString(); // Put the space back in some cases, to support stuff like // @media screen and (-webkit-min-device-pixel-ratio:0){ css = css.replaceAll("(?i)\\band\\(", "and ("); // Remove the spaces after the things that should not have spaces after them. css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1"); // remove unnecessary semicolons css = css.replaceAll(";+}", "}"); // Replace 0(px,em,%) with 0. css = css.replaceAll("(?i)(^|[^0-9])(?:0?\\.)?0(?:px|em|%|in|cm|mm|pc|pt|ex|deg|g?rad|m?s|k?hz)", "$10"); // Replace 0 0 0 0; with 0. css = css.replaceAll(":0 0 0 0(;|})", ":0$1"); css = css.replaceAll(":0 0 0(;|})", ":0$1"); css = css.replaceAll(":0 0(;|})", ":0$1"); // Replace background-position:0; with background-position:0 0; // same for transform-origin sb = new StringBuffer(); p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2)); } m.appendTail(sb); css = sb.toString(); // Replace 0.6 to .6, but only when preceded by : or a white-space css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2"); // Shorten colors from rgb(51,102,153) to #336699 // This makes it more likely that it'll get further compressed in the next step. p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { String[] rgbcolors = m.group(1).split(","); StringBuffer hexcolor = new StringBuffer("#"); for (i = 0; i < rgbcolors.length; i++) { int val = Integer.parseInt(rgbcolors[i]); if (val < 16) { hexcolor.append("0"); } hexcolor.append(Integer.toHexString(val)); } m.appendReplacement(sb, hexcolor.toString()); } m.appendTail(sb); css = sb.toString(); // Shorten colors from #AABBCC to #ABC. Note that we want to make sure // the color is not preceded by either ", " or =. Indeed, the property // filter: chroma(color="#FFFFFF"); // would become // filter: chroma(color="#FFF"); // which makes the filter break in IE. // We also want to make sure we're only compressing #AABBCC patterns inside { }, not id selectors ( #FAABAC {} ) // We also want to avoid compressing invalid values (e.g. #AABBCCD to #ABCD) p = Pattern.compile("(\\=\\s*?[\"']?)?" + "#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])" + "(:?\\}|[^0-9a-fA-F{][^{]*?\\})"); m = p.matcher(css); sb = new StringBuffer(); int index = 0; while (m.find(index)) { sb.append(css.substring(index, m.start())); boolean isFilter = (m.group(1) != null && !"".equals(m.group(1))); if (isFilter) { // Restore, as is. Compression will break filters sb.append(m.group(1) + "#" + m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)); } else { if( m.group(2).equalsIgnoreCase(m.group(3)) && m.group(4).equalsIgnoreCase(m.group(5)) && m.group(6).equalsIgnoreCase(m.group(7))) { // #AABBCC pattern sb.append("#" + (m.group(3) + m.group(5) + m.group(7)).toLowerCase()); } else { // Non-compressible color, restore, but lower case. sb.append("#" + (m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)).toLowerCase()); } } index = m.end(7); } sb.append(css.substring(index)); css = sb.toString(); // border: none -> border:0 sb = new StringBuffer(); p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-right|outline|background):none(;|})"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2)); } m.appendTail(sb); css = sb.toString(); // shorter opacity IE filter css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity="); // Remove empty rules. css = css.replaceAll("[^\\}\\{/;]+\\{\\}", ""); // TODO: Should this be after we re-insert tokens. These could alter the break points. However then // we'd need to make sure we don't break in the middle of a string etc. if (linebreakpos >= 0) { // Some source control tools don't like it when files containing lines longer // than, say 8000 characters, are checked in. The linebreak option is used in // that case to split long lines after a specific column. i = 0; int linestartpos = 0; sb = new StringBuffer(css); while (i < sb.length()) { char c = sb.charAt(i++); if (c == '}' && i - linestartpos > linebreakpos) { sb.insert(i, '\n'); linestartpos = i; } } css = sb.toString(); } // Replace multiple semi-colons in a row by a single one // See SF bug #1980989 css = css.replaceAll(";;+", ";"); // restore preserved comments and strings for(i = 0, max = preservedTokens.size(); i < max; i++) { css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString()); } // Trim the final string (for any leading or trailing white spaces) css = css.trim(); // Write the output... out.write(css); } }
false
true
public void compress(Writer out, int linebreakpos) throws IOException { Pattern p; Matcher m; String css = srcsb.toString(); int startIndex = 0; int endIndex = 0; int i = 0; int max = 0; ArrayList preservedTokens = new ArrayList(0); ArrayList comments = new ArrayList(0); String token; int totallen = css.length(); String placeholder; css = this.extractDataUrls(css, preservedTokens); StringBuffer sb = new StringBuffer(css); // collect all comment blocks... while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) { endIndex = sb.indexOf("*/", startIndex + 2); if (endIndex < 0) { endIndex = totallen; } token = sb.substring(startIndex + 2, endIndex); comments.add(token); sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___"); startIndex += 2; } css = sb.toString(); // preserve strings so their content doesn't get accidentally minified sb = new StringBuffer(); p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')"); m = p.matcher(css); while (m.find()) { token = m.group(); char quote = token.charAt(0); token = token.substring(1, token.length() - 1); // maybe the string contains a comment-like substring? // one, maybe more? put'em back then if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) { for (i = 0, max = comments.size(); i < max; i += 1) { token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString()); } } // minify alpha opacity in filter strings token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity="); preservedTokens.add(token); String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote; m.appendReplacement(sb, preserver); } m.appendTail(sb); css = sb.toString(); // strings are safe, now wrestle the comments for (i = 0, max = comments.size(); i < max; i += 1) { token = comments.get(i).toString(); placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___"; // ! in the first position of the comment means preserve // so push to the preserved tokens while stripping the ! if (token.startsWith("!")) { preservedTokens.add(token); css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___"); continue; } // \ in the last position looks like hack for Mac/IE5 // shorten that to /*\*/ and the next one to /**/ if (token.endsWith("\\")) { preservedTokens.add("\\"); css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___"); i = i + 1; // attn: advancing the loop preservedTokens.add(""); css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___"); continue; } // keep empty comments after child selectors (IE7 hack) // e.g. html >/**/ body if (token.length() == 0) { startIndex = css.indexOf(placeholder); if (startIndex > 2) { if (css.charAt(startIndex - 3) == '>') { preservedTokens.add(""); css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___"); } } } // in all other cases kill the comment css = css.replace("/*" + placeholder + "*/", ""); } // Normalize all whitespace strings to single spaces. Easier to work with that way. css = css.replaceAll("\\s+", " "); // Remove the spaces before the things that should not have spaces before them. // But, be careful not to turn "p :link {...}" into "p:link{...}" // Swap out any pseudo-class colons with the token, and then swap back. sb = new StringBuffer(); p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)"); m = p.matcher(css); while (m.find()) { String s = m.group(); s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___"); s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" ); m.appendReplacement(sb, s); } m.appendTail(sb); css = sb.toString(); // Remove spaces before the things that should not have spaces before them. css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1"); // bring back the colon css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":"); // retain space for special IE6 cases sb = new StringBuffer(); p = Pattern.compile("(?i):first\\-(line|letter)(\\{|,)"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, ":first-" + m.group(1).toLowerCase() + " " + m.group(2)); } m.appendTail(sb); css = sb.toString(); // no space after the end of a preserved comment css = css.replaceAll("\\*/ ", "*/"); // If there are multiple @charset directives, push them to the top of the file. sb = new StringBuffer(); p = Pattern.compile("(?i)^(.*)(@charset)( \"[^\"]*\";)"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, m.group(2).toLowerCase() + m.group(3) + m.group(1)); } m.appendTail(sb); css = sb.toString(); // When all @charset are at the top, remove the second and after (as they are completely ignored). sb = new StringBuffer(); p = Pattern.compile("(?i)^((\\s*)(@charset)( [^;]+;\\s*))+"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, m.group(2) + m.group(3).toLowerCase() + m.group(4)); } m.appendTail(sb); css = sb.toString(); // lowercase some popular @directives (@charset is done right above) sb = new StringBuffer(); p = Pattern.compile("(?i)@(font-face|import|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?keyframe|media|page|namespace)"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, '@' + m.group(1).toLowerCase()); } m.appendTail(sb); css = sb.toString(); // lowercase some more common pseudo-elements sb = new StringBuffer(); p = Pattern.compile("(?i):(active|after|before|checked|disabled|empty|enabled|first-(?:child|of-type)|focus|hover|last-(?:child|of-type)|link|only-(?:child|of-type)|root|:selection|target|visited)"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, ':' + m.group(1).toLowerCase()); } m.appendTail(sb); css = sb.toString(); // lowercase some more common functions sb = new StringBuffer(); p = Pattern.compile("(?i):(lang|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|(?:-(?:moz|webkit)-)?any)\\("); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, ':' + m.group(1).toLowerCase() + '('); } m.appendTail(sb); css = sb.toString(); // lower case some common function that can be values // NOTE: rgb() isn't useful as we replace with #hex later, as well as and() is already done for us right after this sb = new StringBuffer(); p = Pattern.compile("(?i)([:,\\( ]\\s*)(attr|color-stop|from|rgba|to|url|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?(?:calc|max|min|(?:repeating-)?(?:linear|radial)-gradient)|-webkit-gradient)"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, m.group(1) + m.group(2).toLowerCase()); } m.appendTail(sb); css = sb.toString(); // Put the space back in some cases, to support stuff like // @media screen and (-webkit-min-device-pixel-ratio:0){ css = css.replaceAll("(?i)\\band\\(", "and ("); // Remove the spaces after the things that should not have spaces after them. css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1"); // remove unnecessary semicolons css = css.replaceAll(";+}", "}"); // Replace 0(px,em,%) with 0. css = css.replaceAll("(?i)(^|[^0-9])(?:0?\\.)?0(?:px|em|%|in|cm|mm|pc|pt|ex|deg|g?rad|m?s|k?hz)", "$10"); // Replace 0 0 0 0; with 0. css = css.replaceAll(":0 0 0 0(;|})", ":0$1"); css = css.replaceAll(":0 0 0(;|})", ":0$1"); css = css.replaceAll(":0 0(;|})", ":0$1"); // Replace background-position:0; with background-position:0 0; // same for transform-origin sb = new StringBuffer(); p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2)); } m.appendTail(sb); css = sb.toString(); // Replace 0.6 to .6, but only when preceded by : or a white-space css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2"); // Shorten colors from rgb(51,102,153) to #336699 // This makes it more likely that it'll get further compressed in the next step. p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { String[] rgbcolors = m.group(1).split(","); StringBuffer hexcolor = new StringBuffer("#"); for (i = 0; i < rgbcolors.length; i++) { int val = Integer.parseInt(rgbcolors[i]); if (val < 16) { hexcolor.append("0"); } hexcolor.append(Integer.toHexString(val)); } m.appendReplacement(sb, hexcolor.toString()); } m.appendTail(sb); css = sb.toString(); // Shorten colors from #AABBCC to #ABC. Note that we want to make sure // the color is not preceded by either ", " or =. Indeed, the property // filter: chroma(color="#FFFFFF"); // would become // filter: chroma(color="#FFF"); // which makes the filter break in IE. // We also want to make sure we're only compressing #AABBCC patterns inside { }, not id selectors ( #FAABAC {} ) // We also want to avoid compressing invalid values (e.g. #AABBCCD to #ABCD) p = Pattern.compile("(\\=\\s*?[\"']?)?" + "#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])" + "(:?\\}|[^0-9a-fA-F{][^{]*?\\})"); m = p.matcher(css); sb = new StringBuffer(); int index = 0; while (m.find(index)) { sb.append(css.substring(index, m.start())); boolean isFilter = (m.group(1) != null && !"".equals(m.group(1))); if (isFilter) { // Restore, as is. Compression will break filters sb.append(m.group(1) + "#" + m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)); } else { if( m.group(2).equalsIgnoreCase(m.group(3)) && m.group(4).equalsIgnoreCase(m.group(5)) && m.group(6).equalsIgnoreCase(m.group(7))) { // #AABBCC pattern sb.append("#" + (m.group(3) + m.group(5) + m.group(7)).toLowerCase()); } else { // Non-compressible color, restore, but lower case. sb.append("#" + (m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)).toLowerCase()); } } index = m.end(7); } sb.append(css.substring(index)); css = sb.toString(); // border: none -> border:0 sb = new StringBuffer(); p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-right|outline|background):none(;|})"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2)); } m.appendTail(sb); css = sb.toString(); // shorter opacity IE filter css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity="); // Remove empty rules. css = css.replaceAll("[^\\}\\{/;]+\\{\\}", ""); // TODO: Should this be after we re-insert tokens. These could alter the break points. However then // we'd need to make sure we don't break in the middle of a string etc. if (linebreakpos >= 0) { // Some source control tools don't like it when files containing lines longer // than, say 8000 characters, are checked in. The linebreak option is used in // that case to split long lines after a specific column. i = 0; int linestartpos = 0; sb = new StringBuffer(css); while (i < sb.length()) { char c = sb.charAt(i++); if (c == '}' && i - linestartpos > linebreakpos) { sb.insert(i, '\n'); linestartpos = i; } } css = sb.toString(); } // Replace multiple semi-colons in a row by a single one // See SF bug #1980989 css = css.replaceAll(";;+", ";"); // restore preserved comments and strings for(i = 0, max = preservedTokens.size(); i < max; i++) { css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString()); } // Trim the final string (for any leading or trailing white spaces) css = css.trim(); // Write the output... out.write(css); }
public void compress(Writer out, int linebreakpos) throws IOException { Pattern p; Matcher m; String css = srcsb.toString(); int startIndex = 0; int endIndex = 0; int i = 0; int max = 0; ArrayList preservedTokens = new ArrayList(0); ArrayList comments = new ArrayList(0); String token; int totallen = css.length(); String placeholder; css = this.extractDataUrls(css, preservedTokens); StringBuffer sb = new StringBuffer(css); // collect all comment blocks... while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) { endIndex = sb.indexOf("*/", startIndex + 2); if (endIndex < 0) { endIndex = totallen; } token = sb.substring(startIndex + 2, endIndex); comments.add(token); sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___"); startIndex += 2; } css = sb.toString(); // preserve strings so their content doesn't get accidentally minified sb = new StringBuffer(); p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')"); m = p.matcher(css); while (m.find()) { token = m.group(); char quote = token.charAt(0); token = token.substring(1, token.length() - 1); // maybe the string contains a comment-like substring? // one, maybe more? put'em back then if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) { for (i = 0, max = comments.size(); i < max; i += 1) { token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString()); } } // minify alpha opacity in filter strings token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity="); preservedTokens.add(token); String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote; m.appendReplacement(sb, preserver); } m.appendTail(sb); css = sb.toString(); // strings are safe, now wrestle the comments for (i = 0, max = comments.size(); i < max; i += 1) { token = comments.get(i).toString(); placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___"; // ! in the first position of the comment means preserve // so push to the preserved tokens while stripping the ! if (token.startsWith("!")) { preservedTokens.add(token); css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___"); continue; } // \ in the last position looks like hack for Mac/IE5 // shorten that to /*\*/ and the next one to /**/ if (token.endsWith("\\")) { preservedTokens.add("\\"); css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___"); i = i + 1; // attn: advancing the loop preservedTokens.add(""); css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___"); continue; } // keep empty comments after child selectors (IE7 hack) // e.g. html >/**/ body if (token.length() == 0) { startIndex = css.indexOf(placeholder); if (startIndex > 2) { if (css.charAt(startIndex - 3) == '>') { preservedTokens.add(""); css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___"); } } } // in all other cases kill the comment css = css.replace("/*" + placeholder + "*/", ""); } // Normalize all whitespace strings to single spaces. Easier to work with that way. css = css.replaceAll("\\s+", " "); // Remove the spaces before the things that should not have spaces before them. // But, be careful not to turn "p :link {...}" into "p:link{...}" // Swap out any pseudo-class colons with the token, and then swap back. sb = new StringBuffer(); p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)"); m = p.matcher(css); while (m.find()) { String s = m.group(); s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___"); s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" ); m.appendReplacement(sb, s); } m.appendTail(sb); css = sb.toString(); // Remove spaces before the things that should not have spaces before them. css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1"); // bring back the colon css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":"); // retain space for special IE6 cases sb = new StringBuffer(); p = Pattern.compile("(?i):first\\-(line|letter)(\\{|,)"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, ":first-" + m.group(1).toLowerCase() + " " + m.group(2)); } m.appendTail(sb); css = sb.toString(); // no space after the end of a preserved comment css = css.replaceAll("\\*/ ", "*/"); // If there are multiple @charset directives, push them to the top of the file. sb = new StringBuffer(); p = Pattern.compile("(?i)^(.*)(@charset)( \"[^\"]*\";)"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, m.group(2).toLowerCase() + m.group(3) + m.group(1)); } m.appendTail(sb); css = sb.toString(); // When all @charset are at the top, remove the second and after (as they are completely ignored). sb = new StringBuffer(); p = Pattern.compile("(?i)^((\\s*)(@charset)( [^;]+;\\s*))+"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, m.group(2) + m.group(3).toLowerCase() + m.group(4)); } m.appendTail(sb); css = sb.toString(); // lowercase some popular @directives (@charset is done right above) sb = new StringBuffer(); p = Pattern.compile("(?i)@(font-face|import|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?keyframe|media|page|namespace)"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, '@' + m.group(1).toLowerCase()); } m.appendTail(sb); css = sb.toString(); // lowercase some more common pseudo-elements sb = new StringBuffer(); p = Pattern.compile("(?i):(active|after|before|checked|disabled|empty|enabled|first-(?:child|of-type)|focus|hover|last-(?:child|of-type)|link|only-(?:child|of-type)|root|:selection|target|visited)"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, ':' + m.group(1).toLowerCase()); } m.appendTail(sb); css = sb.toString(); // lowercase some more common functions sb = new StringBuffer(); p = Pattern.compile("(?i):(lang|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|(?:-(?:moz|webkit)-)?any)\\("); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, ':' + m.group(1).toLowerCase() + '('); } m.appendTail(sb); css = sb.toString(); // lower case some common function that can be values // NOTE: rgb() isn't useful as we replace with #hex later, as well as and() is already done for us right after this sb = new StringBuffer(); p = Pattern.compile("(?i)([:,\\( ]\\s*)(attr|color-stop|from|rgba|to|url|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?(?:calc|max|min|(?:repeating-)?(?:linear|radial)-gradient)|-webkit-gradient)"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, m.group(1) + m.group(2).toLowerCase()); } m.appendTail(sb); css = sb.toString(); // Put the space back in some cases, to support stuff like // @media screen and (-webkit-min-device-pixel-ratio:0){ css = css.replaceAll("(?i)\\band\\(", "and ("); // Remove the spaces after the things that should not have spaces after them. css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1"); // remove unnecessary semicolons css = css.replaceAll(";+}", "}"); // Replace 0(px,em,%) with 0. css = css.replaceAll("(?i)(^|[^0-9])(?:0?\\.)?0(?:px|em|%|in|cm|mm|pc|pt|ex|deg|g?rad|m?s|k?hz)", "$10"); // Replace 0 0 0 0; with 0. css = css.replaceAll(":0 0 0 0(;|})", ":0$1"); css = css.replaceAll(":0 0 0(;|})", ":0$1"); css = css.replaceAll(":0 0(;|})", ":0$1"); // Replace background-position:0; with background-position:0 0; // same for transform-origin sb = new StringBuffer(); p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2)); } m.appendTail(sb); css = sb.toString(); // Replace 0.6 to .6, but only when preceded by : or a white-space css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2"); // Shorten colors from rgb(51,102,153) to #336699 // This makes it more likely that it'll get further compressed in the next step. p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { String[] rgbcolors = m.group(1).split(","); StringBuffer hexcolor = new StringBuffer("#"); for (i = 0; i < rgbcolors.length; i++) { int val = Integer.parseInt(rgbcolors[i]); if (val < 16) { hexcolor.append("0"); } hexcolor.append(Integer.toHexString(val)); } m.appendReplacement(sb, hexcolor.toString()); } m.appendTail(sb); css = sb.toString(); // Shorten colors from #AABBCC to #ABC. Note that we want to make sure // the color is not preceded by either ", " or =. Indeed, the property // filter: chroma(color="#FFFFFF"); // would become // filter: chroma(color="#FFF"); // which makes the filter break in IE. // We also want to make sure we're only compressing #AABBCC patterns inside { }, not id selectors ( #FAABAC {} ) // We also want to avoid compressing invalid values (e.g. #AABBCCD to #ABCD) p = Pattern.compile("(\\=\\s*?[\"']?)?" + "#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])" + "(:?\\}|[^0-9a-fA-F{][^{]*?\\})"); m = p.matcher(css); sb = new StringBuffer(); int index = 0; while (m.find(index)) { sb.append(css.substring(index, m.start())); boolean isFilter = (m.group(1) != null && !"".equals(m.group(1))); if (isFilter) { // Restore, as is. Compression will break filters sb.append(m.group(1) + "#" + m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)); } else { if( m.group(2).equalsIgnoreCase(m.group(3)) && m.group(4).equalsIgnoreCase(m.group(5)) && m.group(6).equalsIgnoreCase(m.group(7))) { // #AABBCC pattern sb.append("#" + (m.group(3) + m.group(5) + m.group(7)).toLowerCase()); } else { // Non-compressible color, restore, but lower case. sb.append("#" + (m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)).toLowerCase()); } } index = m.end(7); } sb.append(css.substring(index)); css = sb.toString(); // border: none -> border:0 sb = new StringBuffer(); p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-right|outline|background):none(;|})"); m = p.matcher(css); while (m.find()) { m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2)); } m.appendTail(sb); css = sb.toString(); // shorter opacity IE filter css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity="); // Remove empty rules. css = css.replaceAll("[^\\}\\{/;]+\\{\\}", ""); // TODO: Should this be after we re-insert tokens. These could alter the break points. However then // we'd need to make sure we don't break in the middle of a string etc. if (linebreakpos >= 0) { // Some source control tools don't like it when files containing lines longer // than, say 8000 characters, are checked in. The linebreak option is used in // that case to split long lines after a specific column. i = 0; int linestartpos = 0; sb = new StringBuffer(css); while (i < sb.length()) { char c = sb.charAt(i++); if (c == '}' && i - linestartpos > linebreakpos) { sb.insert(i, '\n'); linestartpos = i; } } css = sb.toString(); } // Replace multiple semi-colons in a row by a single one // See SF bug #1980989 css = css.replaceAll(";;+", ";"); // restore preserved comments and strings for(i = 0, max = preservedTokens.size(); i < max; i++) { css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString()); } // Trim the final string (for any leading or trailing white spaces) css = css.trim(); // Write the output... out.write(css); }
diff --git a/parser/src/main/java/org/dna/mqtt/moquette/proto/SubscribeEncoder.java b/parser/src/main/java/org/dna/mqtt/moquette/proto/SubscribeEncoder.java index d5e5b0c..b22b0ec 100644 --- a/parser/src/main/java/org/dna/mqtt/moquette/proto/SubscribeEncoder.java +++ b/parser/src/main/java/org/dna/mqtt/moquette/proto/SubscribeEncoder.java @@ -1,45 +1,45 @@ package org.dna.mqtt.moquette.proto; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.AbstractMessage.QOSType; import org.dna.mqtt.moquette.proto.messages.SubscribeMessage; import org.dna.mqtt.moquette.proto.messages.SubscribeMessage.Couple; /** * * @author andrea */ public class SubscribeEncoder implements MessageEncoder<SubscribeMessage> { public void encode(IoSession session, SubscribeMessage message, ProtocolEncoderOutput out) throws Exception { if (message.subscriptions().isEmpty()) { throw new IllegalArgumentException("Found a subscribe message with empty topics"); } if (message.getQos() != QOSType.LEAST_ONE) { throw new IllegalArgumentException("Expected a message with QOS 1, found " + message.getQos()); } IoBuffer variableHeaderBuff = IoBuffer.allocate(4).setAutoExpand(true); Utils.writeWord(variableHeaderBuff, message.getMessageID()); for (Couple c : message.subscriptions()) { variableHeaderBuff.put(Utils.encodeString(c.getTopic())); variableHeaderBuff.put(c.getQos()); } variableHeaderBuff.flip(); int variableHeaderSize = variableHeaderBuff.remaining(); byte flags = Utils.encodeFlags(message); - IoBuffer buff = IoBuffer.allocate(4 + variableHeaderSize); + IoBuffer buff = IoBuffer.allocate(2 + variableHeaderSize); buff.put((byte) (AbstractMessage.SUBSCRIBE << 4 | flags)); - buff.put(Utils.encodeRemainingLength(4 + variableHeaderSize)); + buff.put(Utils.encodeRemainingLength(variableHeaderSize)); buff.put(variableHeaderBuff).flip(); out.write(buff); } }
false
true
public void encode(IoSession session, SubscribeMessage message, ProtocolEncoderOutput out) throws Exception { if (message.subscriptions().isEmpty()) { throw new IllegalArgumentException("Found a subscribe message with empty topics"); } if (message.getQos() != QOSType.LEAST_ONE) { throw new IllegalArgumentException("Expected a message with QOS 1, found " + message.getQos()); } IoBuffer variableHeaderBuff = IoBuffer.allocate(4).setAutoExpand(true); Utils.writeWord(variableHeaderBuff, message.getMessageID()); for (Couple c : message.subscriptions()) { variableHeaderBuff.put(Utils.encodeString(c.getTopic())); variableHeaderBuff.put(c.getQos()); } variableHeaderBuff.flip(); int variableHeaderSize = variableHeaderBuff.remaining(); byte flags = Utils.encodeFlags(message); IoBuffer buff = IoBuffer.allocate(4 + variableHeaderSize); buff.put((byte) (AbstractMessage.SUBSCRIBE << 4 | flags)); buff.put(Utils.encodeRemainingLength(4 + variableHeaderSize)); buff.put(variableHeaderBuff).flip(); out.write(buff); }
public void encode(IoSession session, SubscribeMessage message, ProtocolEncoderOutput out) throws Exception { if (message.subscriptions().isEmpty()) { throw new IllegalArgumentException("Found a subscribe message with empty topics"); } if (message.getQos() != QOSType.LEAST_ONE) { throw new IllegalArgumentException("Expected a message with QOS 1, found " + message.getQos()); } IoBuffer variableHeaderBuff = IoBuffer.allocate(4).setAutoExpand(true); Utils.writeWord(variableHeaderBuff, message.getMessageID()); for (Couple c : message.subscriptions()) { variableHeaderBuff.put(Utils.encodeString(c.getTopic())); variableHeaderBuff.put(c.getQos()); } variableHeaderBuff.flip(); int variableHeaderSize = variableHeaderBuff.remaining(); byte flags = Utils.encodeFlags(message); IoBuffer buff = IoBuffer.allocate(2 + variableHeaderSize); buff.put((byte) (AbstractMessage.SUBSCRIBE << 4 | flags)); buff.put(Utils.encodeRemainingLength(variableHeaderSize)); buff.put(variableHeaderBuff).flip(); out.write(buff); }
diff --git a/GAE/src/org/waterforpeople/mapping/app/web/rest/SurveyInstanceRestService.java b/GAE/src/org/waterforpeople/mapping/app/web/rest/SurveyInstanceRestService.java index 513cea04a..43e6d7915 100644 --- a/GAE/src/org/waterforpeople/mapping/app/web/rest/SurveyInstanceRestService.java +++ b/GAE/src/org/waterforpeople/mapping/app/web/rest/SurveyInstanceRestService.java @@ -1,246 +1,245 @@ /* * Copyright (C) 2012 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo FLOW. * * Akvo FLOW is free software: you can redistribute it and modify it under the terms of * the GNU Affero General Public License (AGPL) as published by the Free Software Foundation, * either version 3 of the License or any later version. * * Akvo FLOW 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 included below for more details. * * The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>. */ package org.waterforpeople.mapping.app.web.rest; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.waterforpeople.mapping.app.gwt.client.surveyinstance.SurveyInstanceDto; import org.waterforpeople.mapping.app.util.DtoMarshaller; import org.waterforpeople.mapping.app.web.rest.dto.RestStatusDto; import org.waterforpeople.mapping.app.web.rest.dto.SurveyInstancePayload; import org.waterforpeople.mapping.dao.SurveyInstanceDAO; import org.waterforpeople.mapping.domain.SurveyInstance; import com.gallatinsystems.survey.dao.SurveyDAO; import com.gallatinsystems.survey.dao.SurveyUtils; import com.gallatinsystems.survey.domain.Survey; @Controller @RequestMapping("/survey_instances") public class SurveyInstanceRestService { @Inject private SurveyInstanceDAO surveyInstanceDao; // list survey instances @RequestMapping(method = RequestMethod.GET, value = "") @ResponseBody public Map<String, Object> listSurveyInstances( @RequestParam(value = "beginDate", defaultValue = "") Long bDate, @RequestParam(value = "endDate", defaultValue = "") Long eDate, @RequestParam(value = "surveyId", defaultValue = "") Long surveyId, @RequestParam(value = "since", defaultValue = "") String since, @RequestParam(value = "unapprovedOnlyFlag",defaultValue = "") Boolean unapprovedOnlyFlag, @RequestParam(value = "deviceId", defaultValue = "") String deviceId, - @RequestParam(value = "submitterName", defaultValue = "") String submitterName, - @RequestParam(value = "surveyalTime", defaultValue = "0") Long surveyalTime) { + @RequestParam(value = "submitterName", defaultValue = "") String submitterName) { // we don't want to search for empty deviceId's and submitter names if ("".equals(deviceId)) { deviceId = null; } if ("".equals(submitterName)) { submitterName = null; } final Map<String, Object> response = new HashMap<String, Object>(); RestStatusDto statusDto = new RestStatusDto(); // create list of surveygroup / survey SurveyDAO surveyDao = new SurveyDAO(); List<Survey> surveyList = surveyDao.list("all"); HashMap<Long, String> surveyMap = new HashMap<Long, String>(); for (Survey s : surveyList) { surveyMap.put(s.getKey().getId(), s.getPath() + "/" + s.getCode()); } // turn params into dates Date beginDate = null; Date endDate = null; if (bDate != null) { beginDate = new Date(bDate); } if (eDate != null) { endDate = new Date(eDate); } // if no begin and end date, choose begin date 1-1-1970 if (beginDate == null && endDate == null) { //Calendar c = Calendar.getInstance(); //c.add(Calendar.YEAR, -90); beginDate = new Date (0); //c.getTime(); } // get survey Instances List<SurveyInstance> siList = null; SurveyInstanceDAO dao = new SurveyInstanceDAO(); siList = dao.listByDateRangeAndSubmitter(beginDate, endDate, false, surveyId, deviceId, submitterName, since); Integer num = siList.size(); String newSince = SurveyInstanceDAO.getCursor(siList); // put in survey group/survey names ArrayList<SurveyInstanceDto> siDtoList = new ArrayList<SurveyInstanceDto>(); for (SurveyInstance siItem : siList) { String code = surveyMap.get(siItem.getSurveyId()); SurveyInstanceDto dto = new SurveyInstanceDto(); DtoMarshaller.copyToDto(siItem, dto); if (code != null) dto.setSurveyCode(code); siDtoList.add(dto); } statusDto.setSince(newSince); statusDto.setNum(num); response.put("meta", statusDto); response.put("survey_instances", siDtoList); return response; } // find survey instance by id @RequestMapping(method = RequestMethod.GET, value = "/{id}") @ResponseBody public Map<String, SurveyInstanceDto> findSurveyInstanceById( @PathVariable("id") Long id) { final Map<String, SurveyInstanceDto> response = new HashMap<String, SurveyInstanceDto>(); SurveyInstance s = surveyInstanceDao.getByKey(id); SurveyInstanceDto dto = null; if (s != null) { dto = new SurveyInstanceDto(); DtoMarshaller.copyToDto(s, dto); } response.put("survey_instance", dto); return response; } // delete survey instance by id // TODO update counts @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") @ResponseBody public Map<String, RestStatusDto> deleteSurveyInstanceById( @PathVariable("id") Long id) { final Map<String, RestStatusDto> response = new HashMap<String, RestStatusDto>(); SurveyInstance s = surveyInstanceDao.getByKey(id); RestStatusDto statusDto = new RestStatusDto(); statusDto.setStatus("failed"); // check if surveyInstance exists in the datastore if (s != null) { surveyInstanceDao.deleteSurveyInstance(s); statusDto.setStatus("ok"); } response.put("meta", statusDto); List<Long> ids = new ArrayList<Long>(); ids.add(id); SurveyUtils.notifyReportService(ids, "invalidate"); return response; } // Update survey instance // TODO: question - when is this used? @RequestMapping(method = RequestMethod.PUT, value = "/{id}") @ResponseBody public Map<String, Object> saveExistingSurveyInstance( @RequestBody SurveyInstancePayload payLoad) { final SurveyInstanceDto surveyInstanceDto = payLoad.getSurvey_instance(); final Map<String, Object> response = new HashMap<String, Object>(); SurveyInstanceDto dto = null; RestStatusDto statusDto = new RestStatusDto(); statusDto.setStatus("failed"); // if the POST data contains a valid surveyInstanceDto, continue. // Otherwise, server 400 Bad Request if (surveyInstanceDto != null) { Long keyId = surveyInstanceDto.getKeyId(); SurveyInstance s; // if the surveyInstanceDto has a key, try to get the surveyInstance. if (keyId != null) { s = surveyInstanceDao.getByKey(keyId); // if we find the surveyInstance, update it's properties if (s != null) { // copy the properties, except the properties that are set // or provided by the Dao. BeanUtils.copyProperties(surveyInstanceDto, s, new String[] { "createdDateTime", "lastUpdateDateTime", "displayName", "questionInstanceList" }); s = surveyInstanceDao.save(s); dto = new SurveyInstanceDto(); DtoMarshaller.copyToDto(s, dto); statusDto.setStatus("ok"); } } } response.put("meta", statusDto); response.put("survey_instance", dto); return response; } // Create new survey instance @RequestMapping(method = RequestMethod.POST) @ResponseBody public Map<String, Object> saveNewSurveyInstance( @RequestBody SurveyInstancePayload payLoad) { final SurveyInstanceDto surveyInstanceDto = payLoad.getSurvey_instance(); final Map<String, Object> response = new HashMap<String, Object>(); SurveyInstanceDto dto = null; RestStatusDto statusDto = new RestStatusDto(); statusDto.setStatus("failed"); // if the POST data contains a valid surveyInstanceDto, continue. // Otherwise, server 400 Bad Request if (surveyInstanceDto != null) { SurveyInstance s = new SurveyInstance(); // copy the properties, except the properties that are set or // provided by the Dao. BeanUtils.copyProperties(surveyInstanceDto, s, new String[] { "createdDateTime", "lastUpdateDateTime", "displayName", "questionInstanceList" }); s = surveyInstanceDao.save(s); dto = new SurveyInstanceDto(); DtoMarshaller.copyToDto(s, dto); statusDto.setStatus("ok"); } response.put("meta", statusDto); response.put("survey_instance", dto); return response; } }
true
true
public Map<String, Object> listSurveyInstances( @RequestParam(value = "beginDate", defaultValue = "") Long bDate, @RequestParam(value = "endDate", defaultValue = "") Long eDate, @RequestParam(value = "surveyId", defaultValue = "") Long surveyId, @RequestParam(value = "since", defaultValue = "") String since, @RequestParam(value = "unapprovedOnlyFlag",defaultValue = "") Boolean unapprovedOnlyFlag, @RequestParam(value = "deviceId", defaultValue = "") String deviceId, @RequestParam(value = "submitterName", defaultValue = "") String submitterName, @RequestParam(value = "surveyalTime", defaultValue = "0") Long surveyalTime) { // we don't want to search for empty deviceId's and submitter names if ("".equals(deviceId)) { deviceId = null; } if ("".equals(submitterName)) { submitterName = null; } final Map<String, Object> response = new HashMap<String, Object>(); RestStatusDto statusDto = new RestStatusDto(); // create list of surveygroup / survey SurveyDAO surveyDao = new SurveyDAO(); List<Survey> surveyList = surveyDao.list("all"); HashMap<Long, String> surveyMap = new HashMap<Long, String>(); for (Survey s : surveyList) { surveyMap.put(s.getKey().getId(), s.getPath() + "/" + s.getCode()); } // turn params into dates Date beginDate = null; Date endDate = null; if (bDate != null) { beginDate = new Date(bDate); } if (eDate != null) { endDate = new Date(eDate); } // if no begin and end date, choose begin date 1-1-1970 if (beginDate == null && endDate == null) { //Calendar c = Calendar.getInstance(); //c.add(Calendar.YEAR, -90); beginDate = new Date (0); //c.getTime(); } // get survey Instances List<SurveyInstance> siList = null; SurveyInstanceDAO dao = new SurveyInstanceDAO(); siList = dao.listByDateRangeAndSubmitter(beginDate, endDate, false, surveyId, deviceId, submitterName, since); Integer num = siList.size(); String newSince = SurveyInstanceDAO.getCursor(siList); // put in survey group/survey names ArrayList<SurveyInstanceDto> siDtoList = new ArrayList<SurveyInstanceDto>(); for (SurveyInstance siItem : siList) { String code = surveyMap.get(siItem.getSurveyId()); SurveyInstanceDto dto = new SurveyInstanceDto(); DtoMarshaller.copyToDto(siItem, dto); if (code != null) dto.setSurveyCode(code); siDtoList.add(dto); } statusDto.setSince(newSince); statusDto.setNum(num); response.put("meta", statusDto); response.put("survey_instances", siDtoList); return response; }
public Map<String, Object> listSurveyInstances( @RequestParam(value = "beginDate", defaultValue = "") Long bDate, @RequestParam(value = "endDate", defaultValue = "") Long eDate, @RequestParam(value = "surveyId", defaultValue = "") Long surveyId, @RequestParam(value = "since", defaultValue = "") String since, @RequestParam(value = "unapprovedOnlyFlag",defaultValue = "") Boolean unapprovedOnlyFlag, @RequestParam(value = "deviceId", defaultValue = "") String deviceId, @RequestParam(value = "submitterName", defaultValue = "") String submitterName) { // we don't want to search for empty deviceId's and submitter names if ("".equals(deviceId)) { deviceId = null; } if ("".equals(submitterName)) { submitterName = null; } final Map<String, Object> response = new HashMap<String, Object>(); RestStatusDto statusDto = new RestStatusDto(); // create list of surveygroup / survey SurveyDAO surveyDao = new SurveyDAO(); List<Survey> surveyList = surveyDao.list("all"); HashMap<Long, String> surveyMap = new HashMap<Long, String>(); for (Survey s : surveyList) { surveyMap.put(s.getKey().getId(), s.getPath() + "/" + s.getCode()); } // turn params into dates Date beginDate = null; Date endDate = null; if (bDate != null) { beginDate = new Date(bDate); } if (eDate != null) { endDate = new Date(eDate); } // if no begin and end date, choose begin date 1-1-1970 if (beginDate == null && endDate == null) { //Calendar c = Calendar.getInstance(); //c.add(Calendar.YEAR, -90); beginDate = new Date (0); //c.getTime(); } // get survey Instances List<SurveyInstance> siList = null; SurveyInstanceDAO dao = new SurveyInstanceDAO(); siList = dao.listByDateRangeAndSubmitter(beginDate, endDate, false, surveyId, deviceId, submitterName, since); Integer num = siList.size(); String newSince = SurveyInstanceDAO.getCursor(siList); // put in survey group/survey names ArrayList<SurveyInstanceDto> siDtoList = new ArrayList<SurveyInstanceDto>(); for (SurveyInstance siItem : siList) { String code = surveyMap.get(siItem.getSurveyId()); SurveyInstanceDto dto = new SurveyInstanceDto(); DtoMarshaller.copyToDto(siItem, dto); if (code != null) dto.setSurveyCode(code); siDtoList.add(dto); } statusDto.setSince(newSince); statusDto.setNum(num); response.put("meta", statusDto); response.put("survey_instances", siDtoList); return response; }
diff --git a/src/main/java/org/guanxi/idp/service/saml2/WebBrowserSSOAuthHandler.java b/src/main/java/org/guanxi/idp/service/saml2/WebBrowserSSOAuthHandler.java index 3ec9ddb..d0c2107 100644 --- a/src/main/java/org/guanxi/idp/service/saml2/WebBrowserSSOAuthHandler.java +++ b/src/main/java/org/guanxi/idp/service/saml2/WebBrowserSSOAuthHandler.java @@ -1,229 +1,231 @@ //: "The contents of this file are subject to the Mozilla Public License //: Version 1.1 (the "License"); you may not use this file except in //: compliance with the License. You may obtain a copy of the License at //: http://www.mozilla.org/MPL/ //: //: Software distributed under the License is distributed on an "AS IS" //: basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the //: License for the specific language governing rights and limitations //: under the License. //: //: The Original Code is Guanxi (http://www.guanxi.uhi.ac.uk). //: //: The Initial Developer of the Original Code is Alistair Young [email protected] //: All Rights Reserved. //: package org.guanxi.idp.service.saml2; import org.apache.xmlbeans.XmlOptions; import org.guanxi.common.definitions.SAML; import org.guanxi.idp.service.GenericAuthHandler; import org.guanxi.common.Utils; import org.guanxi.common.metadata.SPMetadata; import org.guanxi.common.definitions.Guanxi; import org.guanxi.common.entity.EntityFarm; import org.guanxi.common.entity.EntityManager; import org.guanxi.common.trust.TrustUtils; import org.guanxi.xal.saml_2_0.protocol.AuthnRequestDocument; import org.guanxi.xal.saml_2_0.metadata.EntityDescriptorType; import org.guanxi.xal.saml_2_0.metadata.IndexedEndpointType; import org.apache.xmlbeans.XmlException; import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.StringReader; import java.io.StringWriter; import java.security.cert.X509Certificate; import java.util.HashMap; /** * Handles authenticating SAML2 Web Browser SSO connections * * @author alistair */ public class WebBrowserSSOAuthHandler extends GenericAuthHandler { /** Our logger */ private static final Logger logger = Logger.getLogger(WebBrowserSSOAuthHandler.class.getName()); /** The default binding to use for the Response if none is specified or there's no endpoint match */ private String defaultResponseBinding = null; /** * Takes care of authenticating the user and verifying the requesting entity. * As this handler can't display any errors it sets a request attribute: * wbsso-handler-error-message = error message text to display * if entity verification fails. The main handler can then display an message. * The handler can assume everything was ok if that attribute is not present. * * @param request Servlet request * @param response Servlet response * @param object the object! * @return true to continue with the request otherwise false * @throws Exception if an error occurs */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { String entityID = null; EntityManager manager = null; String requestBinding = null; AuthnRequestDocument requestDoc = null; // Sort out the incoming message encoding String encoding = null; // If requestBinding is there, we've already gone through the auth page via this handler if (request.getParameter("requestBinding") == null) { if (request.getMethod().equalsIgnoreCase("post")) { encoding = "post"; } else { encoding = "get"; } } else { if (request.getParameter("requestBinding").equals(SAML.SAML2_BINDING_HTTP_POST)) { encoding = "post"; } else if (request.getParameter("requestBinding").equals(SAML.SAML2_BINDING_HTTP_REDIRECT)) { encoding = "get"; } } try { if (encoding.equals("post")) { // HTTP-POST binding means a base64 encoded SAML Request requestDoc = AuthnRequestDocument.Factory.parse(new StringReader(Utils.decodeBase64(request.getParameter("SAMLRequest")))); requestBinding = SAML.SAML2_BINDING_HTTP_POST; } else { // HTTP-Redirect binding means a base64 encoded deflated SAML Request String decodedRequest = Utils.decodeBase64(request.getParameter("SAMLRequest")); requestDoc = AuthnRequestDocument.Factory.parse(Utils.inflate(decodedRequest, Utils.RFC1951_NO_WRAP)); requestBinding = SAML.SAML2_BINDING_HTTP_REDIRECT; } entityID = requestDoc.getAuthnRequest().getIssuer().getStringValue(); logger.info(requestBinding + " " + entityID); // Debug syphoning? if (idpConfig.getDebug() != null) { if (idpConfig.getDebug().getSypthonAttributeAssertions() != null) { HashMap<String, String> saml2Namespaces = new HashMap<String, String>(); saml2Namespaces.put(SAML.NS_SAML_20_PROTOCOL, SAML.NS_PREFIX_SAML_20_PROTOCOL); saml2Namespaces.put(SAML.NS_SAML_20_ASSERTION, SAML.NS_PREFIX_SAML_20_ASSERTION); XmlOptions xmlOptions = new XmlOptions(); xmlOptions.setSavePrettyPrint(); xmlOptions.setSavePrettyPrintIndent(2); xmlOptions.setUseDefaultNamespace(); xmlOptions.setSaveAggressiveNamespaces(); xmlOptions.setSaveNamespacesFirst(); if (idpConfig.getDebug().getSypthonAttributeAssertions().equals("yes")) { logger.info("======================================================="); logger.info("Request from " + entityID); logger.info(""); StringWriter sw = new StringWriter(); requestDoc.save(sw, xmlOptions); requestDoc.save(sw, xmlOptions); logger.info(sw.toString()); logger.info(""); logger.info("======================================================="); } } } // Pass the entityID to the service via the login page if required request.setAttribute("requestBinding", requestBinding); request.setAttribute("entityID", entityID); request.setAttribute("requestID", requestDoc.getAuthnRequest().getID()); - request.setAttribute("NameIDFormat", requestDoc.getAuthnRequest().getNameIDPolicy().getFormat()); + if (requestDoc.getAuthnRequest().getNameIDPolicy() != null) { + request.setAttribute("NameIDFormat", requestDoc.getAuthnRequest().getNameIDPolicy().getFormat()); + } EntityFarm farm = (EntityFarm)servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_ENTITY_FARM); manager = farm.getEntityManagerForID(entityID); // Verify the signature if there is one if (requestDoc.getAuthnRequest().getSignature() != null) { if (TrustUtils.verifySignature(requestDoc)) { X509Certificate[] x509FromSig = new X509Certificate[] {TrustUtils.getX509CertFromSignature(requestDoc.getAuthnRequest().getSignature().getKeyInfo())}; if (!manager.getTrustEngine().trustEntity(manager.getMetadata(entityID), x509FromSig)) { logger.error("failed to trust " + entityID); request.setAttribute("wbsso-handler-error-message", messageSource.getMessage("sp.failed.verification", new Object[] {entityID}, request.getLocale())); } } else { logger.error("failed to verify signature from " + entityID); request.setAttribute("wbsso-handler-error-message", messageSource.getMessage("sp.signature.verification.failed", null, request.getLocale())); } } } catch(XmlException xe) { logger.error("Error verifying entity " + entityID, xe); request.setAttribute("wbsso-handler-error-message", messageSource.getMessage("sp.failed.verification", new Object[] {entityID}, request.getLocale())); return true; } // Entity verification was successful. Now get its attribute consumer URL // First, try to get the URL and binding from the SAML Request... if ((requestDoc.getAuthnRequest().getAssertionConsumerServiceURL() != null) && (!requestDoc.getAuthnRequest().getAssertionConsumerServiceURL().equals("")) && (requestDoc.getAuthnRequest().getProtocolBinding() != null) && (!requestDoc.getAuthnRequest().getProtocolBinding().equals(""))) { request.setAttribute("acsURL", requestDoc.getAuthnRequest().getAssertionConsumerServiceURL()); request.setAttribute("responseBinding", requestDoc.getAuthnRequest().getProtocolBinding()); } else { // ...or if the information is missing, try to work it out from the metadata SPMetadata metadata = (SPMetadata)manager.getMetadata(entityID); String acsURL = null; EntityDescriptorType saml2Metadata = (EntityDescriptorType)metadata.getPrivateData(); IndexedEndpointType[] acss = saml2Metadata.getSPSSODescriptorArray(0).getAssertionConsumerServiceArray(); String defaultAcsURL = null; for (IndexedEndpointType acs : acss) { if (acs.getBinding().equalsIgnoreCase(requestBinding)) { acsURL = acs.getLocation(); } // Find the default binding endpoint in case we need it if (acs.getBinding().equalsIgnoreCase(defaultResponseBinding)) { defaultAcsURL = acs.getLocation(); } } // If there's no Response endpoint binding to match the binding used for the Request, use the default if (acsURL == null) { request.setAttribute("acsURL", defaultAcsURL); request.setAttribute("responseBinding", defaultResponseBinding); } else { request.setAttribute("acsURL", acsURL); request.setAttribute("responseBinding", requestBinding); } } // We don't support passive authentication if (requestDoc.getAuthnRequest().getIsPassive()) { request.setAttribute("wbsso-handler-error-message", SAML.SAML2_STATUS_NO_PASSIVE); } // Display the error without going through user authentication if (request.getAttribute("wbsso-handler-error-message") != null) { return true; } /* Redirects to the authentication page as required. This is to authenticate the user. * We'll end up back here after the user has logged in. */ return auth(entityID, request, response); } // Setters public void setDefaultResponseBinding(String defaultResponseBinding) { this.defaultResponseBinding = defaultResponseBinding; } }
true
true
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { String entityID = null; EntityManager manager = null; String requestBinding = null; AuthnRequestDocument requestDoc = null; // Sort out the incoming message encoding String encoding = null; // If requestBinding is there, we've already gone through the auth page via this handler if (request.getParameter("requestBinding") == null) { if (request.getMethod().equalsIgnoreCase("post")) { encoding = "post"; } else { encoding = "get"; } } else { if (request.getParameter("requestBinding").equals(SAML.SAML2_BINDING_HTTP_POST)) { encoding = "post"; } else if (request.getParameter("requestBinding").equals(SAML.SAML2_BINDING_HTTP_REDIRECT)) { encoding = "get"; } } try { if (encoding.equals("post")) { // HTTP-POST binding means a base64 encoded SAML Request requestDoc = AuthnRequestDocument.Factory.parse(new StringReader(Utils.decodeBase64(request.getParameter("SAMLRequest")))); requestBinding = SAML.SAML2_BINDING_HTTP_POST; } else { // HTTP-Redirect binding means a base64 encoded deflated SAML Request String decodedRequest = Utils.decodeBase64(request.getParameter("SAMLRequest")); requestDoc = AuthnRequestDocument.Factory.parse(Utils.inflate(decodedRequest, Utils.RFC1951_NO_WRAP)); requestBinding = SAML.SAML2_BINDING_HTTP_REDIRECT; } entityID = requestDoc.getAuthnRequest().getIssuer().getStringValue(); logger.info(requestBinding + " " + entityID); // Debug syphoning? if (idpConfig.getDebug() != null) { if (idpConfig.getDebug().getSypthonAttributeAssertions() != null) { HashMap<String, String> saml2Namespaces = new HashMap<String, String>(); saml2Namespaces.put(SAML.NS_SAML_20_PROTOCOL, SAML.NS_PREFIX_SAML_20_PROTOCOL); saml2Namespaces.put(SAML.NS_SAML_20_ASSERTION, SAML.NS_PREFIX_SAML_20_ASSERTION); XmlOptions xmlOptions = new XmlOptions(); xmlOptions.setSavePrettyPrint(); xmlOptions.setSavePrettyPrintIndent(2); xmlOptions.setUseDefaultNamespace(); xmlOptions.setSaveAggressiveNamespaces(); xmlOptions.setSaveNamespacesFirst(); if (idpConfig.getDebug().getSypthonAttributeAssertions().equals("yes")) { logger.info("======================================================="); logger.info("Request from " + entityID); logger.info(""); StringWriter sw = new StringWriter(); requestDoc.save(sw, xmlOptions); requestDoc.save(sw, xmlOptions); logger.info(sw.toString()); logger.info(""); logger.info("======================================================="); } } } // Pass the entityID to the service via the login page if required request.setAttribute("requestBinding", requestBinding); request.setAttribute("entityID", entityID); request.setAttribute("requestID", requestDoc.getAuthnRequest().getID()); request.setAttribute("NameIDFormat", requestDoc.getAuthnRequest().getNameIDPolicy().getFormat()); EntityFarm farm = (EntityFarm)servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_ENTITY_FARM); manager = farm.getEntityManagerForID(entityID); // Verify the signature if there is one if (requestDoc.getAuthnRequest().getSignature() != null) { if (TrustUtils.verifySignature(requestDoc)) { X509Certificate[] x509FromSig = new X509Certificate[] {TrustUtils.getX509CertFromSignature(requestDoc.getAuthnRequest().getSignature().getKeyInfo())}; if (!manager.getTrustEngine().trustEntity(manager.getMetadata(entityID), x509FromSig)) { logger.error("failed to trust " + entityID); request.setAttribute("wbsso-handler-error-message", messageSource.getMessage("sp.failed.verification", new Object[] {entityID}, request.getLocale())); } } else { logger.error("failed to verify signature from " + entityID); request.setAttribute("wbsso-handler-error-message", messageSource.getMessage("sp.signature.verification.failed", null, request.getLocale())); } } } catch(XmlException xe) { logger.error("Error verifying entity " + entityID, xe); request.setAttribute("wbsso-handler-error-message", messageSource.getMessage("sp.failed.verification", new Object[] {entityID}, request.getLocale())); return true; } // Entity verification was successful. Now get its attribute consumer URL // First, try to get the URL and binding from the SAML Request... if ((requestDoc.getAuthnRequest().getAssertionConsumerServiceURL() != null) && (!requestDoc.getAuthnRequest().getAssertionConsumerServiceURL().equals("")) && (requestDoc.getAuthnRequest().getProtocolBinding() != null) && (!requestDoc.getAuthnRequest().getProtocolBinding().equals(""))) { request.setAttribute("acsURL", requestDoc.getAuthnRequest().getAssertionConsumerServiceURL()); request.setAttribute("responseBinding", requestDoc.getAuthnRequest().getProtocolBinding()); } else { // ...or if the information is missing, try to work it out from the metadata SPMetadata metadata = (SPMetadata)manager.getMetadata(entityID); String acsURL = null; EntityDescriptorType saml2Metadata = (EntityDescriptorType)metadata.getPrivateData(); IndexedEndpointType[] acss = saml2Metadata.getSPSSODescriptorArray(0).getAssertionConsumerServiceArray(); String defaultAcsURL = null; for (IndexedEndpointType acs : acss) { if (acs.getBinding().equalsIgnoreCase(requestBinding)) { acsURL = acs.getLocation(); } // Find the default binding endpoint in case we need it if (acs.getBinding().equalsIgnoreCase(defaultResponseBinding)) { defaultAcsURL = acs.getLocation(); } } // If there's no Response endpoint binding to match the binding used for the Request, use the default if (acsURL == null) { request.setAttribute("acsURL", defaultAcsURL); request.setAttribute("responseBinding", defaultResponseBinding); } else { request.setAttribute("acsURL", acsURL); request.setAttribute("responseBinding", requestBinding); } } // We don't support passive authentication if (requestDoc.getAuthnRequest().getIsPassive()) { request.setAttribute("wbsso-handler-error-message", SAML.SAML2_STATUS_NO_PASSIVE); } // Display the error without going through user authentication if (request.getAttribute("wbsso-handler-error-message") != null) { return true; } /* Redirects to the authentication page as required. This is to authenticate the user. * We'll end up back here after the user has logged in. */ return auth(entityID, request, response); }
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { String entityID = null; EntityManager manager = null; String requestBinding = null; AuthnRequestDocument requestDoc = null; // Sort out the incoming message encoding String encoding = null; // If requestBinding is there, we've already gone through the auth page via this handler if (request.getParameter("requestBinding") == null) { if (request.getMethod().equalsIgnoreCase("post")) { encoding = "post"; } else { encoding = "get"; } } else { if (request.getParameter("requestBinding").equals(SAML.SAML2_BINDING_HTTP_POST)) { encoding = "post"; } else if (request.getParameter("requestBinding").equals(SAML.SAML2_BINDING_HTTP_REDIRECT)) { encoding = "get"; } } try { if (encoding.equals("post")) { // HTTP-POST binding means a base64 encoded SAML Request requestDoc = AuthnRequestDocument.Factory.parse(new StringReader(Utils.decodeBase64(request.getParameter("SAMLRequest")))); requestBinding = SAML.SAML2_BINDING_HTTP_POST; } else { // HTTP-Redirect binding means a base64 encoded deflated SAML Request String decodedRequest = Utils.decodeBase64(request.getParameter("SAMLRequest")); requestDoc = AuthnRequestDocument.Factory.parse(Utils.inflate(decodedRequest, Utils.RFC1951_NO_WRAP)); requestBinding = SAML.SAML2_BINDING_HTTP_REDIRECT; } entityID = requestDoc.getAuthnRequest().getIssuer().getStringValue(); logger.info(requestBinding + " " + entityID); // Debug syphoning? if (idpConfig.getDebug() != null) { if (idpConfig.getDebug().getSypthonAttributeAssertions() != null) { HashMap<String, String> saml2Namespaces = new HashMap<String, String>(); saml2Namespaces.put(SAML.NS_SAML_20_PROTOCOL, SAML.NS_PREFIX_SAML_20_PROTOCOL); saml2Namespaces.put(SAML.NS_SAML_20_ASSERTION, SAML.NS_PREFIX_SAML_20_ASSERTION); XmlOptions xmlOptions = new XmlOptions(); xmlOptions.setSavePrettyPrint(); xmlOptions.setSavePrettyPrintIndent(2); xmlOptions.setUseDefaultNamespace(); xmlOptions.setSaveAggressiveNamespaces(); xmlOptions.setSaveNamespacesFirst(); if (idpConfig.getDebug().getSypthonAttributeAssertions().equals("yes")) { logger.info("======================================================="); logger.info("Request from " + entityID); logger.info(""); StringWriter sw = new StringWriter(); requestDoc.save(sw, xmlOptions); requestDoc.save(sw, xmlOptions); logger.info(sw.toString()); logger.info(""); logger.info("======================================================="); } } } // Pass the entityID to the service via the login page if required request.setAttribute("requestBinding", requestBinding); request.setAttribute("entityID", entityID); request.setAttribute("requestID", requestDoc.getAuthnRequest().getID()); if (requestDoc.getAuthnRequest().getNameIDPolicy() != null) { request.setAttribute("NameIDFormat", requestDoc.getAuthnRequest().getNameIDPolicy().getFormat()); } EntityFarm farm = (EntityFarm)servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_ENTITY_FARM); manager = farm.getEntityManagerForID(entityID); // Verify the signature if there is one if (requestDoc.getAuthnRequest().getSignature() != null) { if (TrustUtils.verifySignature(requestDoc)) { X509Certificate[] x509FromSig = new X509Certificate[] {TrustUtils.getX509CertFromSignature(requestDoc.getAuthnRequest().getSignature().getKeyInfo())}; if (!manager.getTrustEngine().trustEntity(manager.getMetadata(entityID), x509FromSig)) { logger.error("failed to trust " + entityID); request.setAttribute("wbsso-handler-error-message", messageSource.getMessage("sp.failed.verification", new Object[] {entityID}, request.getLocale())); } } else { logger.error("failed to verify signature from " + entityID); request.setAttribute("wbsso-handler-error-message", messageSource.getMessage("sp.signature.verification.failed", null, request.getLocale())); } } } catch(XmlException xe) { logger.error("Error verifying entity " + entityID, xe); request.setAttribute("wbsso-handler-error-message", messageSource.getMessage("sp.failed.verification", new Object[] {entityID}, request.getLocale())); return true; } // Entity verification was successful. Now get its attribute consumer URL // First, try to get the URL and binding from the SAML Request... if ((requestDoc.getAuthnRequest().getAssertionConsumerServiceURL() != null) && (!requestDoc.getAuthnRequest().getAssertionConsumerServiceURL().equals("")) && (requestDoc.getAuthnRequest().getProtocolBinding() != null) && (!requestDoc.getAuthnRequest().getProtocolBinding().equals(""))) { request.setAttribute("acsURL", requestDoc.getAuthnRequest().getAssertionConsumerServiceURL()); request.setAttribute("responseBinding", requestDoc.getAuthnRequest().getProtocolBinding()); } else { // ...or if the information is missing, try to work it out from the metadata SPMetadata metadata = (SPMetadata)manager.getMetadata(entityID); String acsURL = null; EntityDescriptorType saml2Metadata = (EntityDescriptorType)metadata.getPrivateData(); IndexedEndpointType[] acss = saml2Metadata.getSPSSODescriptorArray(0).getAssertionConsumerServiceArray(); String defaultAcsURL = null; for (IndexedEndpointType acs : acss) { if (acs.getBinding().equalsIgnoreCase(requestBinding)) { acsURL = acs.getLocation(); } // Find the default binding endpoint in case we need it if (acs.getBinding().equalsIgnoreCase(defaultResponseBinding)) { defaultAcsURL = acs.getLocation(); } } // If there's no Response endpoint binding to match the binding used for the Request, use the default if (acsURL == null) { request.setAttribute("acsURL", defaultAcsURL); request.setAttribute("responseBinding", defaultResponseBinding); } else { request.setAttribute("acsURL", acsURL); request.setAttribute("responseBinding", requestBinding); } } // We don't support passive authentication if (requestDoc.getAuthnRequest().getIsPassive()) { request.setAttribute("wbsso-handler-error-message", SAML.SAML2_STATUS_NO_PASSIVE); } // Display the error without going through user authentication if (request.getAttribute("wbsso-handler-error-message") != null) { return true; } /* Redirects to the authentication page as required. This is to authenticate the user. * We'll end up back here after the user has logged in. */ return auth(entityID, request, response); }
diff --git a/src/com/manuelmaly/hn/parser/HNCommentsParser.java b/src/com/manuelmaly/hn/parser/HNCommentsParser.java index 61930ff..c5cb75f 100644 --- a/src/com/manuelmaly/hn/parser/HNCommentsParser.java +++ b/src/com/manuelmaly/hn/parser/HNCommentsParser.java @@ -1,107 +1,107 @@ package com.manuelmaly.hn.parser; import java.util.ArrayList; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.manuelmaly.hn.App; import com.manuelmaly.hn.Settings; import com.manuelmaly.hn.model.HNComment; import com.manuelmaly.hn.model.HNPostComments; import com.manuelmaly.hn.util.HNHelper; public class HNCommentsParser extends BaseHTMLParser<HNPostComments> { @Override public HNPostComments parseDocument(Element doc) throws Exception { if (doc == null) return new HNPostComments(); ArrayList<HNComment> comments = new ArrayList<HNComment>(); Elements tableRows = doc.select("table tr table tr:has(table)"); String currentUser = Settings.getUserName(App.getInstance()); String text = null; String author = null; int level = 0; String timeAgo = null; String url = null; Boolean isDownvoted = false; String upvoteUrl = null; String downvoteUrl = null; boolean endParsing = false; for (int row = 0; row < tableRows.size(); row++) { Element mainRowElement = tableRows.get(row).select("td:eq(2)").first(); Element rowLevelElement = tableRows.get(row).select("td:eq(0)").first(); if (mainRowElement == null) - break; + continue; // The not portion of this query is meant to remove the reply link // from the text. As far as I can tell that is the only place // where size=1 is used. If that turns out to not be the case then // searching for u tags is also a pretty decent option - @jmaltz text = mainRowElement.select("span.comment > *:not(:has(font[size=1]))").html(); Element comHeadElement = mainRowElement.select("span.comhead").first(); author = comHeadElement.select("a[href*=user]").text(); String timeAgoRaw = getFirstTextValueInElementChildren(comHeadElement); if (timeAgoRaw.length() > 0) timeAgo = timeAgoRaw.substring(0, timeAgoRaw.indexOf("|")); Element urlElement = comHeadElement.select("a[href*=item]").first(); if (urlElement != null) url = urlElement.attr("href"); String levelSpacerWidth = rowLevelElement.select("img").first().attr("width"); if (levelSpacerWidth != null) level = Integer.parseInt(levelSpacerWidth) / 40; Elements voteElements = tableRows.get(row).select("td:eq(1) a"); upvoteUrl = getVoteUrl(voteElements.first(), currentUser); // We want to test for size because unlike first() calling .get(1) // Will throw an error if there are not two elements if (voteElements.size() > 1) downvoteUrl = getVoteUrl(voteElements.get(1), currentUser); comments.add(new HNComment(timeAgo, author, url, text, level, isDownvoted, upvoteUrl, downvoteUrl)); if (endParsing) break; } // Just using table:eq(0) would return an extra table, so we use // get(0) instead, which only returns only the one we want Element header = doc.select("body table:eq(0) tbody > tr:eq(2) > td:eq(0) > table").get(0); String headerHtml = null; // Five table rows is what it takes for the title, post information // And other boilerplate stuff. More than five means we have something // Special if(header.select("tr").size() > 5) { HeaderParser headerParser = new HeaderParser(); headerHtml = headerParser.parseDocument(header); } return new HNPostComments(comments, headerHtml, currentUser); } /** * Parses out the url for voting from a given element * @param voteElement The element from which to parse out the voting url * @param currentUser The currently logged in user * @return The relative url to vote in the given direction for that comment */ private String getVoteUrl(Element voteElement, String currentUser) { if (voteElement != null) { return voteElement.attr("href").contains(currentUser) ? HNHelper.resolveRelativeHNURL(voteElement.attr("href")) : null; } return null; } }
true
true
public HNPostComments parseDocument(Element doc) throws Exception { if (doc == null) return new HNPostComments(); ArrayList<HNComment> comments = new ArrayList<HNComment>(); Elements tableRows = doc.select("table tr table tr:has(table)"); String currentUser = Settings.getUserName(App.getInstance()); String text = null; String author = null; int level = 0; String timeAgo = null; String url = null; Boolean isDownvoted = false; String upvoteUrl = null; String downvoteUrl = null; boolean endParsing = false; for (int row = 0; row < tableRows.size(); row++) { Element mainRowElement = tableRows.get(row).select("td:eq(2)").first(); Element rowLevelElement = tableRows.get(row).select("td:eq(0)").first(); if (mainRowElement == null) break; // The not portion of this query is meant to remove the reply link // from the text. As far as I can tell that is the only place // where size=1 is used. If that turns out to not be the case then // searching for u tags is also a pretty decent option - @jmaltz text = mainRowElement.select("span.comment > *:not(:has(font[size=1]))").html(); Element comHeadElement = mainRowElement.select("span.comhead").first(); author = comHeadElement.select("a[href*=user]").text(); String timeAgoRaw = getFirstTextValueInElementChildren(comHeadElement); if (timeAgoRaw.length() > 0) timeAgo = timeAgoRaw.substring(0, timeAgoRaw.indexOf("|")); Element urlElement = comHeadElement.select("a[href*=item]").first(); if (urlElement != null) url = urlElement.attr("href"); String levelSpacerWidth = rowLevelElement.select("img").first().attr("width"); if (levelSpacerWidth != null) level = Integer.parseInt(levelSpacerWidth) / 40; Elements voteElements = tableRows.get(row).select("td:eq(1) a"); upvoteUrl = getVoteUrl(voteElements.first(), currentUser); // We want to test for size because unlike first() calling .get(1) // Will throw an error if there are not two elements if (voteElements.size() > 1) downvoteUrl = getVoteUrl(voteElements.get(1), currentUser); comments.add(new HNComment(timeAgo, author, url, text, level, isDownvoted, upvoteUrl, downvoteUrl)); if (endParsing) break; } // Just using table:eq(0) would return an extra table, so we use // get(0) instead, which only returns only the one we want Element header = doc.select("body table:eq(0) tbody > tr:eq(2) > td:eq(0) > table").get(0); String headerHtml = null; // Five table rows is what it takes for the title, post information // And other boilerplate stuff. More than five means we have something // Special if(header.select("tr").size() > 5) { HeaderParser headerParser = new HeaderParser(); headerHtml = headerParser.parseDocument(header); } return new HNPostComments(comments, headerHtml, currentUser); }
public HNPostComments parseDocument(Element doc) throws Exception { if (doc == null) return new HNPostComments(); ArrayList<HNComment> comments = new ArrayList<HNComment>(); Elements tableRows = doc.select("table tr table tr:has(table)"); String currentUser = Settings.getUserName(App.getInstance()); String text = null; String author = null; int level = 0; String timeAgo = null; String url = null; Boolean isDownvoted = false; String upvoteUrl = null; String downvoteUrl = null; boolean endParsing = false; for (int row = 0; row < tableRows.size(); row++) { Element mainRowElement = tableRows.get(row).select("td:eq(2)").first(); Element rowLevelElement = tableRows.get(row).select("td:eq(0)").first(); if (mainRowElement == null) continue; // The not portion of this query is meant to remove the reply link // from the text. As far as I can tell that is the only place // where size=1 is used. If that turns out to not be the case then // searching for u tags is also a pretty decent option - @jmaltz text = mainRowElement.select("span.comment > *:not(:has(font[size=1]))").html(); Element comHeadElement = mainRowElement.select("span.comhead").first(); author = comHeadElement.select("a[href*=user]").text(); String timeAgoRaw = getFirstTextValueInElementChildren(comHeadElement); if (timeAgoRaw.length() > 0) timeAgo = timeAgoRaw.substring(0, timeAgoRaw.indexOf("|")); Element urlElement = comHeadElement.select("a[href*=item]").first(); if (urlElement != null) url = urlElement.attr("href"); String levelSpacerWidth = rowLevelElement.select("img").first().attr("width"); if (levelSpacerWidth != null) level = Integer.parseInt(levelSpacerWidth) / 40; Elements voteElements = tableRows.get(row).select("td:eq(1) a"); upvoteUrl = getVoteUrl(voteElements.first(), currentUser); // We want to test for size because unlike first() calling .get(1) // Will throw an error if there are not two elements if (voteElements.size() > 1) downvoteUrl = getVoteUrl(voteElements.get(1), currentUser); comments.add(new HNComment(timeAgo, author, url, text, level, isDownvoted, upvoteUrl, downvoteUrl)); if (endParsing) break; } // Just using table:eq(0) would return an extra table, so we use // get(0) instead, which only returns only the one we want Element header = doc.select("body table:eq(0) tbody > tr:eq(2) > td:eq(0) > table").get(0); String headerHtml = null; // Five table rows is what it takes for the title, post information // And other boilerplate stuff. More than five means we have something // Special if(header.select("tr").size() > 5) { HeaderParser headerParser = new HeaderParser(); headerHtml = headerParser.parseDocument(header); } return new HNPostComments(comments, headerHtml, currentUser); }
diff --git a/plugins/org.jboss.tools.deltacloud.core/src/org/jboss/tools/deltacloud/core/job/AbstractCloudJob.java b/plugins/org.jboss.tools.deltacloud.core/src/org/jboss/tools/deltacloud/core/job/AbstractCloudJob.java index a4c48b4b..b25af9e8 100644 --- a/plugins/org.jboss.tools.deltacloud.core/src/org/jboss/tools/deltacloud/core/job/AbstractCloudJob.java +++ b/plugins/org.jboss.tools.deltacloud.core/src/org/jboss/tools/deltacloud/core/job/AbstractCloudJob.java @@ -1,66 +1,66 @@ /******************************************************************************* * Copyright (c) 2010 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.deltacloud.core.job; import java.text.MessageFormat; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.core.runtime.jobs.Job; import org.jboss.tools.common.jobs.ChainedJob; import org.jboss.tools.common.log.StatusFactory; import org.jboss.tools.deltacloud.core.Activator; import org.jboss.tools.deltacloud.core.DeltaCloud; /** * @author André Dietisheim */ public abstract class AbstractCloudJob extends ChainedJob { private DeltaCloud cloud; public AbstractCloudJob(String name, DeltaCloud cloud) { this(name, cloud, null); } public AbstractCloudJob(String name, DeltaCloud cloud, String family) { super(name, family); this.cloud = cloud; } @Override protected IStatus run(IProgressMonitor monitor) { ISchedulingRule rule = getSchedulingRule(); Job.getJobManager().beginRule(rule, monitor); monitor.beginTask(getName(), IProgressMonitor.UNKNOWN); try { return doRun(monitor); } catch (Exception e) { // TODO: internationalize strings return StatusFactory.getInstance(IStatus.ERROR, Activator.PLUGIN_ID, - MessageFormat.format("Could not {0}", getName()), e); + MessageFormat.format("Could not perform \"{0}\"", getName()), e); } finally { monitor.done(); Job.getJobManager().endRule(rule); } } protected DeltaCloud getCloud() { return cloud; } protected abstract IStatus doRun(IProgressMonitor monitor) throws Exception; protected ISchedulingRule getSchedulingRule() { return new CloudSchedulingRule(cloud); } }
true
true
protected IStatus run(IProgressMonitor monitor) { ISchedulingRule rule = getSchedulingRule(); Job.getJobManager().beginRule(rule, monitor); monitor.beginTask(getName(), IProgressMonitor.UNKNOWN); try { return doRun(monitor); } catch (Exception e) { // TODO: internationalize strings return StatusFactory.getInstance(IStatus.ERROR, Activator.PLUGIN_ID, MessageFormat.format("Could not {0}", getName()), e); } finally { monitor.done(); Job.getJobManager().endRule(rule); } }
protected IStatus run(IProgressMonitor monitor) { ISchedulingRule rule = getSchedulingRule(); Job.getJobManager().beginRule(rule, monitor); monitor.beginTask(getName(), IProgressMonitor.UNKNOWN); try { return doRun(monitor); } catch (Exception e) { // TODO: internationalize strings return StatusFactory.getInstance(IStatus.ERROR, Activator.PLUGIN_ID, MessageFormat.format("Could not perform \"{0}\"", getName()), e); } finally { monitor.done(); Job.getJobManager().endRule(rule); } }
diff --git a/openerp-client/src/test/java/org/bahmni/openerp/web/OpenERPPropertiesStub.java b/openerp-client/src/test/java/org/bahmni/openerp/web/OpenERPPropertiesStub.java index a039de4..f4cdfcb 100644 --- a/openerp-client/src/test/java/org/bahmni/openerp/web/OpenERPPropertiesStub.java +++ b/openerp-client/src/test/java/org/bahmni/openerp/web/OpenERPPropertiesStub.java @@ -1,38 +1,38 @@ package org.bahmni.openerp.web; public class OpenERPPropertiesStub implements OpenERPProperties{ @Override public String getHost() { - return "192.168.33.10"; + return "localhost"; } @Override public int getPort() { return 8069; } @Override public String getDatabase() { return "openerp"; } @Override public String getUser() { return "admin"; } @Override public String getPassword() { return "password"; } @Override public int getConnectionTimeoutInMilliseconds() { return 0; } @Override public int getReplyTimeoutInMilliseconds() { return 0; } }
true
true
public String getHost() { return "192.168.33.10"; }
public String getHost() { return "localhost"; }
diff --git a/src/net/sourceforge/schemaspy/view/HtmlGraphFormatter.java b/src/net/sourceforge/schemaspy/view/HtmlGraphFormatter.java index 0fe7037..ab44b51 100755 --- a/src/net/sourceforge/schemaspy/view/HtmlGraphFormatter.java +++ b/src/net/sourceforge/schemaspy/view/HtmlGraphFormatter.java @@ -1,41 +1,41 @@ package net.sourceforge.schemaspy.view; import net.sourceforge.schemaspy.util.*; public class HtmlGraphFormatter extends HtmlFormatter { private static boolean printedNoDotWarning = false; private static boolean printedInvalidVersionWarning = false; protected HtmlGraphFormatter() { } protected Dot getDot() { Dot dot = Dot.getInstance(); if (!dot.exists()) { if (!printedNoDotWarning) { printedNoDotWarning = true; System.err.println(); System.err.println("Warning: Failed to run dot."); System.err.println(" Download " + dot.getSupportedVersions()); - System.err.println(" from www.graphviz.org and make sure dot is in your path."); + System.err.println(" from www.graphviz.org and make sure that dot is in your path."); System.err.println(" Generated pages will not contain a graphical view of table relationships."); } return null; } if (!dot.isValid()) { if (!printedInvalidVersionWarning) { printedInvalidVersionWarning = true; System.err.println(); - System.err.println("Warning: Invalid version of dot detected (" + dot.getVersion() + ")."); - System.err.println(" SchemaSpy requires " + dot.getSupportedVersions() + "."); + System.err.println("Warning: Invalid version of Graphviz dot detected (" + dot.getVersion() + ")."); + System.err.println(" SchemaSpy requires " + dot.getSupportedVersions() + ". from www.graphviz.org."); System.err.println(" Generated pages will not contain a graphical view of table relationships."); } return null; } return dot; } }
false
true
protected Dot getDot() { Dot dot = Dot.getInstance(); if (!dot.exists()) { if (!printedNoDotWarning) { printedNoDotWarning = true; System.err.println(); System.err.println("Warning: Failed to run dot."); System.err.println(" Download " + dot.getSupportedVersions()); System.err.println(" from www.graphviz.org and make sure dot is in your path."); System.err.println(" Generated pages will not contain a graphical view of table relationships."); } return null; } if (!dot.isValid()) { if (!printedInvalidVersionWarning) { printedInvalidVersionWarning = true; System.err.println(); System.err.println("Warning: Invalid version of dot detected (" + dot.getVersion() + ")."); System.err.println(" SchemaSpy requires " + dot.getSupportedVersions() + "."); System.err.println(" Generated pages will not contain a graphical view of table relationships."); } return null; } return dot; }
protected Dot getDot() { Dot dot = Dot.getInstance(); if (!dot.exists()) { if (!printedNoDotWarning) { printedNoDotWarning = true; System.err.println(); System.err.println("Warning: Failed to run dot."); System.err.println(" Download " + dot.getSupportedVersions()); System.err.println(" from www.graphviz.org and make sure that dot is in your path."); System.err.println(" Generated pages will not contain a graphical view of table relationships."); } return null; } if (!dot.isValid()) { if (!printedInvalidVersionWarning) { printedInvalidVersionWarning = true; System.err.println(); System.err.println("Warning: Invalid version of Graphviz dot detected (" + dot.getVersion() + ")."); System.err.println(" SchemaSpy requires " + dot.getSupportedVersions() + ". from www.graphviz.org."); System.err.println(" Generated pages will not contain a graphical view of table relationships."); } return null; } return dot; }
diff --git a/src/org/oneandone/qxwebdriver/By.java b/src/org/oneandone/qxwebdriver/By.java index 05ad2da..c93cbc3 100644 --- a/src/org/oneandone/qxwebdriver/By.java +++ b/src/org/oneandone/qxwebdriver/By.java @@ -1,107 +1,109 @@ package org.oneandone.qxwebdriver; import java.util.List; import org.oneandone.qxwebdriver.resources.javascript.JavaScript; import org.openqa.selenium.InvalidSelectorException; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.RemoteWebElement; public class By extends org.openqa.selenium.By { public WebElement findElement(SearchContext context) { return null; } public List<WebElement> findElements(SearchContext context) { return null; } public static By qxh(final String locator) { if (locator == null) { throw new IllegalArgumentException( "Can't find elements without a locator string."); } return new ByQxh(locator, true); } public static By qxh(final String locator, final Boolean onlyVisible) { if (locator == null) { throw new IllegalArgumentException( "Can't find elements without a locator string."); } return new ByQxh(locator, onlyVisible); } public static class ByQxh extends By { private final String locator; private Boolean onlyVisible; public ByQxh(String locator, Boolean onlyVisible) { this.locator = locator; this.onlyVisible = onlyVisible; } public List<WebElement> findElements(SearchContext context) { //TODO return null; } public WebElement findElement(SearchContext context) { JavascriptExecutor jsExecutor; RemoteWebElement contextElement = null; if (context instanceof RemoteWebElement) { contextElement = (RemoteWebElement) context; jsExecutor = (JavascriptExecutor) contextElement.getWrappedDriver(); } else { jsExecutor = (JavascriptExecutor) context; } String script = JavaScript.INSTANCE.getValue("qxh"); try { Object result; if (contextElement == null) { // OperaDriver.executeScript won't accept null as an argument result = jsExecutor.executeScript(script, locator, onlyVisible); } else { try { result = jsExecutor.executeScript(script, locator, onlyVisible, (WebElement) contextElement); } catch(com.opera.core.systems.scope.exceptions.ScopeException e) { // OperaDriver will sometimes throw a ScopeException if executeScript is called // with an OperaWebElement as argument return null; } } return (WebElement) result; } catch(org.openqa.selenium.WebDriverException e) { String msg = e.getMessage(); - if (msg.contains("Error resolving qxh path")) { + if (msg.contains("Error resolving qxh path") || + // IEDriver doesn't include the original JS exception's message :( + msg.contains("JavaScript error")) { return null; } else if (msg.contains("Illegal path step")) { String reason = "Invalid qxh selector " + locator.toString(); throw new InvalidSelectorException(reason, e); } else { String reason = "Error while processing selector " + locator.toString(); throw new org.openqa.selenium.WebDriverException(reason, e); } } } public String toString() { return "By.qxh: " + locator; } } }
true
true
public WebElement findElement(SearchContext context) { JavascriptExecutor jsExecutor; RemoteWebElement contextElement = null; if (context instanceof RemoteWebElement) { contextElement = (RemoteWebElement) context; jsExecutor = (JavascriptExecutor) contextElement.getWrappedDriver(); } else { jsExecutor = (JavascriptExecutor) context; } String script = JavaScript.INSTANCE.getValue("qxh"); try { Object result; if (contextElement == null) { // OperaDriver.executeScript won't accept null as an argument result = jsExecutor.executeScript(script, locator, onlyVisible); } else { try { result = jsExecutor.executeScript(script, locator, onlyVisible, (WebElement) contextElement); } catch(com.opera.core.systems.scope.exceptions.ScopeException e) { // OperaDriver will sometimes throw a ScopeException if executeScript is called // with an OperaWebElement as argument return null; } } return (WebElement) result; } catch(org.openqa.selenium.WebDriverException e) { String msg = e.getMessage(); if (msg.contains("Error resolving qxh path")) { return null; } else if (msg.contains("Illegal path step")) { String reason = "Invalid qxh selector " + locator.toString(); throw new InvalidSelectorException(reason, e); } else { String reason = "Error while processing selector " + locator.toString(); throw new org.openqa.selenium.WebDriverException(reason, e); } } }
public WebElement findElement(SearchContext context) { JavascriptExecutor jsExecutor; RemoteWebElement contextElement = null; if (context instanceof RemoteWebElement) { contextElement = (RemoteWebElement) context; jsExecutor = (JavascriptExecutor) contextElement.getWrappedDriver(); } else { jsExecutor = (JavascriptExecutor) context; } String script = JavaScript.INSTANCE.getValue("qxh"); try { Object result; if (contextElement == null) { // OperaDriver.executeScript won't accept null as an argument result = jsExecutor.executeScript(script, locator, onlyVisible); } else { try { result = jsExecutor.executeScript(script, locator, onlyVisible, (WebElement) contextElement); } catch(com.opera.core.systems.scope.exceptions.ScopeException e) { // OperaDriver will sometimes throw a ScopeException if executeScript is called // with an OperaWebElement as argument return null; } } return (WebElement) result; } catch(org.openqa.selenium.WebDriverException e) { String msg = e.getMessage(); if (msg.contains("Error resolving qxh path") || // IEDriver doesn't include the original JS exception's message :( msg.contains("JavaScript error")) { return null; } else if (msg.contains("Illegal path step")) { String reason = "Invalid qxh selector " + locator.toString(); throw new InvalidSelectorException(reason, e); } else { String reason = "Error while processing selector " + locator.toString(); throw new org.openqa.selenium.WebDriverException(reason, e); } } }
diff --git a/src/main/java/edu/mit/cci/turksnet/plugins/LoomPlugin.java b/src/main/java/edu/mit/cci/turksnet/plugins/LoomPlugin.java index a40ef9a..1f691f4 100644 --- a/src/main/java/edu/mit/cci/turksnet/plugins/LoomPlugin.java +++ b/src/main/java/edu/mit/cci/turksnet/plugins/LoomPlugin.java @@ -1,321 +1,321 @@ package edu.mit.cci.turksnet.plugins; import edu.mit.cci.snatools.util.jung.DefaultJungEdge; import edu.mit.cci.snatools.util.jung.DefaultJungGraph; import edu.mit.cci.snatools.util.jung.DefaultJungNode; import edu.mit.cci.turksnet.Experiment; import edu.mit.cci.turksnet.Node; import edu.mit.cci.turksnet.SessionLog; import edu.mit.cci.turksnet.Session_; import edu.mit.cci.turksnet.web.NodeForm; import edu.uci.ics.jung.algorithms.generators.Lattice2DGenerator; import edu.uci.ics.jung.graph.util.Pair; import org.apache.log4j.Logger; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * User: jintrone * Date: 4/28/11 * Time: 7:45 AM */ //an experiment maintains settings //a session is run within an expriment. it is a case. public class LoomPlugin implements Plugin { public static final String PROP_STORY = "story"; private static final String PROP_NODE_COUNT = "node_count"; private static final String PROP_GRAPH_TYPE = "graph_type"; private static final String PROP_PRIVATE_TILES = "private_tile_count"; private static final String PROP_ITERATION_COUNT = "iteration_count"; private static final String PROP_SESSION_BONUS_VALUE = "sessionBonusValue"; private static final String PROP_SESSION_BONUS_COUNT = "sessionBonusCount"; private static final String PROP_SESSION_BONUS_CORRECT = "sessionBonusCorrect"; private static Logger log = Logger.getLogger(LoomPlugin.class); public Session_ createSession(Experiment experiment) throws SessionCreationException { Map<String, String> props = experiment.getPropsAsMap(); Session_ session = new Session_(experiment.getId()); session.setCreated(new Date()); session.persist(); try { createGraph(props, session); } catch (Exception e) { throw new SessionCreationException("Error generating graph"); } initNodes(session.getAvailableNodes(), props); session.merge(); return session; } @Override public boolean checkDone(Session_ s) { for (Node n : s.getAvailableNodes()) { if (n.isAcceptingInput()) { return false; } } return (s.getIteration() >= Integer.parseInt(s.getExperiment().getPropsAsMap().get(PROP_ITERATION_COUNT))); } @Override public void processResults(Node n, Map<String,String> results) { n.setPublicData_(results.get("publicData")); n.setPrivateData_(results.get("privateData")); n.persist(); } private static int getNewId(Set<Integer> set) { Random rnd = new Random(); int n; do { n = rnd.nextInt(1000); } while (set.contains(n)); set.add(n); return n; } @Override public void preprocessProperties(Experiment experiment) throws ExperimentCreationException { StringBuilder builder = new StringBuilder(); Map<String, String> props = experiment.getPropsAsMap(); String story = props.get(PROP_STORY); Pattern pat = Pattern.compile("(\\d+):(\\w+)"); if (story == null) throw new ExperimentCreationException("No story associated with Loom Experiment"); String sep = ""; Set<Integer> ids = new HashSet<Integer>(); for (String p : story.split(";")) { p = p.trim(); builder.append(sep); Matcher m = pat.matcher(p); if (m.matches()) { if (!ids.contains(m.group(1))) { ids.add(Integer.getInteger(m.group(1))); builder.append(p); } else { int nid = getNewId(ids); builder.append(nid).append(":").append(m.group(2)); } } else { int nid = getNewId(ids); builder.append(nid).append(":").append(p); } sep = ";"; } experiment.updateProperty(PROP_STORY, builder.toString()); } private void createGraph(Map<String, String> props, Session_ session) throws GraphCreationException { String graphtype = props.get(PROP_GRAPH_TYPE); Integer nodecount = Integer.parseInt(props.get(PROP_NODE_COUNT)); DefaultJungGraph graph = null; if (nodecount == 1) { graph = new DefaultJungGraph(); DefaultJungNode node = DefaultJungNode.getFactory().create(); graph.addVertex(node); } else if ("lattice".equals(graphtype)) { if (Math.floor(Math.sqrt(nodecount.doubleValue())) < Math.sqrt(nodecount.doubleValue())) { log.warn("Requested number of nodes must be a perfect square for lattice networks"); } Lattice2DGenerator<DefaultJungNode, DefaultJungEdge> generator = new Lattice2DGenerator<DefaultJungNode, DefaultJungEdge>( DefaultJungGraph.getFactory(), DefaultJungNode.getFactory(), DefaultJungEdge.getFactory(), (int) Math.sqrt(nodecount.doubleValue()), true); graph = (DefaultJungGraph) generator.create(); } else { throw new GraphCreationException("Graph type not supported"); } Map<DefaultJungNode, Node> nodes = new HashMap<DefaultJungNode, Node>(); for (DefaultJungNode vertex : graph.getVertices()) { Node node = new Node(); node.setSession_(session); session.addNode(node); nodes.put(vertex, node); } for (DefaultJungEdge edge : graph.getEdges()) { Pair<DefaultJungNode> eps = graph.getEndpoints(edge); nodes.get(eps.getSecond()).getIncoming().add(nodes.get(eps.getFirst())); } } private void initNodes(Collection<Node> nodes, Map<String, String> props) { int numtiles = Integer.valueOf(props.get(PROP_PRIVATE_TILES)); String[] story = props.get(PROP_STORY).split(";"); List<Node> rndnodes = new ArrayList<Node>(nodes); List<String> rndstory = new ArrayList<String>(Arrays.asList(story)); Collections.shuffle(rndnodes); int i = 0; for (Node n : rndnodes) { for (int elt = 0; elt < numtiles; elt++) { i = (i + elt) % story.length; if (i == 0) { Collections.shuffle(rndstory); } n.setPrivateData_((n.getPrivateData_() == null ? "" : n.getPrivateData_() + ";") + rndstory.get(i)); } n.persist(); } } @Override public String getHitCreation(Session_ session, String rooturl) { Map<String, String> result = new HashMap<String, String>(); result.put("title", "Figure out the story"); result.put("desc", "Combine your story pieces with your neighbors to create the best story you can"); result.put("url", rooturl + "/session_s/" + session.getId() + "/turk/app"); result.put("reward", ".03"); result.put("assignments", session.getExperiment().getPropsAsMap().get(PROP_NODE_COUNT)); result.put("height", "800"); if (session.getQualificationRequirements()!=null ) { result.put("qualificationRequirements", createQualificationString(session.getQualificationRequirements())); } return "("+jsonify(result)+")"; } private static String createQualificationString(String qual) { Map<String,String> map = new HashMap<String, String>(); map.put("QualificationTypeId",qual); map.put("Comparator","Exists"); return jsonify(map); } private static String jsonify(Map<String, String> vals) { StringBuilder buffer = new StringBuilder(); String sep = ""; buffer.append("{"); for (Map.Entry<String, String> ent : vals.entrySet()) { buffer.append(sep).append(ent.getKey()).append(":"); if (ent.getValue().startsWith("{") && ent.getValue().endsWith("}")) { buffer.append(ent.getValue()); } else if (!ent.getValue().matches("[\\d\\.]+")) { buffer.append('"').append(ent.getValue()).append('"'); } else { buffer.append(ent.getValue()); } sep = ","; } buffer.append("}"); return buffer.toString(); } public static List<Float> getSessionScores(Experiment experiment, List<SessionLog> logs) { List<Float> result = new ArrayList<Float>(); List<Integer> truth = getStoryOrder(experiment.getPropsAsMap().get(PROP_STORY)); for (SessionLog log:logs) { result.add(score(truth,getStoryOrder(log.getNodePublicData()))); } return result; } public Map<String,String> getBonus(Node n) { List<SessionLog> logs = new ArrayList<SessionLog>(); for (SessionLog log :SessionLog.findAllSessionLogs()) { if (n.equals(log.getNode()) && log.getType().equals("results")) { logs.add(log); } } Experiment e = n.getSession_().getExperiment(); List<Float> scores = getSessionScores(n.getSession_().getExperiment(),logs); String description = "No score could be obtained"; String bonus = "0.0f"; if (scores.isEmpty()) { return Collections.emptyMap(); } Float lastscore = scores.get(scores.size()-1); Collections.sort(scores,new Comparator<Float>() { @Override public int compare(Float aFloat, Float aFloat1) { return -1 * (aFloat.compareTo(aFloat1)); } }); - scores.subList(0,Integer.parseInt(e.getPropsAsMap().get(PROP_SESSION_BONUS_COUNT))); + scores.subList(0,Math.min(scores.size(),Integer.parseInt(e.getPropsAsMap().get(PROP_SESSION_BONUS_COUNT)))); StringBuilder builder = new StringBuilder(); - builder.append("Your ten best session scores were: "); + builder.append("Your best session scores were: "); float total = 0; for (Float f:scores) { builder.append(String.format("%.2f",f)).append(" "); total+=f*Float.parseFloat(e.getPropsAsMap().get(PROP_SESSION_BONUS_VALUE)); } builder.append("\n").append("Your final session score was: ").append(String.format("%.2f",lastscore)); if (lastscore == 1.0f) { total +=Float.parseFloat(e.getPropsAsMap().get(PROP_SESSION_BONUS_CORRECT)); } Map<String,String> result = new HashMap<String,String>(); result.put("Description",builder.toString()); result.put("Bonus",String.format("%.2f",total)); return result; } private static List<Integer> getStoryOrder(String story) { List<Integer> result = new ArrayList<Integer>(); Pattern pat = Pattern.compile("(\\d+):\\w+"); if (story!=null) { for (String p : story.split(";")) { p = p.trim(); Matcher m = pat.matcher(p); if (m.matches()) { result.add(Integer.parseInt(m.group(1))); } } } return result; } public static Float score(List<Integer> truth, List<Integer> sample) { Map<Integer,Integer> tmap = new HashMap<Integer,Integer>(); int i = 0; for (Integer t:truth) { tmap.put(t,i++); } tmap.keySet().retainAll(sample); int last = -1; int accountedFor = 0; for (Integer s:sample) { if (last > -1) { if (tmap.get(last) > tmap.get(s)) { accountedFor++; } } last= s; } return accountedFor / (float)(truth.size()-1); } }
false
true
public Map<String,String> getBonus(Node n) { List<SessionLog> logs = new ArrayList<SessionLog>(); for (SessionLog log :SessionLog.findAllSessionLogs()) { if (n.equals(log.getNode()) && log.getType().equals("results")) { logs.add(log); } } Experiment e = n.getSession_().getExperiment(); List<Float> scores = getSessionScores(n.getSession_().getExperiment(),logs); String description = "No score could be obtained"; String bonus = "0.0f"; if (scores.isEmpty()) { return Collections.emptyMap(); } Float lastscore = scores.get(scores.size()-1); Collections.sort(scores,new Comparator<Float>() { @Override public int compare(Float aFloat, Float aFloat1) { return -1 * (aFloat.compareTo(aFloat1)); } }); scores.subList(0,Integer.parseInt(e.getPropsAsMap().get(PROP_SESSION_BONUS_COUNT))); StringBuilder builder = new StringBuilder(); builder.append("Your ten best session scores were: "); float total = 0; for (Float f:scores) { builder.append(String.format("%.2f",f)).append(" "); total+=f*Float.parseFloat(e.getPropsAsMap().get(PROP_SESSION_BONUS_VALUE)); } builder.append("\n").append("Your final session score was: ").append(String.format("%.2f",lastscore)); if (lastscore == 1.0f) { total +=Float.parseFloat(e.getPropsAsMap().get(PROP_SESSION_BONUS_CORRECT)); } Map<String,String> result = new HashMap<String,String>(); result.put("Description",builder.toString()); result.put("Bonus",String.format("%.2f",total)); return result; }
public Map<String,String> getBonus(Node n) { List<SessionLog> logs = new ArrayList<SessionLog>(); for (SessionLog log :SessionLog.findAllSessionLogs()) { if (n.equals(log.getNode()) && log.getType().equals("results")) { logs.add(log); } } Experiment e = n.getSession_().getExperiment(); List<Float> scores = getSessionScores(n.getSession_().getExperiment(),logs); String description = "No score could be obtained"; String bonus = "0.0f"; if (scores.isEmpty()) { return Collections.emptyMap(); } Float lastscore = scores.get(scores.size()-1); Collections.sort(scores,new Comparator<Float>() { @Override public int compare(Float aFloat, Float aFloat1) { return -1 * (aFloat.compareTo(aFloat1)); } }); scores.subList(0,Math.min(scores.size(),Integer.parseInt(e.getPropsAsMap().get(PROP_SESSION_BONUS_COUNT)))); StringBuilder builder = new StringBuilder(); builder.append("Your best session scores were: "); float total = 0; for (Float f:scores) { builder.append(String.format("%.2f",f)).append(" "); total+=f*Float.parseFloat(e.getPropsAsMap().get(PROP_SESSION_BONUS_VALUE)); } builder.append("\n").append("Your final session score was: ").append(String.format("%.2f",lastscore)); if (lastscore == 1.0f) { total +=Float.parseFloat(e.getPropsAsMap().get(PROP_SESSION_BONUS_CORRECT)); } Map<String,String> result = new HashMap<String,String>(); result.put("Description",builder.toString()); result.put("Bonus",String.format("%.2f",total)); return result; }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java index 767abf76..efb45f82 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java @@ -1,244 +1,238 @@ /* * Copyright (C) 2012 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.systemui.statusbar.phone; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.UserHandle; import android.provider.Settings; import android.util.AttributeSet; import android.util.EventLog; import android.util.Slog; import android.view.MotionEvent; import android.view.View; import android.view.accessibility.AccessibilityEvent; import com.android.systemui.EventLogTags; import com.android.systemui.R; import com.android.systemui.statusbar.GestureRecorder; public class NotificationPanelView extends PanelView { public static final boolean DEBUG_GESTURES = true; private static final float STATUS_BAR_SETTINGS_LEFT_PERCENTAGE = 0.8f; private static final float STATUS_BAR_SETTINGS_RIGHT_PERCENTAGE = 0.2f; private static final float STATUS_BAR_SWIPE_TRIGGER_PERCENTAGE = 0.05f; private static final float STATUS_BAR_SWIPE_VERTICAL_MAX_PERCENTAGE = 0.025f; private static final float STATUS_BAR_SWIPE_MOVE_PERCENTAGE = 0.2f; private Drawable mHandleBar; private int mHandleBarHeight; private View mHandleView; private int mFingers; private PhoneStatusBar mStatusBar; private boolean mOkToFlip; private float mGestureStartX; private float mGestureStartY; private float mFlipOffset; private float mSwipeDirection; private boolean mTrackingSwipe; private boolean mSwipeTriggered; public NotificationPanelView(Context context, AttributeSet attrs) { super(context, attrs); } public void setStatusBar(PhoneStatusBar bar) { mStatusBar = bar; } @Override protected void onFinishInflate() { super.onFinishInflate(); Resources resources = getContext().getResources(); mHandleBar = resources.getDrawable(R.drawable.status_bar_close); mHandleBarHeight = resources.getDimensionPixelSize(R.dimen.close_handle_height); mHandleView = findViewById(R.id.handle); } @Override public void fling(float vel, boolean always) { GestureRecorder gr = ((PhoneStatusBarView) mBar).mBar.getGestureRecorder(); if (gr != null) { gr.tag( "fling " + ((vel > 0) ? "open" : "closed"), "notifications,v=" + vel); } super.fling(vel, always); } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { event.getText() .add(getContext().getString(R.string.accessibility_desc_notification_shade)); return true; } return super.dispatchPopulateAccessibilityEvent(event); } // We draw the handle ourselves so that it's always glued to the bottom of the window. @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (changed) { final int pl = getPaddingLeft(); final int pr = getPaddingRight(); mHandleBar.setBounds(pl, 0, getWidth() - pr, (int) mHandleBarHeight); } } @Override public void draw(Canvas canvas) { super.draw(canvas); final int off = (int) (getHeight() - mHandleBarHeight - getPaddingBottom()); canvas.translate(0, off); mHandleBar.setState(mHandleView.getDrawableState()); mHandleBar.draw(canvas); canvas.translate(0, -off); } @Override public boolean onTouchEvent(MotionEvent event) { boolean shouldRecycleEvent = false; - if (DEBUG_GESTURES) { - if (event.getActionMasked() != MotionEvent.ACTION_MOVE) { - EventLog.writeEvent(EventLogTags.SYSUI_NOTIFICATIONPANEL_TOUCH, - event.getActionMasked(), (int) event.getX(), (int) event.getY()); - } - } if (PhoneStatusBar.SETTINGS_DRAG_SHORTCUT && mStatusBar.mHasFlipSettings) { boolean flip = false; boolean swipeFlipJustFinished = false; boolean swipeFlipJustStarted = false; switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: mGestureStartX = event.getX(0); mGestureStartY = event.getY(0); mTrackingSwipe = isFullyExpanded() && // Pointer is at the handle portion of the view? mGestureStartY > getHeight() - mHandleBarHeight - getPaddingBottom(); mOkToFlip = getExpandedHeight() == 0; if (event.getX(0) > getWidth() * (1.0f - STATUS_BAR_SETTINGS_RIGHT_PERCENTAGE) && Settings.System.getIntForUser(getContext().getContentResolver(), Settings.System.QS_QUICK_PULLDOWN, 0, UserHandle.USER_CURRENT) == 1) { flip = true; } else if (event.getX(0) < getWidth() * (1.0f - STATUS_BAR_SETTINGS_LEFT_PERCENTAGE) && Settings.System.getIntForUser(getContext().getContentResolver(), Settings.System.QS_QUICK_PULLDOWN, 0, UserHandle.USER_CURRENT) == 2) { flip = true; } break; case MotionEvent.ACTION_MOVE: final float deltaX = Math.abs(event.getX(0) - mGestureStartX); final float deltaY = Math.abs(event.getY(0) - mGestureStartY); final float maxDeltaY = getHeight() * STATUS_BAR_SWIPE_VERTICAL_MAX_PERCENTAGE; final float minDeltaX = getWidth() * STATUS_BAR_SWIPE_TRIGGER_PERCENTAGE; if (mTrackingSwipe && deltaY > maxDeltaY) { mTrackingSwipe = false; } if (mTrackingSwipe && deltaX > deltaY && deltaX > minDeltaX) { // The value below can be used to adjust deltaX to always increase, // if the user keeps swiping in the same direction as she started the // gesture. If she, however, moves her finger the other way, deltaX will // decrease. // // This allows for an horizontal swipe, in any direction, to always flip // the views. mSwipeDirection = event.getX(0) < mGestureStartX ? -1f : 1f; if (mStatusBar.isShowingSettings()) { mFlipOffset = 1f; // in this case, however, we need deltaX to decrease mSwipeDirection = -mSwipeDirection; } else { mFlipOffset = -1f; } mGestureStartX = event.getX(0); mTrackingSwipe = false; mSwipeTriggered = true; swipeFlipJustStarted = true; } break; case MotionEvent.ACTION_POINTER_DOWN: flip = true; break; case MotionEvent.ACTION_UP: swipeFlipJustFinished = mSwipeTriggered; mSwipeTriggered = false; mTrackingSwipe = false; break; } if (mOkToFlip && flip) { float miny = event.getY(0); float maxy = miny; for (int i=1; i<event.getPointerCount(); i++) { final float y = event.getY(i); if (y < miny) miny = y; if (y > maxy) maxy = y; } if (maxy - miny < mHandleBarHeight) { if (mJustPeeked || getExpandedHeight() < mHandleBarHeight) { mStatusBar.switchToSettings(); } else { mStatusBar.flipToSettings(); } mOkToFlip = false; } } else if (mSwipeTriggered) { final float deltaX = (event.getX(0) - mGestureStartX) * mSwipeDirection; mStatusBar.partialFlip(mFlipOffset + deltaX / (getWidth() * STATUS_BAR_SWIPE_MOVE_PERCENTAGE)); if (!swipeFlipJustStarted) { return true; // Consume the event. } } else if (swipeFlipJustFinished) { mStatusBar.completePartialFlip(); } if (swipeFlipJustStarted || swipeFlipJustFinished) { // Made up event: finger at the middle bottom of the view. MotionEvent original = event; event = MotionEvent.obtain(original.getDownTime(), original.getEventTime(), original.getAction(), getWidth()/2, getHeight(), original.getPressure(0), original.getSize(0), original.getMetaState(), original.getXPrecision(), original.getYPrecision(), original.getDeviceId(), original.getEdgeFlags()); // The following two lines looks better than the chunk of code above, but, // nevertheless, doesn't work. The view is not pinned down, and may close, // just after the gesture is finished. // // event = MotionEvent.obtainNoHistory(original); // event.setLocation(getWidth()/2, getHeight()); shouldRecycleEvent = true; } } final boolean result = mHandleView.dispatchTouchEvent(event); if (shouldRecycleEvent) { event.recycle(); } return result; } }
true
true
public boolean onTouchEvent(MotionEvent event) { boolean shouldRecycleEvent = false; if (DEBUG_GESTURES) { if (event.getActionMasked() != MotionEvent.ACTION_MOVE) { EventLog.writeEvent(EventLogTags.SYSUI_NOTIFICATIONPANEL_TOUCH, event.getActionMasked(), (int) event.getX(), (int) event.getY()); } } if (PhoneStatusBar.SETTINGS_DRAG_SHORTCUT && mStatusBar.mHasFlipSettings) { boolean flip = false; boolean swipeFlipJustFinished = false; boolean swipeFlipJustStarted = false; switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: mGestureStartX = event.getX(0); mGestureStartY = event.getY(0); mTrackingSwipe = isFullyExpanded() && // Pointer is at the handle portion of the view? mGestureStartY > getHeight() - mHandleBarHeight - getPaddingBottom(); mOkToFlip = getExpandedHeight() == 0; if (event.getX(0) > getWidth() * (1.0f - STATUS_BAR_SETTINGS_RIGHT_PERCENTAGE) && Settings.System.getIntForUser(getContext().getContentResolver(), Settings.System.QS_QUICK_PULLDOWN, 0, UserHandle.USER_CURRENT) == 1) { flip = true; } else if (event.getX(0) < getWidth() * (1.0f - STATUS_BAR_SETTINGS_LEFT_PERCENTAGE) && Settings.System.getIntForUser(getContext().getContentResolver(), Settings.System.QS_QUICK_PULLDOWN, 0, UserHandle.USER_CURRENT) == 2) { flip = true; } break; case MotionEvent.ACTION_MOVE: final float deltaX = Math.abs(event.getX(0) - mGestureStartX); final float deltaY = Math.abs(event.getY(0) - mGestureStartY); final float maxDeltaY = getHeight() * STATUS_BAR_SWIPE_VERTICAL_MAX_PERCENTAGE; final float minDeltaX = getWidth() * STATUS_BAR_SWIPE_TRIGGER_PERCENTAGE; if (mTrackingSwipe && deltaY > maxDeltaY) { mTrackingSwipe = false; } if (mTrackingSwipe && deltaX > deltaY && deltaX > minDeltaX) { // The value below can be used to adjust deltaX to always increase, // if the user keeps swiping in the same direction as she started the // gesture. If she, however, moves her finger the other way, deltaX will // decrease. // // This allows for an horizontal swipe, in any direction, to always flip // the views. mSwipeDirection = event.getX(0) < mGestureStartX ? -1f : 1f; if (mStatusBar.isShowingSettings()) { mFlipOffset = 1f; // in this case, however, we need deltaX to decrease mSwipeDirection = -mSwipeDirection; } else { mFlipOffset = -1f; } mGestureStartX = event.getX(0); mTrackingSwipe = false; mSwipeTriggered = true; swipeFlipJustStarted = true; } break; case MotionEvent.ACTION_POINTER_DOWN: flip = true; break; case MotionEvent.ACTION_UP: swipeFlipJustFinished = mSwipeTriggered; mSwipeTriggered = false; mTrackingSwipe = false; break; } if (mOkToFlip && flip) { float miny = event.getY(0); float maxy = miny; for (int i=1; i<event.getPointerCount(); i++) { final float y = event.getY(i); if (y < miny) miny = y; if (y > maxy) maxy = y; } if (maxy - miny < mHandleBarHeight) { if (mJustPeeked || getExpandedHeight() < mHandleBarHeight) { mStatusBar.switchToSettings(); } else { mStatusBar.flipToSettings(); } mOkToFlip = false; } } else if (mSwipeTriggered) { final float deltaX = (event.getX(0) - mGestureStartX) * mSwipeDirection; mStatusBar.partialFlip(mFlipOffset + deltaX / (getWidth() * STATUS_BAR_SWIPE_MOVE_PERCENTAGE)); if (!swipeFlipJustStarted) { return true; // Consume the event. } } else if (swipeFlipJustFinished) { mStatusBar.completePartialFlip(); } if (swipeFlipJustStarted || swipeFlipJustFinished) { // Made up event: finger at the middle bottom of the view. MotionEvent original = event; event = MotionEvent.obtain(original.getDownTime(), original.getEventTime(), original.getAction(), getWidth()/2, getHeight(), original.getPressure(0), original.getSize(0), original.getMetaState(), original.getXPrecision(), original.getYPrecision(), original.getDeviceId(), original.getEdgeFlags()); // The following two lines looks better than the chunk of code above, but, // nevertheless, doesn't work. The view is not pinned down, and may close, // just after the gesture is finished. // // event = MotionEvent.obtainNoHistory(original); // event.setLocation(getWidth()/2, getHeight()); shouldRecycleEvent = true; } } final boolean result = mHandleView.dispatchTouchEvent(event); if (shouldRecycleEvent) { event.recycle(); } return result; }
public boolean onTouchEvent(MotionEvent event) { boolean shouldRecycleEvent = false; if (PhoneStatusBar.SETTINGS_DRAG_SHORTCUT && mStatusBar.mHasFlipSettings) { boolean flip = false; boolean swipeFlipJustFinished = false; boolean swipeFlipJustStarted = false; switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: mGestureStartX = event.getX(0); mGestureStartY = event.getY(0); mTrackingSwipe = isFullyExpanded() && // Pointer is at the handle portion of the view? mGestureStartY > getHeight() - mHandleBarHeight - getPaddingBottom(); mOkToFlip = getExpandedHeight() == 0; if (event.getX(0) > getWidth() * (1.0f - STATUS_BAR_SETTINGS_RIGHT_PERCENTAGE) && Settings.System.getIntForUser(getContext().getContentResolver(), Settings.System.QS_QUICK_PULLDOWN, 0, UserHandle.USER_CURRENT) == 1) { flip = true; } else if (event.getX(0) < getWidth() * (1.0f - STATUS_BAR_SETTINGS_LEFT_PERCENTAGE) && Settings.System.getIntForUser(getContext().getContentResolver(), Settings.System.QS_QUICK_PULLDOWN, 0, UserHandle.USER_CURRENT) == 2) { flip = true; } break; case MotionEvent.ACTION_MOVE: final float deltaX = Math.abs(event.getX(0) - mGestureStartX); final float deltaY = Math.abs(event.getY(0) - mGestureStartY); final float maxDeltaY = getHeight() * STATUS_BAR_SWIPE_VERTICAL_MAX_PERCENTAGE; final float minDeltaX = getWidth() * STATUS_BAR_SWIPE_TRIGGER_PERCENTAGE; if (mTrackingSwipe && deltaY > maxDeltaY) { mTrackingSwipe = false; } if (mTrackingSwipe && deltaX > deltaY && deltaX > minDeltaX) { // The value below can be used to adjust deltaX to always increase, // if the user keeps swiping in the same direction as she started the // gesture. If she, however, moves her finger the other way, deltaX will // decrease. // // This allows for an horizontal swipe, in any direction, to always flip // the views. mSwipeDirection = event.getX(0) < mGestureStartX ? -1f : 1f; if (mStatusBar.isShowingSettings()) { mFlipOffset = 1f; // in this case, however, we need deltaX to decrease mSwipeDirection = -mSwipeDirection; } else { mFlipOffset = -1f; } mGestureStartX = event.getX(0); mTrackingSwipe = false; mSwipeTriggered = true; swipeFlipJustStarted = true; } break; case MotionEvent.ACTION_POINTER_DOWN: flip = true; break; case MotionEvent.ACTION_UP: swipeFlipJustFinished = mSwipeTriggered; mSwipeTriggered = false; mTrackingSwipe = false; break; } if (mOkToFlip && flip) { float miny = event.getY(0); float maxy = miny; for (int i=1; i<event.getPointerCount(); i++) { final float y = event.getY(i); if (y < miny) miny = y; if (y > maxy) maxy = y; } if (maxy - miny < mHandleBarHeight) { if (mJustPeeked || getExpandedHeight() < mHandleBarHeight) { mStatusBar.switchToSettings(); } else { mStatusBar.flipToSettings(); } mOkToFlip = false; } } else if (mSwipeTriggered) { final float deltaX = (event.getX(0) - mGestureStartX) * mSwipeDirection; mStatusBar.partialFlip(mFlipOffset + deltaX / (getWidth() * STATUS_BAR_SWIPE_MOVE_PERCENTAGE)); if (!swipeFlipJustStarted) { return true; // Consume the event. } } else if (swipeFlipJustFinished) { mStatusBar.completePartialFlip(); } if (swipeFlipJustStarted || swipeFlipJustFinished) { // Made up event: finger at the middle bottom of the view. MotionEvent original = event; event = MotionEvent.obtain(original.getDownTime(), original.getEventTime(), original.getAction(), getWidth()/2, getHeight(), original.getPressure(0), original.getSize(0), original.getMetaState(), original.getXPrecision(), original.getYPrecision(), original.getDeviceId(), original.getEdgeFlags()); // The following two lines looks better than the chunk of code above, but, // nevertheless, doesn't work. The view is not pinned down, and may close, // just after the gesture is finished. // // event = MotionEvent.obtainNoHistory(original); // event.setLocation(getWidth()/2, getHeight()); shouldRecycleEvent = true; } } final boolean result = mHandleView.dispatchTouchEvent(event); if (shouldRecycleEvent) { event.recycle(); } return result; }
diff --git a/server/jetty/src/main/java/org/mortbay/jetty/servlet/NIOResourceCache.java b/server/jetty/src/main/java/org/mortbay/jetty/servlet/NIOResourceCache.java index 635a2c792..3d9659224 100644 --- a/server/jetty/src/main/java/org/mortbay/jetty/servlet/NIOResourceCache.java +++ b/server/jetty/src/main/java/org/mortbay/jetty/servlet/NIOResourceCache.java @@ -1,90 +1,88 @@ //======================================================================== //Copyright 2004-2008 Mort Bay Consulting Pty. Ltd. //------------------------------------------------------------------------ //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //======================================================================== /** * */ package org.mortbay.jetty.servlet; import java.io.File; import java.io.IOException; import java.io.InputStream; import org.mortbay.io.Buffer; import org.mortbay.io.nio.DirectNIOBuffer; import org.mortbay.io.nio.IndirectNIOBuffer; import org.mortbay.io.nio.NIOBuffer; import org.mortbay.jetty.Connector; import org.mortbay.jetty.HttpConnection; import org.mortbay.jetty.MimeTypes; import org.mortbay.jetty.ResourceCache; import org.mortbay.jetty.nio.NIOConnector; import org.mortbay.log.Log; import org.mortbay.resource.Resource; class NIOResourceCache extends ResourceCache { boolean _useFileMappedBuffer; /* ------------------------------------------------------------ */ public NIOResourceCache(MimeTypes mimeTypes) { super(mimeTypes); } /* ------------------------------------------------------------ */ protected void fill(Content content) throws IOException { Buffer buffer=null; Resource resource=content.getResource(); long length=resource.length(); if (_useFileMappedBuffer && resource.getFile()!=null) - { - File file = resource.getFile(); - if (file != null) - buffer = new DirectNIOBuffer(file); + { + buffer = new DirectNIOBuffer(resource.getFile()); } else { InputStream is = resource.getInputStream(); try { Connector connector = HttpConnection.getCurrentConnection().getConnector(); buffer = ((NIOConnector)connector).getUseDirectBuffers()? (NIOBuffer)new DirectNIOBuffer((int)length): (NIOBuffer)new IndirectNIOBuffer((int)length); } catch(OutOfMemoryError e) { Log.warn(e.toString()); Log.debug(e); buffer = new IndirectNIOBuffer((int) length); } buffer.readFrom(is,(int)length); is.close(); } content.setBuffer(buffer); } public boolean isUseFileMappedBuffer() { return _useFileMappedBuffer; } public void setUseFileMappedBuffer(boolean useFileMappedBuffer) { _useFileMappedBuffer = useFileMappedBuffer; } }
true
true
protected void fill(Content content) throws IOException { Buffer buffer=null; Resource resource=content.getResource(); long length=resource.length(); if (_useFileMappedBuffer && resource.getFile()!=null) { File file = resource.getFile(); if (file != null) buffer = new DirectNIOBuffer(file); } else { InputStream is = resource.getInputStream(); try { Connector connector = HttpConnection.getCurrentConnection().getConnector(); buffer = ((NIOConnector)connector).getUseDirectBuffers()? (NIOBuffer)new DirectNIOBuffer((int)length): (NIOBuffer)new IndirectNIOBuffer((int)length); } catch(OutOfMemoryError e) { Log.warn(e.toString()); Log.debug(e); buffer = new IndirectNIOBuffer((int) length); } buffer.readFrom(is,(int)length); is.close(); } content.setBuffer(buffer); }
protected void fill(Content content) throws IOException { Buffer buffer=null; Resource resource=content.getResource(); long length=resource.length(); if (_useFileMappedBuffer && resource.getFile()!=null) { buffer = new DirectNIOBuffer(resource.getFile()); } else { InputStream is = resource.getInputStream(); try { Connector connector = HttpConnection.getCurrentConnection().getConnector(); buffer = ((NIOConnector)connector).getUseDirectBuffers()? (NIOBuffer)new DirectNIOBuffer((int)length): (NIOBuffer)new IndirectNIOBuffer((int)length); } catch(OutOfMemoryError e) { Log.warn(e.toString()); Log.debug(e); buffer = new IndirectNIOBuffer((int) length); } buffer.readFrom(is,(int)length); is.close(); } content.setBuffer(buffer); }
diff --git a/fenix-tools/src/pt/utl/ist/fenix/tools/codeGenerator/RootDomainObjectGenerator.java b/fenix-tools/src/pt/utl/ist/fenix/tools/codeGenerator/RootDomainObjectGenerator.java index e94fa18..ee7a2f6 100644 --- a/fenix-tools/src/pt/utl/ist/fenix/tools/codeGenerator/RootDomainObjectGenerator.java +++ b/fenix-tools/src/pt/utl/ist/fenix/tools/codeGenerator/RootDomainObjectGenerator.java @@ -1,154 +1,155 @@ /** * */ package pt.utl.ist.fenix.tools.codeGenerator; import java.io.IOException; import java.util.Formatter; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import pt.utl.ist.fenix.tools.util.FileUtils; import dml.DomainClass; import dml.Role; /** * @author - Shezad Anavarali ([email protected]) * */ public class RootDomainObjectGenerator extends DomainObjectGenerator { private static final String CLASS_NAME = "net.sourceforge.fenixedu.domain.RootDomainObject"; public void appendMethodsInTheRootDomainObject() throws IOException { String rootObjectSourceCodeFilePath = outputFolder + "/" + CLASS_NAME.replace('.', '/') + sourceSuffix; Set<String> usedNames = new HashSet<String>(); Map<DomainClass, String> classes = new HashMap<DomainClass, String>(); String rootObjectSourceCode = FileUtils.readFile(rootObjectSourceCodeFilePath); int lastBrace = rootObjectSourceCode.lastIndexOf('}'); if (lastBrace > 0) { StringBuilder resultSourceCode = new StringBuilder(); resultSourceCode.append(rootObjectSourceCode.substring(0, lastBrace)); appendClosureAccessMap(resultSourceCode); Formatter methods = new Formatter(resultSourceCode); DomainClass rootDomainObjectClass = getModel().findClass(CLASS_NAME); for (Iterator<Role> iter = rootDomainObjectClass.getRoleSlots(); iter.hasNext();) { Role roleSlot = iter.next(); if (roleSlot.getMultiplicityUpper() != 1) { //String slotName = StringUtils.capitalize(roleSlot.getName()); DomainClass otherDomainClass = (DomainClass) roleSlot.getType(); String className = otherDomainClass.getName(); if(usedNames.contains(className)){ - className = otherDomainClass.getSuperclassName() + className; + continue; + //className = otherDomainClass.getSuperclassName() + className; } if(!className.equals("DomainObject")){ methods.format("\n\tpublic %s read%sByOID(Integer idInternal){\n", otherDomainClass .getFullName(), className); methods.format("\t\tfinal %s domainObject = (%s) pt.ist.fenixframework.pstm.Transaction.readDomainObject(%s.class.getName(), idInternal);\n",otherDomainClass.getFullName(), otherDomainClass.getFullName(), otherDomainClass.getFullName()); methods.format("return (domainObject == null || domainObject.getRootDomainObject() == null) ? null : domainObject;\n\t}\n"); usedNames.add(className); classes.put(otherDomainClass, className); } //appendAddToClosureAccessMap(resultSourceCode, otherDomainClass, slotName); } } resultSourceCode.append("\n\tpublic void initAccessClosures () {"); for (final Iterator<Role> iter = rootDomainObjectClass.getRoleSlots(); iter.hasNext();) { final Role roleSlot = iter.next(); if (roleSlot.getMultiplicityUpper() != 1) { final String slotName = StringUtils.capitalize(roleSlot.getName()); final DomainClass otherDomainClass = (DomainClass) roleSlot.getType(); appendAddToClosureAccessMap(resultSourceCode, otherDomainClass.getFullName(), classes.get(otherDomainClass), slotName); } } resultSourceCode.append("\n\t}"); resultSourceCode.append("\n\n}\n"); //System.out.println(resultSourceCode.toString()); FileUtils.writeFile(rootObjectSourceCodeFilePath, resultSourceCode.toString(), false); } } private void appendClosureAccessMap(final StringBuilder resultSourceCode) { resultSourceCode.append("\n\tprivate interface DomainObjectReader {"); resultSourceCode.append("\n\t\tpublic DomainObject readDomainObjectByOID(final Integer idInternal);"); resultSourceCode.append("\n\t\tpublic java.util.Set readAllDomainObjects();"); resultSourceCode.append("\n\t}"); resultSourceCode.append("\n\tprivate static final java.util.Map<String, DomainObjectReader> closureAccessMap = new java.util.HashMap<String, DomainObjectReader>();"); resultSourceCode.append("\n\tpublic static DomainObject readDomainObjectByOID(final Class domainClass, final Integer idInternal) {"); resultSourceCode.append("\n\t\tif (domainClass != null) {"); resultSourceCode.append("\n\t\t\tfinal DomainObjectReader domainObjectReader = closureAccessMap.get(domainClass.getName());"); resultSourceCode.append("\n\t\t\tif (domainObjectReader != null) {"); resultSourceCode.append("\n\t\t\t\treturn domainObjectReader.readDomainObjectByOID(idInternal);"); resultSourceCode.append("\n\t\t\t} else if (domainClass != Object.class && domainClass != DomainObject.class) {"); resultSourceCode.append("\n\t\t\t\treturn readDomainObjectByOID(domainClass.getSuperclass(), idInternal);"); resultSourceCode.append("\n\t\t\t}"); resultSourceCode.append("\n\t\t}"); resultSourceCode.append("\n\t\treturn null;"); resultSourceCode.append("\n\t}"); resultSourceCode.append("\n\tpublic static java.util.Set readAllDomainObjects(final Class domainClass) {"); resultSourceCode.append("\n\t\tfinal java.util.Set domainObjects = readAllDomainObjectsAux(domainClass);"); resultSourceCode.append("\n\t\tfinal java.util.Set resultSet = new java.util.HashSet();"); resultSourceCode.append("\n\t\tif (domainObjects != null) {"); resultSourceCode.append("\n\t\t\tfor (final Object object : domainObjects) {"); resultSourceCode.append("\n\t\t\t\tif (domainClass.isInstance(object)) {"); resultSourceCode.append("\n\t\t\t\t\tresultSet.add(object);"); resultSourceCode.append("\n\t\t\t\t}"); resultSourceCode.append("\n\t\t\t}"); resultSourceCode.append("\n\t\t}"); resultSourceCode.append("\n\t\treturn resultSet;"); resultSourceCode.append("\n\t}"); resultSourceCode.append("\n\tpublic static java.util.Set readAllDomainObjectsAux(final Class domainClass) {"); resultSourceCode.append("\n\t\tif (domainClass != null) {"); resultSourceCode.append("\n\t\t\tfinal DomainObjectReader domainObjectReader = closureAccessMap.get(domainClass.getName());"); resultSourceCode.append("\n\t\t\tif (domainObjectReader != null) {"); resultSourceCode.append("\n\t\t\t\treturn domainObjectReader.readAllDomainObjects();"); resultSourceCode.append("\n\t\t\t} else if (domainClass != Object.class && domainClass != DomainObject.class) {"); resultSourceCode.append("\n\t\t\t\treturn readAllDomainObjectsAux(domainClass.getSuperclass());"); resultSourceCode.append("\n\t\t\t}"); resultSourceCode.append("\n\t\t}"); resultSourceCode.append("\n\t\treturn null;"); resultSourceCode.append("\n\t}"); } private void appendAddToClosureAccessMap(final StringBuilder resultSourceCode, final String fullName, final String name, final String slotName) { resultSourceCode.append("\n\t\tclosureAccessMap.put("); resultSourceCode.append(fullName); resultSourceCode.append(".class.getName(), new DomainObjectReader() {"); resultSourceCode.append("\n\t\t\tpublic DomainObject readDomainObjectByOID(final Integer idInternal) {"); resultSourceCode.append("\n\t\t\t\treturn read"); resultSourceCode.append(name); resultSourceCode.append("ByOID(idInternal);"); resultSourceCode.append("\n\t\t\t}"); resultSourceCode.append("\n\t\t\tpublic java.util.Set readAllDomainObjects() {"); resultSourceCode.append("\n\t\t\t\treturn get"); resultSourceCode.append(slotName); resultSourceCode.append("Set();"); resultSourceCode.append("\n\t\t\t}"); resultSourceCode.append("\n\t\t});"); } public static void main(String[] args) { process(args, new RootDomainObjectGenerator()); System.exit(0); } }
true
true
public void appendMethodsInTheRootDomainObject() throws IOException { String rootObjectSourceCodeFilePath = outputFolder + "/" + CLASS_NAME.replace('.', '/') + sourceSuffix; Set<String> usedNames = new HashSet<String>(); Map<DomainClass, String> classes = new HashMap<DomainClass, String>(); String rootObjectSourceCode = FileUtils.readFile(rootObjectSourceCodeFilePath); int lastBrace = rootObjectSourceCode.lastIndexOf('}'); if (lastBrace > 0) { StringBuilder resultSourceCode = new StringBuilder(); resultSourceCode.append(rootObjectSourceCode.substring(0, lastBrace)); appendClosureAccessMap(resultSourceCode); Formatter methods = new Formatter(resultSourceCode); DomainClass rootDomainObjectClass = getModel().findClass(CLASS_NAME); for (Iterator<Role> iter = rootDomainObjectClass.getRoleSlots(); iter.hasNext();) { Role roleSlot = iter.next(); if (roleSlot.getMultiplicityUpper() != 1) { //String slotName = StringUtils.capitalize(roleSlot.getName()); DomainClass otherDomainClass = (DomainClass) roleSlot.getType(); String className = otherDomainClass.getName(); if(usedNames.contains(className)){ className = otherDomainClass.getSuperclassName() + className; } if(!className.equals("DomainObject")){ methods.format("\n\tpublic %s read%sByOID(Integer idInternal){\n", otherDomainClass .getFullName(), className); methods.format("\t\tfinal %s domainObject = (%s) pt.ist.fenixframework.pstm.Transaction.readDomainObject(%s.class.getName(), idInternal);\n",otherDomainClass.getFullName(), otherDomainClass.getFullName(), otherDomainClass.getFullName()); methods.format("return (domainObject == null || domainObject.getRootDomainObject() == null) ? null : domainObject;\n\t}\n"); usedNames.add(className); classes.put(otherDomainClass, className); } //appendAddToClosureAccessMap(resultSourceCode, otherDomainClass, slotName); } } resultSourceCode.append("\n\tpublic void initAccessClosures () {"); for (final Iterator<Role> iter = rootDomainObjectClass.getRoleSlots(); iter.hasNext();) { final Role roleSlot = iter.next(); if (roleSlot.getMultiplicityUpper() != 1) { final String slotName = StringUtils.capitalize(roleSlot.getName()); final DomainClass otherDomainClass = (DomainClass) roleSlot.getType(); appendAddToClosureAccessMap(resultSourceCode, otherDomainClass.getFullName(), classes.get(otherDomainClass), slotName); } } resultSourceCode.append("\n\t}"); resultSourceCode.append("\n\n}\n"); //System.out.println(resultSourceCode.toString()); FileUtils.writeFile(rootObjectSourceCodeFilePath, resultSourceCode.toString(), false); } }
public void appendMethodsInTheRootDomainObject() throws IOException { String rootObjectSourceCodeFilePath = outputFolder + "/" + CLASS_NAME.replace('.', '/') + sourceSuffix; Set<String> usedNames = new HashSet<String>(); Map<DomainClass, String> classes = new HashMap<DomainClass, String>(); String rootObjectSourceCode = FileUtils.readFile(rootObjectSourceCodeFilePath); int lastBrace = rootObjectSourceCode.lastIndexOf('}'); if (lastBrace > 0) { StringBuilder resultSourceCode = new StringBuilder(); resultSourceCode.append(rootObjectSourceCode.substring(0, lastBrace)); appendClosureAccessMap(resultSourceCode); Formatter methods = new Formatter(resultSourceCode); DomainClass rootDomainObjectClass = getModel().findClass(CLASS_NAME); for (Iterator<Role> iter = rootDomainObjectClass.getRoleSlots(); iter.hasNext();) { Role roleSlot = iter.next(); if (roleSlot.getMultiplicityUpper() != 1) { //String slotName = StringUtils.capitalize(roleSlot.getName()); DomainClass otherDomainClass = (DomainClass) roleSlot.getType(); String className = otherDomainClass.getName(); if(usedNames.contains(className)){ continue; //className = otherDomainClass.getSuperclassName() + className; } if(!className.equals("DomainObject")){ methods.format("\n\tpublic %s read%sByOID(Integer idInternal){\n", otherDomainClass .getFullName(), className); methods.format("\t\tfinal %s domainObject = (%s) pt.ist.fenixframework.pstm.Transaction.readDomainObject(%s.class.getName(), idInternal);\n",otherDomainClass.getFullName(), otherDomainClass.getFullName(), otherDomainClass.getFullName()); methods.format("return (domainObject == null || domainObject.getRootDomainObject() == null) ? null : domainObject;\n\t}\n"); usedNames.add(className); classes.put(otherDomainClass, className); } //appendAddToClosureAccessMap(resultSourceCode, otherDomainClass, slotName); } } resultSourceCode.append("\n\tpublic void initAccessClosures () {"); for (final Iterator<Role> iter = rootDomainObjectClass.getRoleSlots(); iter.hasNext();) { final Role roleSlot = iter.next(); if (roleSlot.getMultiplicityUpper() != 1) { final String slotName = StringUtils.capitalize(roleSlot.getName()); final DomainClass otherDomainClass = (DomainClass) roleSlot.getType(); appendAddToClosureAccessMap(resultSourceCode, otherDomainClass.getFullName(), classes.get(otherDomainClass), slotName); } } resultSourceCode.append("\n\t}"); resultSourceCode.append("\n\n}\n"); //System.out.println(resultSourceCode.toString()); FileUtils.writeFile(rootObjectSourceCodeFilePath, resultSourceCode.toString(), false); } }
diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeDestructionCallbackIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeDestructionCallbackIntegrationTests.java index 445222f11..00a86b51b 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeDestructionCallbackIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeDestructionCallbackIntegrationTests.java @@ -1,72 +1,72 @@ package org.springframework.batch.core.scope; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.Step; import org.springframework.batch.core.StepExecution; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration @RunWith(SpringJUnit4ClassRunner.class) public class StepScopeDestructionCallbackIntegrationTests { @Autowired @Qualifier("proxied") private Step proxied; @Autowired @Qualifier("nested") private Step nested; @Autowired @Qualifier("foo") private Collaborator foo; @Before @After public void resetMessage() throws Exception { TestDisposableCollaborator.message = "none"; TestAdvice.names.clear(); } @Test public void testDisposableScopedProxy() throws Exception { assertNotNull(proxied); proxied.execute(new StepExecution("step", new JobExecution(0L), 1L)); assertEquals("destroyed", TestDisposableCollaborator.message); } @Test public void testDisposableInnerScopedProxy() throws Exception { assertNotNull(nested); nested.execute(new StepExecution("step", new JobExecution(0L), 1L)); assertEquals("destroyed", TestDisposableCollaborator.message); } @Test public void testProxiedScopedProxy() throws Exception { assertNotNull(nested); nested.execute(new StepExecution("step", new JobExecution(0L), 1L)); - assertEquals(2, TestAdvice.names.size()); + assertEquals(4, TestAdvice.names.size()); assertEquals("bar", TestAdvice.names.get(0)); assertEquals("destroyed", TestDisposableCollaborator.message); } @Test public void testProxiedNormalBean() throws Exception { assertNotNull(nested); String name = foo.getName(); assertEquals(1, TestAdvice.names.size()); assertEquals(name, TestAdvice.names.get(0)); } }
true
true
public void testProxiedScopedProxy() throws Exception { assertNotNull(nested); nested.execute(new StepExecution("step", new JobExecution(0L), 1L)); assertEquals(2, TestAdvice.names.size()); assertEquals("bar", TestAdvice.names.get(0)); assertEquals("destroyed", TestDisposableCollaborator.message); }
public void testProxiedScopedProxy() throws Exception { assertNotNull(nested); nested.execute(new StepExecution("step", new JobExecution(0L), 1L)); assertEquals(4, TestAdvice.names.size()); assertEquals("bar", TestAdvice.names.get(0)); assertEquals("destroyed", TestDisposableCollaborator.message); }
diff --git a/src/InvTweaksItemTree.java b/src/InvTweaksItemTree.java index 2ffaea0..baf7da5 100644 --- a/src/InvTweaksItemTree.java +++ b/src/InvTweaksItemTree.java @@ -1,272 +1,275 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Vector; import java.util.logging.Logger; /** * Contains the whole hierarchy of categories and items, as defined * in the XML item tree. Is used to recognize keywords and store * item orders. * @author Jimeo Wan * */ public class InvTweaksItemTree { public static final int MAX_CATEGORY_RANGE = 1000; public static final String UNKNOWN_ITEM = "unknown"; private static final Logger log = Logger.getLogger("InvTweaks"); /** All categories, stored by name */ private Map<String, InvTweaksItemTreeCategory> categories = new HashMap<String, InvTweaksItemTreeCategory>(); /** Items stored by ID. A same ID can hold several names. */ private Map<Integer, Vector<InvTweaksItemTreeItem>> itemsById = new HashMap<Integer, Vector<InvTweaksItemTreeItem>>(500); private static Vector<InvTweaksItemTreeItem> defaultItems = null; /** Items stored by name. A same name can match several IDs. */ private Map<String, Vector<InvTweaksItemTreeItem>> itemsByName = new HashMap<String, Vector<InvTweaksItemTreeItem>>(500); private String rootCategory; public InvTweaksItemTree() { reset(); } public void reset() { if (defaultItems == null) { defaultItems = new Vector<InvTweaksItemTreeItem>(); defaultItems.add(new InvTweaksItemTreeItem(UNKNOWN_ITEM, -1, -1, Integer.MAX_VALUE)); } // Reset tree categories.clear(); itemsByName.clear(); itemsById.clear(); } /** * Checks it given item ID matches a given keyword (either the item's name * is the keyword, or it is in the keyword category) * * @param item * @param keyword * @return */ public boolean matches(List<InvTweaksItemTreeItem> items, String keyword) { if (items == null) return false; // The keyword is an item for (InvTweaksItemTreeItem item : items) { if (item.getName().equals(keyword)) { return true; } } // The keyword is a category InvTweaksItemTreeCategory category = getCategory(keyword); if (category != null) { for (InvTweaksItemTreeItem item : items) { if (category.contains(item)) { return true; } } } // Everything is stuff if (keyword.equals(rootCategory)) { return true; } return false; } public int getKeywordDepth(String keyword) { try { return getRootCategory().findKeywordDepth(keyword); } catch (NullPointerException e) { log.severe("The root category is missing: " + e.getMessage()); return 0; } } public int getKeywordOrder(String keyword) { List<InvTweaksItemTreeItem> items = getItems(keyword); if (items != null && items.size() != 0) { return items.get(0).getOrder(); } else { try { return getRootCategory().findCategoryOrder(keyword); } catch (NullPointerException e) { log.severe("The root category is missing: " + e.getMessage()); return -1; } } } /** * Checks if the given keyword is valid (i.e. represents either a registered * item or a registered category) * * @param keyword * @return */ public boolean isKeywordValid(String keyword) { // Is the keyword an item? if (containsItem(keyword)) { return true; } // Or maybe a category ? else { InvTweaksItemTreeCategory category = getCategory(keyword); return category != null; } } /** * Returns a reference to all categories. */ public Collection<InvTweaksItemTreeCategory> getAllCategories() { return categories.values(); } public InvTweaksItemTreeCategory getRootCategory() { return categories.get(rootCategory); } public InvTweaksItemTreeCategory getCategory(String keyword) { return categories.get(keyword); } public boolean isItemUnknown(int id, int damage) { return itemsById.get(id) == null; } public List<InvTweaksItemTreeItem> getItems(int id, int damage) { List<InvTweaksItemTreeItem> items = itemsById.get(id); - List<InvTweaksItemTreeItem> filteredItems = new ArrayList<InvTweaksItemTreeItem>(items); + List<InvTweaksItemTreeItem> filteredItems = new ArrayList<InvTweaksItemTreeItem>(); + if (items != null) { + filteredItems.addAll(items); + } // Filter items of same ID, but different damage value if (items != null && !items.isEmpty()) { for (InvTweaksItemTreeItem item : items) { if (item.getDamage() != -1 && item.getDamage() != damage) { if (filteredItems.isEmpty()) { filteredItems.addAll(items); } filteredItems.remove(item); } } } // If there's no matching item, create new ones if (filteredItems.isEmpty()) { InvTweaksItemTreeItem newItemId = new InvTweaksItemTreeItem( String.format("%d-%d", id, damage), id, damage, 5000 + id * 16 + damage); InvTweaksItemTreeItem newItemDamage = new InvTweaksItemTreeItem( Integer.toString(id), id, -1, 5000 + id * 16); addItem(getRootCategory().getName(), newItemId); addItem(getRootCategory().getName(), newItemDamage); filteredItems.add(newItemId); filteredItems.add(newItemDamage); } return filteredItems; } public List<InvTweaksItemTreeItem> getItems(String name) { return itemsByName.get(name); } public InvTweaksItemTreeItem getRandomItem(Random r) { return (InvTweaksItemTreeItem) itemsByName.values() .toArray()[r.nextInt(itemsByName.size())]; } public boolean containsItem(String name) { return itemsByName.containsKey(name); } public boolean containsCategory(String name) { return categories.containsKey(name); } protected void setRootCategory(InvTweaksItemTreeCategory category) { rootCategory = category.getName(); categories.put(rootCategory, category); } protected void addCategory(String parentCategory, InvTweaksItemTreeCategory newCategory) throws NullPointerException { // Build tree categories.get(parentCategory.toLowerCase()).addCategory(newCategory); // Register category categories.put(newCategory.getName(), newCategory); } protected void addItem(String parentCategory, InvTweaksItemTreeItem newItem) throws NullPointerException { // Build tree categories.get(parentCategory.toLowerCase()).addItem(newItem); // Register item if (itemsByName.containsKey(newItem.getName())) { itemsByName.get(newItem.getName()).add(newItem); } else { Vector<InvTweaksItemTreeItem> list = new Vector<InvTweaksItemTreeItem>(); list.add(newItem); itemsByName.put(newItem.getName(), list); } if (itemsById.containsKey(newItem.getId())) { itemsById.get(newItem.getId()).add(newItem); } else { Vector<InvTweaksItemTreeItem> list = new Vector<InvTweaksItemTreeItem>(); list.add(newItem); itemsById.put(newItem.getId(), list); } } /** * For debug purposes. Call log(getRootCategory(), 0) to log the whole tree. */ @SuppressWarnings("unused") private void log(InvTweaksItemTreeCategory category, int indentLevel) { String logIdent = ""; for (int i = 0; i < indentLevel; i++) { logIdent += " "; } log.info(logIdent + category.getName()); for (InvTweaksItemTreeCategory subCategory : category.getSubCategories()) { log(subCategory, indentLevel + 1); } for (List<InvTweaksItemTreeItem> itemList : category.getItems()) { for (InvTweaksItemTreeItem item : itemList) { log.info(logIdent + " " + item + " " + item.getId() + " " + item.getDamage()); } } } }
true
true
public List<InvTweaksItemTreeItem> getItems(int id, int damage) { List<InvTweaksItemTreeItem> items = itemsById.get(id); List<InvTweaksItemTreeItem> filteredItems = new ArrayList<InvTweaksItemTreeItem>(items); // Filter items of same ID, but different damage value if (items != null && !items.isEmpty()) { for (InvTweaksItemTreeItem item : items) { if (item.getDamage() != -1 && item.getDamage() != damage) { if (filteredItems.isEmpty()) { filteredItems.addAll(items); } filteredItems.remove(item); } } } // If there's no matching item, create new ones if (filteredItems.isEmpty()) { InvTweaksItemTreeItem newItemId = new InvTweaksItemTreeItem( String.format("%d-%d", id, damage), id, damage, 5000 + id * 16 + damage); InvTweaksItemTreeItem newItemDamage = new InvTweaksItemTreeItem( Integer.toString(id), id, -1, 5000 + id * 16); addItem(getRootCategory().getName(), newItemId); addItem(getRootCategory().getName(), newItemDamage); filteredItems.add(newItemId); filteredItems.add(newItemDamage); } return filteredItems; }
public List<InvTweaksItemTreeItem> getItems(int id, int damage) { List<InvTweaksItemTreeItem> items = itemsById.get(id); List<InvTweaksItemTreeItem> filteredItems = new ArrayList<InvTweaksItemTreeItem>(); if (items != null) { filteredItems.addAll(items); } // Filter items of same ID, but different damage value if (items != null && !items.isEmpty()) { for (InvTweaksItemTreeItem item : items) { if (item.getDamage() != -1 && item.getDamage() != damage) { if (filteredItems.isEmpty()) { filteredItems.addAll(items); } filteredItems.remove(item); } } } // If there's no matching item, create new ones if (filteredItems.isEmpty()) { InvTweaksItemTreeItem newItemId = new InvTweaksItemTreeItem( String.format("%d-%d", id, damage), id, damage, 5000 + id * 16 + damage); InvTweaksItemTreeItem newItemDamage = new InvTweaksItemTreeItem( Integer.toString(id), id, -1, 5000 + id * 16); addItem(getRootCategory().getName(), newItemId); addItem(getRootCategory().getName(), newItemDamage); filteredItems.add(newItemId); filteredItems.add(newItemDamage); } return filteredItems; }
diff --git a/js-karma/src/com/intellij/javascript/karma/execution/KarmaRunConfiguration.java b/js-karma/src/com/intellij/javascript/karma/execution/KarmaRunConfiguration.java index 06c2fea240..530becace7 100644 --- a/js-karma/src/com/intellij/javascript/karma/execution/KarmaRunConfiguration.java +++ b/js-karma/src/com/intellij/javascript/karma/execution/KarmaRunConfiguration.java @@ -1,144 +1,144 @@ package com.intellij.javascript.karma.execution; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.configurations.*; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; import com.intellij.psi.PsiElement; import com.intellij.refactoring.listeners.RefactoringElementListener; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; /** * @author Sergey Simonchik */ public class KarmaRunConfiguration extends LocatableConfigurationBase implements RefactoringListenerProvider { private KarmaRunSettings myRunSettings = new KarmaRunSettings.Builder().build(); private final ThreadLocal<GlobalSettings> myGlobalSettingsRef = new ThreadLocal<GlobalSettings>(); protected KarmaRunConfiguration(@NotNull Project project, @NotNull ConfigurationFactory factory, @NotNull String name) { super(project, factory, name); } @NotNull @Override public KarmaRunConfigurationEditor getConfigurationEditor() { return new KarmaRunConfigurationEditor(getProject()); } @Override public void readExternal(Element element) throws InvalidDataException { super.readExternal(element); KarmaRunSettings runSettings = KarmaRunSettingsSerializationUtil.readFromXml(element); setRunSettings(runSettings); } @Override public void writeExternal(Element element) throws WriteExternalException { super.writeExternal(element); KarmaRunSettingsSerializationUtil.writeToXml(element, myRunSettings); } @Nullable @Override public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment env) throws ExecutionException { try { checkConfiguration(); } catch (RuntimeConfigurationError e) { throw new ExecutionException(e.getMessage()); } catch (RuntimeConfigurationException ignored) { // does nothing } GlobalSettings globalSettings = myGlobalSettingsRef.get(); if (globalSettings == null) { return null; } return new KarmaRunProfileState(getProject(), env, globalSettings.myNodeInterpreterPath, globalSettings.myKarmaNodePackage, myRunSettings, executor); } @Override public void checkConfiguration() throws RuntimeConfigurationException { myGlobalSettingsRef.remove(); String nodeInterpreterPath = KarmaGlobalSettingsUtil.getNodeInterpreterPath(); String karmaPackagePath = KarmaGlobalSettingsUtil.getKarmaNodePackageDir(getProject(), myRunSettings.getConfigPath()); check(nodeInterpreterPath, karmaPackagePath); if (nodeInterpreterPath != null && karmaPackagePath != null) { myGlobalSettingsRef.set(new GlobalSettings(nodeInterpreterPath, karmaPackagePath)); } } private void check(@Nullable String nodeInterpreterPath, @Nullable String karmaPackagePath) throws RuntimeConfigurationError { if (nodeInterpreterPath == null || nodeInterpreterPath.trim().isEmpty()) { - throw new RuntimeConfigurationError("Please specify Node.js interpreter"); + throw new RuntimeConfigurationError("Please specify Node.js interpreter path"); } File nodeInterpreter = new File(nodeInterpreterPath); if (!nodeInterpreter.isFile() || !nodeInterpreter.canExecute() || !nodeInterpreter.isAbsolute()) { - throw new RuntimeConfigurationError("Incorrect Node.js interpreter path"); + throw new RuntimeConfigurationError("Please specify Node.js interpreter path correctly"); } if (karmaPackagePath == null || karmaPackagePath.trim().isEmpty()) { - throw new RuntimeConfigurationError("Please specify Karma Node.js package"); + throw new RuntimeConfigurationError("Please specify Karma package path"); } File karmaPackageDir = new File(karmaPackagePath); if (!karmaPackageDir.isDirectory() || !karmaPackageDir.isAbsolute()) { - throw new RuntimeConfigurationError("Incorrect Karma Node.js package"); + throw new RuntimeConfigurationError("Please specify Karma package path correctly"); } String configPath = myRunSettings.getConfigPath(); if (configPath.trim().isEmpty()) { - throw new RuntimeConfigurationError("Config file path is empty"); + throw new RuntimeConfigurationError("Please specify config file path"); } File configFile = new File(configPath); if (!configFile.exists()) { throw new RuntimeConfigurationError("Configuration file does not exist"); } if (!configFile.isFile()) { - throw new RuntimeConfigurationError("Specified config file path is incorrect"); + throw new RuntimeConfigurationError("Please specify config file path correctly"); } } @NotNull public KarmaRunSettings getRunSettings() { return myRunSettings; } public void setRunSettings(@NotNull KarmaRunSettings runSettings) { myRunSettings = runSettings; } @Override public String suggestedName() { File file = new File(myRunSettings.getConfigPath()); return file.getName(); } @Nullable @Override public RefactoringElementListener getRefactoringElementListener(PsiElement element) { return KarmaRunConfigurationRefactoringHandler.getRefactoringElementListener(this, element); } private static class GlobalSettings { private final String myNodeInterpreterPath; private final String myKarmaNodePackage; private GlobalSettings(@NotNull String nodeInterpreterPath, @NotNull String karmaNodePackage) { myKarmaNodePackage = karmaNodePackage; myNodeInterpreterPath = nodeInterpreterPath; } } }
false
true
private void check(@Nullable String nodeInterpreterPath, @Nullable String karmaPackagePath) throws RuntimeConfigurationError { if (nodeInterpreterPath == null || nodeInterpreterPath.trim().isEmpty()) { throw new RuntimeConfigurationError("Please specify Node.js interpreter"); } File nodeInterpreter = new File(nodeInterpreterPath); if (!nodeInterpreter.isFile() || !nodeInterpreter.canExecute() || !nodeInterpreter.isAbsolute()) { throw new RuntimeConfigurationError("Incorrect Node.js interpreter path"); } if (karmaPackagePath == null || karmaPackagePath.trim().isEmpty()) { throw new RuntimeConfigurationError("Please specify Karma Node.js package"); } File karmaPackageDir = new File(karmaPackagePath); if (!karmaPackageDir.isDirectory() || !karmaPackageDir.isAbsolute()) { throw new RuntimeConfigurationError("Incorrect Karma Node.js package"); } String configPath = myRunSettings.getConfigPath(); if (configPath.trim().isEmpty()) { throw new RuntimeConfigurationError("Config file path is empty"); } File configFile = new File(configPath); if (!configFile.exists()) { throw new RuntimeConfigurationError("Configuration file does not exist"); } if (!configFile.isFile()) { throw new RuntimeConfigurationError("Specified config file path is incorrect"); } }
private void check(@Nullable String nodeInterpreterPath, @Nullable String karmaPackagePath) throws RuntimeConfigurationError { if (nodeInterpreterPath == null || nodeInterpreterPath.trim().isEmpty()) { throw new RuntimeConfigurationError("Please specify Node.js interpreter path"); } File nodeInterpreter = new File(nodeInterpreterPath); if (!nodeInterpreter.isFile() || !nodeInterpreter.canExecute() || !nodeInterpreter.isAbsolute()) { throw new RuntimeConfigurationError("Please specify Node.js interpreter path correctly"); } if (karmaPackagePath == null || karmaPackagePath.trim().isEmpty()) { throw new RuntimeConfigurationError("Please specify Karma package path"); } File karmaPackageDir = new File(karmaPackagePath); if (!karmaPackageDir.isDirectory() || !karmaPackageDir.isAbsolute()) { throw new RuntimeConfigurationError("Please specify Karma package path correctly"); } String configPath = myRunSettings.getConfigPath(); if (configPath.trim().isEmpty()) { throw new RuntimeConfigurationError("Please specify config file path"); } File configFile = new File(configPath); if (!configFile.exists()) { throw new RuntimeConfigurationError("Configuration file does not exist"); } if (!configFile.isFile()) { throw new RuntimeConfigurationError("Please specify config file path correctly"); } }
diff --git a/test/com/sun/jna/CallbacksTest.java b/test/com/sun/jna/CallbacksTest.java index a58e0efd..7f18d683 100644 --- a/test/com/sun/jna/CallbacksTest.java +++ b/test/com/sun/jna/CallbacksTest.java @@ -1,1276 +1,1277 @@ /* Copyright (c) 2007-2008 Timothy Wall, 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. * <p/> * 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. */ package com.sun.jna; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.ref.WeakReference; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import junit.framework.TestCase; import com.sun.jna.Callback.UncaughtExceptionHandler; import com.sun.jna.CallbacksTest.TestLibrary.CbCallback; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import com.sun.jna.win32.W32APIOptions; /** Exercise callback-related functionality. * * @author [email protected] */ //@SuppressWarnings("unused") public class CallbacksTest extends TestCase { private static final String UNICODE = "[\u0444]"; private static final double DOUBLE_MAGIC = -118.625d; private static final float FLOAT_MAGIC = -118.625f; public static class SmallTestStructure extends Structure { public double value; public static int allocations = 0; protected void allocateMemory(int size) { super.allocateMemory(size); ++allocations; } public SmallTestStructure() { } public SmallTestStructure(Pointer p) { super(p); read(); } protected List getFieldOrder() { return Arrays.asList(new String[] { "value" }); } } public static class TestStructure extends Structure { public static class ByValue extends TestStructure implements Structure.ByValue { } public static interface TestCallback extends Callback { TestStructure.ByValue callback(TestStructure.ByValue s); } public byte c; public short s; public int i; public long j; public SmallTestStructure inner; protected List getFieldOrder() { return Arrays.asList(new String[] { "c", "s", "i", "j", "inner" }); } } public static interface TestLibrary extends Library { interface NoMethodCallback extends Callback { } interface CustomMethodCallback extends Callback { void invoke(); } interface TooManyMethodsCallback extends Callback { void invoke(); void invoke2(); } interface MultipleMethodsCallback extends Callback { void invoke(); void callback(); } interface VoidCallback extends Callback { void callback(); } void callVoidCallback(VoidCallback c); void callVoidCallbackThreaded(VoidCallback c, int count, int ms); interface VoidCallbackCustom extends Callback { void customMethodName(); } abstract class VoidCallbackCustomAbstract implements VoidCallbackCustom { public void customMethodName() { } } class VoidCallbackCustomDerived extends VoidCallbackCustomAbstract { } void callVoidCallback(VoidCallbackCustom c); interface BooleanCallback extends Callback { boolean callback(boolean arg, boolean arg2); } boolean callBooleanCallback(BooleanCallback c, boolean arg, boolean arg2); interface ByteCallback extends Callback { byte callback(byte arg, byte arg2); } byte callInt8Callback(ByteCallback c, byte arg, byte arg2); interface ShortCallback extends Callback { short callback(short arg, short arg2); } short callInt16Callback(ShortCallback c, short arg, short arg2); interface Int32Callback extends Callback { int callback(int arg, int arg2); } int callInt32Callback(Int32Callback c, int arg, int arg2); interface NativeLongCallback extends Callback { NativeLong callback(NativeLong arg, NativeLong arg2); } NativeLong callNativeLongCallback(NativeLongCallback c, NativeLong arg, NativeLong arg2); interface Int64Callback extends Callback { long callback(long arg, long arg2); } long callInt64Callback(Int64Callback c, long arg, long arg2); interface FloatCallback extends Callback { float callback(float arg, float arg2); } float callFloatCallback(FloatCallback c, float arg, float arg2); interface DoubleCallback extends Callback { double callback(double arg, double arg2); } double callDoubleCallback(DoubleCallback c, double arg, double arg2); interface StructureCallback extends Callback { SmallTestStructure callback(SmallTestStructure arg); } SmallTestStructure callStructureCallback(StructureCallback c, SmallTestStructure arg); interface StringCallback extends Callback { String callback(String arg); } String callStringCallback(StringCallback c, String arg); interface WideStringCallback extends Callback { WString callback(WString arg); } WString callWideStringCallback(WideStringCallback c, WString arg); interface CopyArgToByReference extends Callback { int callback(int arg, IntByReference result); } interface StringArrayCallback extends Callback { String[] callback(String[] arg); } Pointer callStringArrayCallback(StringArrayCallback c, String[] arg); int callCallbackWithByReferenceArgument(CopyArgToByReference cb, int arg, IntByReference result); TestStructure.ByValue callCallbackWithStructByValue(TestStructure.TestCallback callback, TestStructure.ByValue cbstruct); interface CbCallback extends Callback { CbCallback callback(CbCallback arg); } CbCallback callCallbackWithCallback(CbCallback cb); interface Int32CallbackX extends Callback { public int callback(int arg); } Int32CallbackX returnCallback(); Int32CallbackX returnCallbackArgument(Int32CallbackX cb); interface CustomCallback extends Callback { Custom callback(Custom arg1, Custom arg2); } int callInt32Callback(CustomCallback cb, int arg1, int arg2); class CbStruct extends Structure { public Callback cb; protected List getFieldOrder() { return Arrays.asList(new String[] { "cb" }); } } void callCallbackInStruct(CbStruct cbstruct); // Union (by value) class TestUnion extends Union implements Structure.ByValue { public String f1; public int f2; } interface UnionCallback extends Callback { TestUnion invoke(TestUnion arg); } TestUnion testUnionByValueCallbackArgument(UnionCallback cb, TestUnion arg); } TestLibrary lib; protected void setUp() { lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); } protected void tearDown() { lib = null; } public static class Custom implements NativeMapped { private int value; public Custom() { } public Custom(int value) { this.value = value; } public Object fromNative(Object nativeValue, FromNativeContext context) { return new Custom(((Integer)nativeValue).intValue()); } public Class nativeType() { return Integer.class; } public Object toNative() { return new Integer(value); } public boolean equals(Object o) { return o instanceof Custom && ((Custom)o).value == value; } } public void testLookupNullCallback() { assertNull("NULL pointer should result in null callback", CallbackReference.getCallback(null, null)); try { CallbackReference.getCallback(TestLibrary.VoidCallback.class, new Pointer(0)); fail("Null pointer lookup should fail"); } catch(NullPointerException e) { } } public void testLookupNonCallbackClass() { try { CallbackReference.getCallback(String.class, new Pointer(0)); fail("Request for non-Callback class should fail"); } catch(IllegalArgumentException e) { } } public void testNoMethodCallback() { try { CallbackReference.getCallback(TestLibrary.NoMethodCallback.class, new Pointer(1)); fail("Callback with no callback method should fail"); } catch(IllegalArgumentException e) { } } public void testCustomMethodCallback() { CallbackReference.getCallback(TestLibrary.CustomMethodCallback.class, new Pointer(1)); } public void testTooManyMethodsCallback() { try { CallbackReference.getCallback(TestLibrary.TooManyMethodsCallback.class, new Pointer(1)); fail("Callback lookup with too many methods should fail"); } catch(IllegalArgumentException e) { } } public void testMultipleMethodsCallback() { CallbackReference.getCallback(TestLibrary.MultipleMethodsCallback.class, new Pointer(1)); } public void testNativeFunctionPointerStringValue() { Callback cb = CallbackReference.getCallback(TestLibrary.VoidCallback.class, new Pointer(1)); Class cls = CallbackReference.findCallbackClass(cb.getClass()); assertTrue("toString should include Java Callback type: " + cb + " (" + cls + ")", cb.toString().indexOf(cls.getName()) != -1); } public void testLookupSameCallback() { Callback cb = CallbackReference.getCallback(TestLibrary.VoidCallback.class, new Pointer(1)); Callback cb2 = CallbackReference.getCallback(TestLibrary.VoidCallback.class, new Pointer(1)); assertEquals("Callback lookups for same pointer should return same Callback object", cb, cb2); } // Allow direct tests to override protected Map callbackCache() { return CallbackReference.callbackMap; } // Fails on OpenJDK(linux/ppc), probably finalize not run public void testGCCallbackOnFinalize() throws Exception { final boolean[] called = { false }; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { public void callback() { called[0] = true; } }; lib.callVoidCallback(cb); assertTrue("Callback not called", called[0]); Map refs = new WeakHashMap(callbackCache()); assertTrue("Callback not cached", refs.containsKey(cb)); CallbackReference ref = (CallbackReference)refs.get(cb); refs = callbackCache(); Pointer cbstruct = ref.cbstruct; cb = null; System.gc(); for (int i = 0; i < 100 && (ref.get() != null || refs.containsValue(ref)); ++i) { try { Thread.sleep(10); // Give the GC a chance to run System.gc(); } finally {} } assertNull("Callback not GC'd", ref.get()); assertFalse("Callback still in map", refs.containsValue(ref)); ref = null; System.gc(); for (int i = 0; i < 100 && (cbstruct.peer != 0 || refs.size() > 0); ++i) { // Flush weak hash map refs.size(); try { Thread.sleep(10); // Give the GC a chance to run System.gc(); } finally {} } assertEquals("Callback trampoline not freed", 0, cbstruct.peer); } public void testFindCallbackInterface() { TestLibrary.Int32Callback cb = new TestLibrary.Int32Callback() { public int callback(int arg, int arg2) { return arg + arg2; } }; assertEquals("Wrong callback interface", TestLibrary.Int32Callback.class, CallbackReference.findCallbackClass(cb.getClass())); } public void testCallVoidCallback() { final boolean[] called = { false }; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { public void callback() { called[0] = true; } }; lib.callVoidCallback(cb); assertTrue("Callback not called", called[0]); } public void testCallInt32Callback() { final int MAGIC = 0x11111111; final boolean[] called = { false }; TestLibrary.Int32Callback cb = new TestLibrary.Int32Callback() { public int callback(int arg, int arg2) { called[0] = true; return arg + arg2; } }; final int EXPECTED = MAGIC*3; int value = lib.callInt32Callback(cb, MAGIC, MAGIC*2); assertTrue("Callback not called", called[0]); assertEquals("Wrong callback value", Integer.toHexString(EXPECTED), Integer.toHexString(value)); value = lib.callInt32Callback(cb, -1, -2); assertEquals("Wrong callback return", -3, value); } public void testCallInt64Callback() { final long MAGIC = 0x1111111111111111L; final boolean[] called = { false }; TestLibrary.Int64Callback cb = new TestLibrary.Int64Callback() { public long callback(long arg, long arg2) { called[0] = true; return arg + arg2; } }; final long EXPECTED = MAGIC*3; long value = lib.callInt64Callback(cb, MAGIC, MAGIC*2); assertTrue("Callback not called", called[0]); assertEquals("Wrong callback value", Long.toHexString(EXPECTED), Long.toHexString(value)); value = lib.callInt64Callback(cb, -1, -2); assertEquals("Wrong callback return", -3, value); } public void testCallFloatCallback() { final boolean[] called = { false }; final float[] args = { 0, 0 }; TestLibrary.FloatCallback cb = new TestLibrary.FloatCallback() { public float callback(float arg, float arg2) { called[0] = true; args[0] = arg; args[1] = arg2; return arg + arg2; } }; final float EXPECTED = FLOAT_MAGIC*3; float value = lib.callFloatCallback(cb, FLOAT_MAGIC, FLOAT_MAGIC*2); assertTrue("Callback not called", called[0]); assertEquals("Wrong first argument", FLOAT_MAGIC, args[0], 0); assertEquals("Wrong second argument", FLOAT_MAGIC*2, args[1], 0); assertEquals("Wrong callback value", EXPECTED, value, 0); value = lib.callFloatCallback(cb, -1f, -2f); assertEquals("Wrong callback return", -3f, value, 0); } public void testCallDoubleCallback() { final boolean[] called = { false }; final double[] args = { 0, 0 }; TestLibrary.DoubleCallback cb = new TestLibrary.DoubleCallback() { public double callback(double arg, double arg2) { called[0] = true; args[0] = arg; args[1] = arg2; return arg + arg2; } }; final double EXPECTED = DOUBLE_MAGIC*3; double value = lib.callDoubleCallback(cb, DOUBLE_MAGIC, DOUBLE_MAGIC*2); assertTrue("Callback not called", called[0]); assertEquals("Wrong first argument", DOUBLE_MAGIC, args[0], 0); assertEquals("Wrong second argument", DOUBLE_MAGIC*2, args[1], 0); assertEquals("Wrong callback value", EXPECTED, value, 0); value = lib.callDoubleCallback(cb, -1d, -2d); assertEquals("Wrong callback return", -3d, value, 0); } public void testCallStructureCallback() { final boolean[] called = {false}; final Pointer[] cbarg = { null }; final SmallTestStructure s = new SmallTestStructure(); final double MAGIC = 118.625; TestLibrary.StructureCallback cb = new TestLibrary.StructureCallback() { public SmallTestStructure callback(SmallTestStructure arg) { called[0] = true; cbarg[0] = arg.getPointer(); arg.value = MAGIC; return arg; } }; SmallTestStructure.allocations = 0; SmallTestStructure value = lib.callStructureCallback(cb, s); assertTrue("Callback not called", called[0]); assertEquals("Wrong argument passed to callback", s.getPointer(), cbarg[0]); assertEquals("Structure argument not synched on callback return", MAGIC, s.value, 0d); assertEquals("Wrong structure return", s.getPointer(), value.getPointer()); assertEquals("Structure return not synched", MAGIC, value.value, 0d); // All structures involved should be created from pointers, with no // memory allocation at all. assertEquals("No structure memory should be allocated", 0, SmallTestStructure.allocations); } public void testCallStructureArrayCallback() { final SmallTestStructure s = new SmallTestStructure(); final SmallTestStructure[] array = (SmallTestStructure[])s.toArray(2); final double MAGIC = 118.625; TestLibrary.StructureCallback cb = new TestLibrary.StructureCallback() { public SmallTestStructure callback(SmallTestStructure arg) { SmallTestStructure[] array = (SmallTestStructure[])arg.toArray(2); array[0].value = MAGIC; array[1].value = MAGIC*2; return arg; } }; SmallTestStructure value = lib.callStructureCallback(cb, s); assertEquals("Structure array element 0 not synched on callback return", MAGIC, array[0].value, 0d); assertEquals("Structure array element 1 not synched on callback return", MAGIC*2, array[1].value, 0d); } public void testCallBooleanCallback() { final boolean[] called = {false}; final boolean[] cbargs = { false, false }; TestLibrary.BooleanCallback cb = new TestLibrary.BooleanCallback() { public boolean callback(boolean arg, boolean arg2) { called[0] = true; cbargs[0] = arg; cbargs[1] = arg2; return arg && arg2; } }; boolean value = lib.callBooleanCallback(cb, true, false); assertTrue("Callback not called", called[0]); assertEquals("Wrong callback argument 1", true, cbargs[0]); assertEquals("Wrong callback argument 2", false, cbargs[1]); assertFalse("Wrong boolean return", value); } public void testCallInt8Callback() { final boolean[] called = {false}; final byte[] cbargs = { 0, 0 }; TestLibrary.ByteCallback cb = new TestLibrary.ByteCallback() { public byte callback(byte arg, byte arg2) { called[0] = true; cbargs[0] = arg; cbargs[1] = arg2; return (byte)(arg + arg2); } }; final byte MAGIC = 0x11; byte value = lib.callInt8Callback(cb, MAGIC, (byte)(MAGIC*2)); assertTrue("Callback not called", called[0]); assertEquals("Wrong callback argument 1", Integer.toHexString(MAGIC), Integer.toHexString(cbargs[0])); assertEquals("Wrong callback argument 2", Integer.toHexString(MAGIC*2), Integer.toHexString(cbargs[1])); assertEquals("Wrong byte return", Integer.toHexString(MAGIC*3), Integer.toHexString(value)); value = lib.callInt8Callback(cb, (byte)-1, (byte)-2); assertEquals("Wrong byte return (hi bit)", (byte)-3, value); } public void testCallInt16Callback() { final boolean[] called = {false}; final short[] cbargs = { 0, 0 }; TestLibrary.ShortCallback cb = new TestLibrary.ShortCallback() { public short callback(short arg, short arg2) { called[0] = true; cbargs[0] = arg; cbargs[1] = arg2; return (short)(arg + arg2); } }; final short MAGIC = 0x1111; short value = lib.callInt16Callback(cb, MAGIC, (short)(MAGIC*2)); assertTrue("Callback not called", called[0]); assertEquals("Wrong callback argument 1", Integer.toHexString(MAGIC), Integer.toHexString(cbargs[0])); assertEquals("Wrong callback argument 2", Integer.toHexString(MAGIC*2), Integer.toHexString(cbargs[1])); assertEquals("Wrong short return", Integer.toHexString(MAGIC*3), Integer.toHexString(value)); value = lib.callInt16Callback(cb, (short)-1, (short)-2); assertEquals("Wrong short return (hi bit)", (short)-3, value); } public void testCallNativeLongCallback() { final boolean[] called = {false}; final NativeLong[] cbargs = { null, null}; TestLibrary.NativeLongCallback cb = new TestLibrary.NativeLongCallback() { public NativeLong callback(NativeLong arg, NativeLong arg2) { called[0] = true; cbargs[0] = arg; cbargs[1] = arg2; return new NativeLong(arg.intValue() + arg2.intValue()); } }; NativeLong value = lib.callNativeLongCallback(cb, new NativeLong(1), new NativeLong(2)); assertTrue("Callback not called", called[0]); assertEquals("Wrong callback argument 1", new NativeLong(1), cbargs[0]); assertEquals("Wrong callback argument 2", new NativeLong(2), cbargs[1]); assertEquals("Wrong boolean return", new NativeLong(3), value); } public void testCallNativeMappedCallback() { final boolean[] called = {false}; final Custom[] cbargs = { null, null}; TestLibrary.CustomCallback cb = new TestLibrary.CustomCallback() { public Custom callback(Custom arg, Custom arg2) { called[0] = true; cbargs[0] = arg; cbargs[1] = arg2; return new Custom(arg.value + arg2.value); } }; int value = lib.callInt32Callback(cb, 1, 2); assertTrue("Callback not called", called[0]); assertEquals("Wrong callback argument 1", new Custom(1), cbargs[0]); assertEquals("Wrong callback argument 2", new Custom(2), cbargs[1]); assertEquals("Wrong NativeMapped return", 3, value); } public void testCallStringCallback() { final boolean[] called = {false}; final String[] cbargs = { null }; TestLibrary.StringCallback cb = new TestLibrary.StringCallback() { public String callback(String arg) { called[0] = true; cbargs[0] = arg; return arg; } }; final String VALUE = "value" + UNICODE; String value = lib.callStringCallback(cb, VALUE); assertTrue("Callback not called", called[0]); assertEquals("Wrong String callback argument", VALUE, cbargs[0]); assertEquals("Wrong String return", VALUE, value); } public void testStringCallbackMemoryReclamation() throws InterruptedException { TestLibrary.StringCallback cb = new TestLibrary.StringCallback() { public String callback(String arg) { return arg; } }; // A little internal groping Map m = CallbackReference.allocations; m.clear(); String arg = getName() + "1" + UNICODE; String value = lib.callStringCallback(cb, arg); WeakReference ref = new WeakReference(value); arg = null; value = null; System.gc(); for (int i = 0; i < 100 && (ref.get() != null || m.size() > 0); ++i) { try { Thread.sleep(10); // Give the GC a chance to run System.gc(); } finally {} } assertNull("NativeString reference not GC'd", ref.get()); assertEquals("NativeString reference still held: " + m.values(), 0, m.size()); } public void testCallWideStringCallback() { final boolean[] called = {false}; final WString[] cbargs = { null }; TestLibrary.WideStringCallback cb = new TestLibrary.WideStringCallback() { public WString callback(WString arg) { called[0] = true; cbargs[0] = arg; return arg; } }; final WString VALUE = new WString("value" + UNICODE); WString value = lib.callWideStringCallback(cb, VALUE); assertTrue("Callback not called", called[0]); assertEquals("Wrong callback argument 1", VALUE, cbargs[0]); assertEquals("Wrong wide string return", VALUE, value); } public void testCallStringArrayCallback() { final boolean[] called = {false}; final String[][] cbargs = { null }; TestLibrary.StringArrayCallback cb = new TestLibrary.StringArrayCallback() { public String[] callback(String[] arg) { called[0] = true; cbargs[0] = arg; return arg; } }; final String VALUE = "value" + UNICODE; final String[] VALUE_ARRAY = { VALUE, null }; Pointer value = lib.callStringArrayCallback(cb, VALUE_ARRAY); assertTrue("Callback not called", called[0]); assertEquals("String[] array should not be modified", VALUE, VALUE_ARRAY[0]); assertEquals("Terminating null should be removed from incoming arg", VALUE_ARRAY.length-1, cbargs[0].length); assertEquals("String[] argument index 0 mismatch", VALUE_ARRAY[0], cbargs[0][0]); String[] result = value.getStringArray(0); assertEquals("Wrong String[] return", VALUE_ARRAY[0], result[0]); assertEquals("Terminating null should be removed from return value", VALUE_ARRAY.length-1, result.length); } public void testCallCallbackWithByReferenceArgument() { final boolean[] called = {false}; TestLibrary.CopyArgToByReference cb = new TestLibrary.CopyArgToByReference() { public int callback(int arg, IntByReference result) { called[0] = true; result.setValue(arg); return result.getValue(); } }; final int VALUE = 0; IntByReference ref = new IntByReference(~VALUE); int value = lib.callCallbackWithByReferenceArgument(cb, VALUE, ref); assertEquals("Wrong value returned", VALUE, value); assertEquals("Wrong value in by reference memory", VALUE, ref.getValue()); } public void testCallCallbackWithStructByValue() { final boolean[] called = { false }; final TestStructure.ByValue[] arg = { null }; final TestStructure.ByValue s = new TestStructure.ByValue(); TestStructure.TestCallback cb = new TestStructure.TestCallback() { public TestStructure.ByValue callback(TestStructure.ByValue s) { // Copy the argument value for later comparison called[0] = true; return arg[0] = s; } }; s.c = (byte)0x11; s.s = 0x2222; s.i = 0x33333333; s.j = 0x4444444444444444L; s.inner.value = 5; TestStructure result = lib.callCallbackWithStructByValue(cb, s); assertTrue("Callback not called", called[0]); assertTrue("ByValue argument should own its own memory, instead was " + arg[0].getPointer(), arg[0].getPointer() instanceof Memory); assertTrue("ByValue result should own its own memory, instead was " + result.getPointer(), result.getPointer() instanceof Memory); assertEquals("Wrong value for callback argument", s, arg[0]); assertEquals("Wrong value for callback result", s, result); } public void testUnionByValueCallbackArgument() throws Exception{ TestLibrary.TestUnion arg = new TestLibrary.TestUnion(); arg.setType(String.class); final String VALUE = getName() + UNICODE; arg.f1 = VALUE; final boolean[] called = { false }; final TestLibrary.TestUnion[] cbvalue = { null }; TestLibrary.TestUnion result = lib.testUnionByValueCallbackArgument(new TestLibrary.UnionCallback() { public TestLibrary.TestUnion invoke(TestLibrary.TestUnion v) { called[0] = true; v.setType(String.class); v.read(); cbvalue[0] = v; return v; } }, arg); assertTrue("Callback not called", called[0]); assertTrue("ByValue argument should have its own allocated memory, instead was " + cbvalue[0].getPointer(), cbvalue[0].getPointer() instanceof Memory); assertEquals("Wrong value for callback argument", VALUE, cbvalue[0].f1); assertEquals("Wrong value for callback result", VALUE, result.getTypedValue(String.class)); } public void testCallCallbackWithCallbackArgumentAndResult() { TestLibrary.CbCallback cb = new TestLibrary.CbCallback() { public CbCallback callback(CbCallback arg) { return arg; } }; TestLibrary.CbCallback cb2 = lib.callCallbackWithCallback(cb); assertEquals("Callback reference should be reused", cb, cb2); } public void testDefaultCallbackExceptionHandler() { final RuntimeException ERROR = new RuntimeException(getName()); PrintStream ps = System.err; ByteArrayOutputStream s = new ByteArrayOutputStream(); System.setErr(new PrintStream(s)); try { TestLibrary.CbCallback cb = new TestLibrary.CbCallback() { public CbCallback callback(CbCallback arg) { throw ERROR; } }; TestLibrary.CbCallback cb2 = lib.callCallbackWithCallback(cb); String output = s.toString(); assertTrue("Default handler not called", output.length() > 0); } finally { System.setErr(ps); } } // Most Callbacks are wrapped in DefaultCallbackProxy, which catches their // exceptions. public void testCallbackExceptionHandler() { final RuntimeException ERROR = new RuntimeException(getName()); final Throwable CAUGHT[] = { null }; final Callback CALLBACK[] = { null }; UncaughtExceptionHandler old = Native.getCallbackExceptionHandler(); UncaughtExceptionHandler handler = new UncaughtExceptionHandler() { public void uncaughtException(Callback cb, Throwable e) { CALLBACK[0] = cb; CAUGHT[0] = e; } }; Native.setCallbackExceptionHandler(handler); try { TestLibrary.CbCallback cb = new TestLibrary.CbCallback() { public CbCallback callback(CbCallback arg) { throw ERROR; } }; TestLibrary.CbCallback cb2 = lib.callCallbackWithCallback(cb); assertNotNull("Exception handler not called", CALLBACK[0]); assertEquals("Wrong callback argument to handler", cb, CALLBACK[0]); assertEquals("Wrong exception passed to handler", ERROR, CAUGHT[0]); } finally { Native.setCallbackExceptionHandler(old); } } // CallbackProxy is called directly from native. public void testCallbackExceptionHandlerWithCallbackProxy() throws Throwable { final RuntimeException ERROR = new RuntimeException(getName()); final Throwable CAUGHT[] = { null }; final Callback CALLBACK[] = { null }; UncaughtExceptionHandler old = Native.getCallbackExceptionHandler(); UncaughtExceptionHandler handler = new UncaughtExceptionHandler() { public void uncaughtException(Callback cb, Throwable e) { CALLBACK[0] = cb; CAUGHT[0] = e; } }; Native.setCallbackExceptionHandler(handler); try { class TestProxy implements CallbackProxy, TestLibrary.CbCallback { public CbCallback callback(CbCallback arg) { throw new Error("Should never be called"); } public Object callback(Object[] args) { throw ERROR; } public Class[] getParameterTypes() { return new Class[] { CbCallback.class }; } public Class getReturnType() { return CbCallback.class; } }; TestLibrary.CbCallback cb = new TestProxy(); TestLibrary.CbCallback cb2 = lib.callCallbackWithCallback(cb); assertNotNull("Exception handler not called", CALLBACK[0]); assertEquals("Wrong callback argument to handler", cb, CALLBACK[0]); assertEquals("Wrong exception passed to handler", ERROR, CAUGHT[0]); } finally { Native.setCallbackExceptionHandler(old); } } public void testResetCallbackExceptionHandler() { Native.setCallbackExceptionHandler(null); assertNotNull("Should not be able to set callback EH null", Native.getCallbackExceptionHandler()); } public void testInvokeCallback() { TestLibrary.Int32CallbackX cb = lib.returnCallback(); assertNotNull("Callback should not be null", cb); assertEquals("Callback should be callable", 1, cb.callback(1)); TestLibrary.Int32CallbackX cb2 = new TestLibrary.Int32CallbackX() { public int callback(int arg) { return 0; } }; assertSame("Java callback should be looked up", cb2, lib.returnCallbackArgument(cb2)); assertSame("Existing native function wrapper should be reused", cb, lib.returnCallbackArgument(cb)); } public void testCallCallbackInStructure() { final boolean[] flag = {false}; final TestLibrary.CbStruct s = new TestLibrary.CbStruct(); s.cb = new Callback() { public void callback() { flag[0] = true; } }; lib.callCallbackInStruct(s); assertTrue("Callback not invoked", flag[0]); } public void testCustomCallbackMethodName() { final boolean[] called = {false}; TestLibrary.VoidCallbackCustom cb = new TestLibrary.VoidCallbackCustom() { public void customMethodName() { called[0] = true; } public String toString() { return "Some debug output"; } }; lib.callVoidCallback(cb); assertTrue("Callback with custom method name not called", called[0]); } public void testCustomCallbackVariedInheritance() { final boolean[] called = {false}; TestLibrary.VoidCallbackCustom cb = new TestLibrary.VoidCallbackCustomDerived(); lib.callVoidCallback(cb); } public static interface CallbackTestLibrary extends Library { final TypeMapper _MAPPER = new DefaultTypeMapper() { { // Convert java doubles into native integers and back TypeConverter converter = new TypeConverter() { public Object fromNative(Object value, FromNativeContext context) { return new Double(((Integer)value).intValue()); } public Class nativeType() { return Integer.class; } public Object toNative(Object value, ToNativeContext ctx) { return new Integer(((Double)value).intValue()); } }; addTypeConverter(double.class, converter); converter = new TypeConverter() { public Object fromNative(Object value, FromNativeContext context) { return new Float(((Long)value).intValue()); } public Class nativeType() { return Long.class; } public Object toNative(Object value, ToNativeContext ctx) { return new Long(((Float)value).longValue()); } }; addTypeConverter(float.class, converter); } }; final Map _OPTIONS = new HashMap() { { put(Library.OPTION_TYPE_MAPPER, _MAPPER); } }; interface DoubleCallback extends Callback { double callback(double arg, double arg2); } double callInt32Callback(DoubleCallback c, double arg, double arg2); interface FloatCallback extends Callback { float callback(float arg, float arg2); } float callInt64Callback(FloatCallback c, float arg, float arg2); } protected CallbackTestLibrary loadCallbackTestLibrary() { return (CallbackTestLibrary) Native.loadLibrary("testlib", CallbackTestLibrary.class, CallbackTestLibrary._OPTIONS); } /** This test is here instead of NativeTest in order to facilitate running the exact same test on a direct-mapped library without the tests interfering with one another due to persistent/cached state in library loading. */ public void testCallbackUsesTypeMapper() throws Exception { CallbackTestLibrary lib = loadCallbackTestLibrary(); final double[] ARGS = new double[2]; CallbackTestLibrary.DoubleCallback cb = new CallbackTestLibrary.DoubleCallback() { public double callback(double arg, double arg2) { ARGS[0] = arg; ARGS[1] = arg2; return arg + arg2; } }; assertEquals("Wrong type mapper for callback class", lib._MAPPER, Native.getTypeMapper(CallbackTestLibrary.DoubleCallback.class)); assertEquals("Wrong type mapper for callback object", lib._MAPPER, Native.getTypeMapper(cb.getClass())); double result = lib.callInt32Callback(cb, -1, -1); assertEquals("Wrong callback argument 1", -1, ARGS[0], 0); assertEquals("Wrong callback argument 2", -1, ARGS[1], 0); assertEquals("Incorrect result of callback invocation", -2, result, 0); } public void testCallbackUsesTypeMapperWithDifferentReturnTypeSize() throws Exception { CallbackTestLibrary lib = loadCallbackTestLibrary(); final float[] ARGS = new float[2]; CallbackTestLibrary.FloatCallback cb = new CallbackTestLibrary.FloatCallback() { public float callback(float arg, float arg2) { ARGS[0] = arg; ARGS[1] = arg2; return arg + arg2; } }; assertEquals("Wrong type mapper for callback class", lib._MAPPER, Native.getTypeMapper(CallbackTestLibrary.FloatCallback.class)); assertEquals("Wrong type mapper for callback object", lib._MAPPER, Native.getTypeMapper(cb.getClass())); float result = lib.callInt64Callback(cb, -1, -1); assertEquals("Wrong callback argument 1", -1, ARGS[0], 0); assertEquals("Wrong callback argument 2", -1, ARGS[1], 0); assertEquals("Incorrect result of callback invocation", -2, result, 0); } protected void callThreadedCallback(TestLibrary.VoidCallback cb, CallbackThreadInitializer cti, int repeat, int sleepms, int[] called) throws Exception { if (cti != null) { Native.setCallbackThreadInitializer(cb, cti); } lib.callVoidCallbackThreaded(cb, repeat, sleepms); long start = System.currentTimeMillis(); while (called[0] < repeat) { Thread.sleep(10); if (System.currentTimeMillis() - start > 5000) { fail("Timed out waiting for callback, invoked " + called[0] + " times so far"); } } } public void testCallbackThreadDefaults() throws Exception { final int[] called = {0}; final boolean[] daemon = {false}; final String[] name = { null }; final ThreadGroup[] group = { null }; final Thread[] t = { null }; ThreadGroup testGroup = new ThreadGroup(getName() + UNICODE); TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { public void callback() { Thread thread = Thread.currentThread(); daemon[0] = thread.isDaemon(); name[0] = thread.getName(); group[0] = thread.getThreadGroup(); t[0] = thread; ++called[0]; } }; callThreadedCallback(cb, null, 1, 100, called); assertFalse("Callback thread default should not be attached as daemon", daemon[0]); // thread name and group are not defined } public void testCustomizeCallbackThread() throws Exception { final int[] called = {0}; final boolean[] daemon = {false}; final String[] name = { null }; final ThreadGroup[] group = { null }; final Thread[] t = { null }; // Ensure unicode is properly handled final String tname = "NAME: " + getName() + UNICODE; final boolean[] alive = {false}; ThreadGroup testGroup = new ThreadGroup("Thread group for " + getName()); CallbackThreadInitializer init = new CallbackThreadInitializer(true, false, tname, testGroup); TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { public void callback() { Thread thread = Thread.currentThread(); daemon[0] = thread.isDaemon(); name[0] = thread.getName(); group[0] = thread.getThreadGroup(); t[0] = thread; if (thread.isAlive()) { // NOTE: older phoneME incorrectly reports thread "alive" status alive[0] = true; } if (++called[0] == 2) { // Allow the thread to exit Native.detach(true); } } }; callThreadedCallback(cb, init, 1, 5000, called); assertTrue("Callback thread not attached as daemon", daemon[0]); assertEquals("Callback thread name not applied", tname, name[0]); assertEquals("Callback thread group not applied", testGroup, group[0]); // NOTE: older phoneME incorrectly reports thread "alive" status if (!alive[0]) { throw new Error("VM incorrectly reports Thread.isAlive() == false within callback"); } assertTrue("Thread should still be alive", t[0].isAlive()); } // Detach preference is indicated by the initializer. Thread is attached // as daemon to allow VM to reclaim it. public void testCallbackThreadPersistence() throws Exception { final int[] called = {0}; final Set threads = new HashSet(); final int COUNT = 5; CallbackThreadInitializer init = new CallbackThreadInitializer(true, false) { public String getName(Callback cb) { return CallbacksTest.this.getName() + " thread " + called[0]; } }; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { public void callback() { threads.add(Thread.currentThread()); ++called[0]; } }; callThreadedCallback(cb, init, COUNT, 100, called); assertEquals("Multiple callbacks on a given native thread should use the same Thread mapping: " + threads, 1, threads.size()); } // Thread object is never GC'd on linux-amd64 and darwin-amd64 (w/openjdk7) public void testAttachedThreadCleanupOnExit() throws Exception { final Set threads = new HashSet(); final int[] called = { 0 }; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { public void callback() { threads.add(new WeakReference(Thread.currentThread())); if (++called[0] == 1) { Thread.currentThread().setName("Thread to be cleaned up"); } Native.detach(false); } }; CallbackThreadInitializer asDaemon = new CallbackThreadInitializer(true); callThreadedCallback(cb, asDaemon, 1, 0, called); while (threads.size() == 0) { Thread.sleep(10); } long start = System.currentTimeMillis(); WeakReference ref = (WeakReference)threads.iterator().next(); while (ref.get() != null) { System.gc(); Thread.sleep(10); if (System.currentTimeMillis() - start > 10000) { Thread t = (Thread)ref.get(); fail("Timed out waiting for attached thread to be detached on exit and disposed: " + t + " alive: " + t.isAlive() + " daemon " + t.isDaemon()); } } } // Callback indicates detach preference (instead of // CallbackThreadInitializer); thread is non-daemon (default), // but callback explicitly detaches it on final invocation. public void testCallbackIndicatedThreadDetach() throws Exception { final int[] called = {0}; final Set threads = new HashSet(); final int COUNT = 5; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { public void callback() { threads.add(Thread.currentThread()); // detach on final invocation int count = called[0] + 1; if (count == 1) { Native.detach(false); } else if (count == COUNT) { Native.detach(true); } called[0] = count; } }; callThreadedCallback(cb, null, COUNT, 100, called); assertEquals("Multiple callbacks in the same native thread should use the same Thread mapping: " + threads, 1, threads.size()); Thread thread = (Thread)threads.iterator().next(); long start = System.currentTimeMillis(); while (thread.isAlive()) { System.gc(); Thread.sleep(10); if (System.currentTimeMillis() - start > 5000) { PrintStream ps = System.err; ByteArrayOutputStream s = new ByteArrayOutputStream(); System.setErr(new PrintStream(s)); try { thread.dumpStack(); } finally { System.setErr(ps); } fail("Timed out waiting for callback thread " + thread + " to die: " + s); } } } public void testDLLCallback() throws Exception { if (!Platform.HAS_DLL_CALLBACKS) { return; } final boolean[] called = { false }; class TestCallback implements TestLibrary.VoidCallback, com.sun.jna.win32.DLLCallback { public void callback() { called[0] = true; } } TestCallback cb = new TestCallback(); lib.callVoidCallback(cb); assertTrue("Callback not called", called[0]); // Check module information Pointer fp = CallbackReference.getFunctionPointer(cb); NativeLibrary kernel32 = NativeLibrary.getInstance("kernel32", W32APIOptions.DEFAULT_OPTIONS); - Function f = kernel32.getFunction("GetModuleHandleEx"); + Function f = kernel32.getFunction("GetModuleHandleExW"); final int GET_MODULE_HANDLE_FROM_ADDRESS = 0x4; PointerByReference pref = new PointerByReference(); int result = f.invokeInt(new Object[] { new Integer(GET_MODULE_HANDLE_FROM_ADDRESS), fp, pref }); assertTrue("GetModuleHandleEx(fptr) failed: " + Native.getLastError(), result != 0); - f = kernel32.getFunction("GetModuleHandle"); + f = kernel32.getFunction("GetModuleHandleW"); Pointer handle = f.invokePointer(new Object[] { "jnidispatch" }); assertTrue("GetModuleHandle(\"jnidispatch\") failed: " + Native.getLastError(), result != 0); + assertNotNull("Could not object module handle for jnidispatch.dll", handle); assertEquals("Wrong module HANDLE for DLL function pointer", handle, pref.getValue()); // Check slot re-use Map refs = new WeakHashMap(callbackCache()); assertTrue("Callback not cached", refs.containsKey(cb)); CallbackReference ref = (CallbackReference)refs.get(cb); refs = callbackCache(); Pointer cbstruct = ref.cbstruct; Pointer first_fptr = cbstruct.getPointer(0); cb = null; System.gc(); for (int i = 0; i < 100 && (ref.get() != null || refs.containsValue(ref)); ++i) { Thread.sleep(10); // Give the GC a chance to run System.gc(); } assertNull("Callback not GC'd", ref.get()); assertFalse("Callback still in map", refs.containsValue(ref)); ref = null; System.gc(); for (int i = 0; i < 100 && (cbstruct.peer != 0 || refs.size() > 0); ++i) { // Flush weak hash map refs.size(); Thread.sleep(10); // Give the GC a chance to run System.gc(); } assertEquals("Callback trampoline not freed", 0, cbstruct.peer); // Next allocation should be at same place called[0] = false; cb = new TestCallback(); lib.callVoidCallback(cb); ref = (CallbackReference)refs.get(cb); cbstruct = ref.cbstruct; assertTrue("Callback not called", called[0]); assertEquals("Same (in-DLL) address should be re-used for DLL callbacks after callback is GCd", first_fptr, cbstruct.getPointer(0)); } public void testThrowOutOfMemoryWhenDLLCallbacksExhausted() throws Exception { if (!Platform.HAS_DLL_CALLBACKS) { return; } final boolean[] called = { false }; class TestCallback implements TestLibrary.VoidCallback, com.sun.jna.win32.DLLCallback { public void callback() { called[0] = true; } } // Exceeding allocations should result in OOM error try { for (int i=0;i <= TestCallback.DLL_FPTRS;i++) { lib.callVoidCallback(new TestCallback()); } fail("Expected out of memory error when all DLL callbacks used"); } catch(OutOfMemoryError e) { } } public static void main(java.lang.String[] argList) { junit.textui.TestRunner.run(CallbacksTest.class); } }
false
true
public void testDLLCallback() throws Exception { if (!Platform.HAS_DLL_CALLBACKS) { return; } final boolean[] called = { false }; class TestCallback implements TestLibrary.VoidCallback, com.sun.jna.win32.DLLCallback { public void callback() { called[0] = true; } } TestCallback cb = new TestCallback(); lib.callVoidCallback(cb); assertTrue("Callback not called", called[0]); // Check module information Pointer fp = CallbackReference.getFunctionPointer(cb); NativeLibrary kernel32 = NativeLibrary.getInstance("kernel32", W32APIOptions.DEFAULT_OPTIONS); Function f = kernel32.getFunction("GetModuleHandleEx"); final int GET_MODULE_HANDLE_FROM_ADDRESS = 0x4; PointerByReference pref = new PointerByReference(); int result = f.invokeInt(new Object[] { new Integer(GET_MODULE_HANDLE_FROM_ADDRESS), fp, pref }); assertTrue("GetModuleHandleEx(fptr) failed: " + Native.getLastError(), result != 0); f = kernel32.getFunction("GetModuleHandle"); Pointer handle = f.invokePointer(new Object[] { "jnidispatch" }); assertTrue("GetModuleHandle(\"jnidispatch\") failed: " + Native.getLastError(), result != 0); assertEquals("Wrong module HANDLE for DLL function pointer", handle, pref.getValue()); // Check slot re-use Map refs = new WeakHashMap(callbackCache()); assertTrue("Callback not cached", refs.containsKey(cb)); CallbackReference ref = (CallbackReference)refs.get(cb); refs = callbackCache(); Pointer cbstruct = ref.cbstruct; Pointer first_fptr = cbstruct.getPointer(0); cb = null; System.gc(); for (int i = 0; i < 100 && (ref.get() != null || refs.containsValue(ref)); ++i) { Thread.sleep(10); // Give the GC a chance to run System.gc(); } assertNull("Callback not GC'd", ref.get()); assertFalse("Callback still in map", refs.containsValue(ref)); ref = null; System.gc(); for (int i = 0; i < 100 && (cbstruct.peer != 0 || refs.size() > 0); ++i) { // Flush weak hash map refs.size(); Thread.sleep(10); // Give the GC a chance to run System.gc(); } assertEquals("Callback trampoline not freed", 0, cbstruct.peer); // Next allocation should be at same place called[0] = false; cb = new TestCallback(); lib.callVoidCallback(cb); ref = (CallbackReference)refs.get(cb); cbstruct = ref.cbstruct; assertTrue("Callback not called", called[0]); assertEquals("Same (in-DLL) address should be re-used for DLL callbacks after callback is GCd", first_fptr, cbstruct.getPointer(0)); }
public void testDLLCallback() throws Exception { if (!Platform.HAS_DLL_CALLBACKS) { return; } final boolean[] called = { false }; class TestCallback implements TestLibrary.VoidCallback, com.sun.jna.win32.DLLCallback { public void callback() { called[0] = true; } } TestCallback cb = new TestCallback(); lib.callVoidCallback(cb); assertTrue("Callback not called", called[0]); // Check module information Pointer fp = CallbackReference.getFunctionPointer(cb); NativeLibrary kernel32 = NativeLibrary.getInstance("kernel32", W32APIOptions.DEFAULT_OPTIONS); Function f = kernel32.getFunction("GetModuleHandleExW"); final int GET_MODULE_HANDLE_FROM_ADDRESS = 0x4; PointerByReference pref = new PointerByReference(); int result = f.invokeInt(new Object[] { new Integer(GET_MODULE_HANDLE_FROM_ADDRESS), fp, pref }); assertTrue("GetModuleHandleEx(fptr) failed: " + Native.getLastError(), result != 0); f = kernel32.getFunction("GetModuleHandleW"); Pointer handle = f.invokePointer(new Object[] { "jnidispatch" }); assertTrue("GetModuleHandle(\"jnidispatch\") failed: " + Native.getLastError(), result != 0); assertNotNull("Could not object module handle for jnidispatch.dll", handle); assertEquals("Wrong module HANDLE for DLL function pointer", handle, pref.getValue()); // Check slot re-use Map refs = new WeakHashMap(callbackCache()); assertTrue("Callback not cached", refs.containsKey(cb)); CallbackReference ref = (CallbackReference)refs.get(cb); refs = callbackCache(); Pointer cbstruct = ref.cbstruct; Pointer first_fptr = cbstruct.getPointer(0); cb = null; System.gc(); for (int i = 0; i < 100 && (ref.get() != null || refs.containsValue(ref)); ++i) { Thread.sleep(10); // Give the GC a chance to run System.gc(); } assertNull("Callback not GC'd", ref.get()); assertFalse("Callback still in map", refs.containsValue(ref)); ref = null; System.gc(); for (int i = 0; i < 100 && (cbstruct.peer != 0 || refs.size() > 0); ++i) { // Flush weak hash map refs.size(); Thread.sleep(10); // Give the GC a chance to run System.gc(); } assertEquals("Callback trampoline not freed", 0, cbstruct.peer); // Next allocation should be at same place called[0] = false; cb = new TestCallback(); lib.callVoidCallback(cb); ref = (CallbackReference)refs.get(cb); cbstruct = ref.cbstruct; assertTrue("Callback not called", called[0]); assertEquals("Same (in-DLL) address should be re-used for DLL callbacks after callback is GCd", first_fptr, cbstruct.getPointer(0)); }
diff --git a/examples/embedding/java/embedding/intermediate/ExampleStamp.java b/examples/embedding/java/embedding/intermediate/ExampleStamp.java index 42ea34137..860a75401 100644 --- a/examples/embedding/java/embedding/intermediate/ExampleStamp.java +++ b/examples/embedding/java/embedding/intermediate/ExampleStamp.java @@ -1,146 +1,146 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id$ */ package embedding.intermediate; import java.io.File; import java.io.IOException; import java.io.OutputStream; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.xml.sax.SAXException; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.FopFactory; import org.apache.fop.apps.MimeConstants; import org.apache.fop.render.intermediate.IFDocumentHandler; import org.apache.fop.render.intermediate.IFException; import org.apache.fop.render.intermediate.IFParser; import org.apache.fop.render.intermediate.IFUtil; import embedding.ExampleObj2XML; import embedding.model.ProjectTeam; /** * Example for the intermediate format that demonstrates the stamping of a document with some * kind of watermark. The resulting document is then rendered to a PDF file. */ public class ExampleStamp { // configure fopFactory as desired private FopFactory fopFactory = FopFactory.newInstance(); /** * Stamps an intermediate file and renders it to a PDF file. * @param iffile the intermediate file (area tree XML) * @param stampSheet the stylesheet that does the stamping * @param pdffile the target PDF file * @throws IOException In case of an I/O problem * @throws TransformerException In case of a XSL transformation problem * @throws SAXException In case of an XML-related problem * @throws IFException if there was an IF-related error while creating the output file */ public void stampToPDF(File iffile, File stampSheet, File pdffile) throws IOException, TransformerException, SAXException, IFException { // Setup output OutputStream out = new java.io.FileOutputStream(pdffile); out = new java.io.BufferedOutputStream(out); try { //user agent FOUserAgent userAgent = fopFactory.newFOUserAgent(); //Setup target handler String mime = MimeConstants.MIME_PDF + ";mode=painter"; IFDocumentHandler targetHandler = fopFactory.getRendererFactory().createDocumentHandler( userAgent, mime); //Setup fonts IFUtil.setupFonts(targetHandler); targetHandler.setResult(new StreamResult(pdffile)); IFParser parser = new IFParser(); Source src = new StreamSource(iffile); Source xslt = new StreamSource(stampSheet); //Setup Transformer for XSLT processing TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(xslt); //Send XSLT result to AreaTreeParser SAXResult res = new SAXResult(parser.getContentHandler(targetHandler, userAgent)); //Start XSLT transformation and area tree parsing transformer.transform(src, res); } finally { out.close(); } } /** * Main method. * @param args command-line arguments */ public static void main(String[] args) { try { System.out.println("FOP ExampleConcat (for the Intermediate Format)\n"); //Setup directories File baseDir = new File("."); File outDir = new File(baseDir, "out"); outDir.mkdirs(); //Setup output file File xsltfile = new File(baseDir, "xml/xslt/projectteam2fo.xsl"); - File iffile = new File(outDir, "team.at.xml"); + File iffile = new File(outDir, "team.if.xml"); File stampxsltfile = new File(baseDir, "xml/xslt/ifstamp.xsl"); File pdffile = new File(outDir, "ResultIFStamped.pdf"); System.out.println("Intermediate file : " + iffile.getCanonicalPath()); System.out.println("Stamp XSLT: " + stampxsltfile.getCanonicalPath()); System.out.println("PDF Output File: " + pdffile.getCanonicalPath()); System.out.println(); ProjectTeam team1 = ExampleObj2XML.createSampleProjectTeam(); //Create intermediate file ExampleConcat concatapp = new ExampleConcat(); concatapp.convertToIntermediate( team1.getSourceForProjectTeam(), new StreamSource(xsltfile), iffile); //Stamp document and produce a PDF from the intermediate format ExampleStamp app = new ExampleStamp(); app.stampToPDF(iffile, stampxsltfile, pdffile); System.out.println("Success!"); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } }
true
true
public static void main(String[] args) { try { System.out.println("FOP ExampleConcat (for the Intermediate Format)\n"); //Setup directories File baseDir = new File("."); File outDir = new File(baseDir, "out"); outDir.mkdirs(); //Setup output file File xsltfile = new File(baseDir, "xml/xslt/projectteam2fo.xsl"); File iffile = new File(outDir, "team.at.xml"); File stampxsltfile = new File(baseDir, "xml/xslt/ifstamp.xsl"); File pdffile = new File(outDir, "ResultIFStamped.pdf"); System.out.println("Intermediate file : " + iffile.getCanonicalPath()); System.out.println("Stamp XSLT: " + stampxsltfile.getCanonicalPath()); System.out.println("PDF Output File: " + pdffile.getCanonicalPath()); System.out.println(); ProjectTeam team1 = ExampleObj2XML.createSampleProjectTeam(); //Create intermediate file ExampleConcat concatapp = new ExampleConcat(); concatapp.convertToIntermediate( team1.getSourceForProjectTeam(), new StreamSource(xsltfile), iffile); //Stamp document and produce a PDF from the intermediate format ExampleStamp app = new ExampleStamp(); app.stampToPDF(iffile, stampxsltfile, pdffile); System.out.println("Success!"); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } }
public static void main(String[] args) { try { System.out.println("FOP ExampleConcat (for the Intermediate Format)\n"); //Setup directories File baseDir = new File("."); File outDir = new File(baseDir, "out"); outDir.mkdirs(); //Setup output file File xsltfile = new File(baseDir, "xml/xslt/projectteam2fo.xsl"); File iffile = new File(outDir, "team.if.xml"); File stampxsltfile = new File(baseDir, "xml/xslt/ifstamp.xsl"); File pdffile = new File(outDir, "ResultIFStamped.pdf"); System.out.println("Intermediate file : " + iffile.getCanonicalPath()); System.out.println("Stamp XSLT: " + stampxsltfile.getCanonicalPath()); System.out.println("PDF Output File: " + pdffile.getCanonicalPath()); System.out.println(); ProjectTeam team1 = ExampleObj2XML.createSampleProjectTeam(); //Create intermediate file ExampleConcat concatapp = new ExampleConcat(); concatapp.convertToIntermediate( team1.getSourceForProjectTeam(), new StreamSource(xsltfile), iffile); //Stamp document and produce a PDF from the intermediate format ExampleStamp app = new ExampleStamp(); app.stampToPDF(iffile, stampxsltfile, pdffile); System.out.println("Success!"); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java index 1fd9b7ba..dd4d0797 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java @@ -1,1533 +1,1536 @@ /* * Copyright (C) 2012 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.systemui.statusbar.phone; import com.android.internal.view.RotationPolicy; import com.android.internal.widget.LockPatternUtils; import com.android.systemui.R; import com.android.systemui.statusbar.phone.QuickSettingsModel.BluetoothState; import com.android.systemui.statusbar.phone.QuickSettingsModel.RSSIState; import com.android.systemui.statusbar.phone.QuickSettingsModel.State; import com.android.systemui.statusbar.phone.QuickSettingsModel.UserState; import com.android.systemui.statusbar.phone.QuickSettingsModel.WifiState; import com.android.systemui.statusbar.policy.BatteryController; import com.android.systemui.statusbar.policy.BluetoothController; import com.android.systemui.statusbar.policy.BrightnessController; import com.android.systemui.statusbar.policy.LocationController; import com.android.systemui.statusbar.policy.NetworkController; import com.android.systemui.statusbar.policy.ToggleSlider; import android.app.ActivityManagerNative; import android.app.AlertDialog; import android.app.Dialog; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.UserInfo; import android.content.res.Resources; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LevelListDrawable; import android.hardware.display.DisplayManager; import android.hardware.display.WifiDisplayStatus; import android.location.LocationManager; import android.nfc.NfcAdapter; import android.net.ConnectivityManager; import android.net.wifi.WifiManager; import android.os.AsyncTask; import android.os.Handler; import android.os.RemoteException; import android.os.UserHandle; import android.os.UserManager; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Profile; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.telephony.TelephonyManager; import android.util.Log; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.WindowManagerGlobal; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.internal.telephony.PhoneConstants; import com.android.systemui.aokp.AokpTarget; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; /** * */ class QuickSettings { private static final String TAG = "QuickSettings"; public static final boolean SHOW_IME_TILE = false; private static final String TOGGLE_PIPE = "|"; private static final int USER_TILE = 0; private static final int BRIGHTNESS_TILE = 1; private static final int SETTINGS_TILE = 2; private static final int WIFI_TILE = 3; private static final int SIGNAL_TILE = 4; private static final int ROTATE_TILE = 5; private static final int CLOCK_TILE = 6; private static final int GPS_TILE = 7; private static final int IME_TILE = 8; private static final int BATTERY_TILE = 9; private static final int AIRPLANE_TILE = 10; private static final int BLUETOOTH_TILE = 11; private static final int SWAGGER_TILE = 12; private static final int VIBRATE_TILE = 13; private static final int SILENT_TILE = 14; private static final int FCHARGE_TILE = 15; private static final int SYNC_TILE = 16; private static final int NFC_TILE = 17; private static final int TORCH_TILE = 18; private static final int WIFI_TETHER_TILE = 19; private static final int USB_TETHER_TILE = 20; private static final int TWOG_TILE = 21; private static final int LTE_TILE = 22; // private static final int BT_TETHER_TILE = 23; public static final String USER_TOGGLE = "USER"; public static final String BRIGHTNESS_TOGGLE = "BRIGHTNESS"; public static final String SETTINGS_TOGGLE = "SETTINGS"; public static final String WIFI_TOGGLE = "WIFI"; public static final String SIGNAL_TOGGLE = "SIGNAL"; public static final String ROTATE_TOGGLE = "ROTATE"; public static final String CLOCK_TOGGLE = "CLOCK"; public static final String GPS_TOGGLE = "GPS"; public static final String IME_TOGGLE = "IME"; public static final String BATTERY_TOGGLE = "BATTERY"; public static final String AIRPLANE_TOGGLE = "AIRPLANE_MODE"; public static final String BLUETOOTH_TOGGLE = "BLUETOOTH"; public static final String SWAGGER_TOGGLE = "SWAGGER"; public static final String VIBRATE_TOGGLE = "VIBRATE"; public static final String SILENT_TOGGLE = "SILENT"; public static final String FCHARGE_TOGGLE = "FCHARGE"; public static final String SYNC_TOGGLE = "SYNC"; public static final String NFC_TOGGLE = "NFC"; public static final String TORCH_TOGGLE = "TORCH"; public static final String WIFI_TETHER_TOGGLE = "WIFITETHER"; // public static final String BT_TETHER_TOGGLE = "BTTETHER"; public static final String USB_TETHER_TOGGLE = "USBTETHER"; public static final String TWOG_TOGGLE = "2G"; public static final String LTE_TOGGLE = "LTE"; private static final String DEFAULT_TOGGLES = "default"; public static final String FAST_CHARGE_DIR = "/sys/kernel/fast_charge"; public static final String FAST_CHARGE_FILE = "force_fast_charge"; private int mWifiApState = WifiManager.WIFI_AP_STATE_DISABLED; private int mDataState = -1; private boolean usbTethered; // at some point we need to move these to string for translation.... dont let me forget public String strGPSoff = "GPS Off"; public String strGPSon = "GPS On"; public String strDataoff = "Mobile Data Off"; public String strDataon = "Mobile Data On"; private Context mContext; private PanelBar mBar; private QuickSettingsModel mModel; private ViewGroup mContainerView; private DisplayManager mDisplayManager; private WifiDisplayStatus mWifiDisplayStatus; private WifiManager wifiManager; private ConnectivityManager connManager; private LocationManager locationManager; private PhoneStatusBar mStatusBarService; private BluetoothState mBluetoothState; private TelephonyManager tm; private ConnectivityManager mConnService; private AokpTarget mAokpTarget; private BrightnessController mBrightnessController; private BluetoothController mBluetoothController; private Dialog mBrightnessDialog; private int mBrightnessDialogShortTimeout; private int mBrightnessDialogLongTimeout; private AsyncTask<Void, Void, Pair<String, Drawable>> mUserInfoTask; private LevelListDrawable mBatteryLevels; private LevelListDrawable mChargingBatteryLevels; boolean mTilesSetUp = false; private Handler mHandler; private ArrayList<String> toggles; private String userToggles = null; private HashMap<String, Integer> toggleMap; private HashMap<String, Integer> getToggleMap() { if (toggleMap == null) { toggleMap = new HashMap<String, Integer>(); toggleMap.put(USER_TOGGLE, USER_TILE); toggleMap.put(BRIGHTNESS_TOGGLE, BRIGHTNESS_TILE); toggleMap.put(SETTINGS_TOGGLE, SETTINGS_TILE); toggleMap.put(WIFI_TOGGLE, WIFI_TILE); toggleMap.put(SIGNAL_TOGGLE, SIGNAL_TILE); toggleMap.put(ROTATE_TOGGLE, ROTATE_TILE); toggleMap.put(CLOCK_TOGGLE, CLOCK_TILE); toggleMap.put(GPS_TOGGLE, GPS_TILE); toggleMap.put(IME_TOGGLE, IME_TILE); toggleMap.put(BATTERY_TOGGLE, BATTERY_TILE); toggleMap.put(AIRPLANE_TOGGLE, AIRPLANE_TILE); toggleMap.put(BLUETOOTH_TOGGLE, BLUETOOTH_TILE); toggleMap.put(VIBRATE_TOGGLE, VIBRATE_TILE); toggleMap.put(SILENT_TOGGLE, SILENT_TILE); toggleMap.put(FCHARGE_TOGGLE, FCHARGE_TILE); toggleMap.put(SYNC_TOGGLE, SYNC_TILE); toggleMap.put(NFC_TOGGLE, NFC_TILE); toggleMap.put(TORCH_TOGGLE, TORCH_TILE); toggleMap.put(WIFI_TETHER_TOGGLE, WIFI_TETHER_TILE); toggleMap.put(USB_TETHER_TOGGLE, USB_TETHER_TILE); toggleMap.put(TWOG_TOGGLE, TWOG_TILE); toggleMap.put(LTE_TOGGLE, LTE_TILE); //toggleMap.put(BT_TETHER_TOGGLE, BT_TETHER_TILE); } return toggleMap; } // The set of QuickSettingsTiles that have dynamic spans (and need to be // updated on // configuration change) private final ArrayList<QuickSettingsTileView> mDynamicSpannedTiles = new ArrayList<QuickSettingsTileView>(); private final RotationPolicy.RotationPolicyListener mRotationPolicyListener = new RotationPolicy.RotationPolicyListener() { @Override public void onChange() { mModel.onRotationLockChanged(); } }; public QuickSettings(Context context, QuickSettingsContainerView container) { mDisplayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE); mContext = context; mContainerView = container; mModel = new QuickSettingsModel(context); mWifiDisplayStatus = new WifiDisplayStatus(); wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); connManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); mBluetoothState = new QuickSettingsModel.BluetoothState(); mHandler = new Handler(); mAokpTarget = new AokpTarget(mContext); Resources r = mContext.getResources(); mBatteryLevels = (LevelListDrawable) r.getDrawable(R.drawable.qs_sys_battery); mChargingBatteryLevels = (LevelListDrawable) r.getDrawable(R.drawable.qs_sys_battery_charging); mBrightnessDialogLongTimeout = r.getInteger(R.integer.quick_settings_brightness_dialog_long_timeout); mBrightnessDialogShortTimeout = r.getInteger(R.integer.quick_settings_brightness_dialog_short_timeout); IntentFilter filter = new IntentFilter(); filter.addAction(DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED); filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); filter.addAction(Intent.ACTION_USER_SWITCHED); mContext.registerReceiver(mReceiver, filter); IntentFilter profileFilter = new IntentFilter(); profileFilter.addAction(ContactsContract.Intents.ACTION_PROFILE_CHANGED); profileFilter.addAction(Intent.ACTION_USER_INFO_CHANGED); mContext.registerReceiverAsUser(mProfileReceiver, UserHandle.ALL, profileFilter, null, null); new SettingsObserver(new Handler()).observe(); } void setBar(PanelBar bar) { mBar = bar; } public void setService(PhoneStatusBar phoneStatusBar) { mStatusBarService = phoneStatusBar; } public PhoneStatusBar getService() { return mStatusBarService; } public void setImeWindowStatus(boolean visible) { mModel.onImeWindowStatusChanged(visible); } void setup(NetworkController networkController, BluetoothController bluetoothController, BatteryController batteryController, LocationController locationController) { mBluetoothController = bluetoothController; setupQuickSettings(); updateWifiDisplayStatus(); updateResources(); if (getCustomUserTiles().contains(SIGNAL_TOGGLE)) networkController.addNetworkSignalChangedCallback(mModel); if (getCustomUserTiles().contains(BLUETOOTH_TOGGLE)) bluetoothController.addStateChangedCallback(mModel); if (getCustomUserTiles().contains(BATTERY_TOGGLE)) batteryController.addStateChangedCallback(mModel); if (getCustomUserTiles().contains(GPS_TOGGLE)) locationController.addStateChangedCallback(mModel); if (getCustomUserTiles().contains(ROTATE_TOGGLE)) RotationPolicy.registerRotationPolicyListener(mContext, mRotationPolicyListener, UserHandle.USER_ALL); } private void queryForUserInformation() { Context currentUserContext = null; UserInfo userInfo = null; try { userInfo = ActivityManagerNative.getDefault().getCurrentUser(); currentUserContext = mContext.createPackageContextAsUser("android", 0, new UserHandle(userInfo.id)); } catch (NameNotFoundException e) { Log.e(TAG, "Couldn't create user context", e); throw new RuntimeException(e); } catch (RemoteException e) { Log.e(TAG, "Couldn't get user info", e); } final int userId = userInfo.id; final String userName = userInfo.name; final Context context = currentUserContext; mUserInfoTask = new AsyncTask<Void, Void, Pair<String, Drawable>>() { @Override protected Pair<String, Drawable> doInBackground(Void... params) { final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE); // Fall back to the UserManager nickname if we can't read the // name from the local // profile below. String name = userName; Drawable avatar = null; Bitmap rawAvatar = um.getUserIcon(userId); if (rawAvatar != null) { avatar = new BitmapDrawable(mContext.getResources(), rawAvatar); } else { avatar = mContext.getResources().getDrawable(R.drawable.ic_qs_default_user); } // If it's a single-user device, get the profile name, since the // nickname is not // usually valid if (um.getUsers().size() <= 1) { // Try and read the display name from the local profile final Cursor cursor = context.getContentResolver().query( Profile.CONTENT_URI, new String[] { Phone._ID, Phone.DISPLAY_NAME }, null, null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { name = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME)); } } finally { cursor.close(); } } } return new Pair<String, Drawable>(name, avatar); } @Override protected void onPostExecute(Pair<String, Drawable> result) { super.onPostExecute(result); mModel.setUserTileInfo(result.first, result.second); mUserInfoTask = null; } }; mUserInfoTask.execute(); } private void setupQuickSettings() { // Setup the tiles that we are going to be showing (including the // temporary ones) LayoutInflater inflater = LayoutInflater.from(mContext); addUserTiles(mContainerView, inflater); addTemporaryTiles(mContainerView, inflater); queryForUserInformation(); mTilesSetUp = true; } private void startSettingsActivity(String action) { Intent intent = new Intent(action); startSettingsActivity(intent); } private void startSettingsActivity(Intent intent) { startSettingsActivity(intent, true); } private void startSettingsActivity(Intent intent, boolean onlyProvisioned) { if (onlyProvisioned && !getService().isDeviceProvisioned()) return; try { // Dismiss the lock screen when Settings starts. ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity(); } catch (RemoteException e) { } intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT)); getService().animateCollapsePanels(); } private QuickSettingsTileView getTile(int tile, ViewGroup parent, LayoutInflater inflater) { QuickSettingsTileView quick = null; switch (tile) { case USER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_user, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBar.collapseAllPanels(true); final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE); if (um.getUsers(true).size() > 1) { try { WindowManagerGlobal.getWindowManagerService().lockNow( LockPatternUtils.USER_SWITCH_LOCK_OPTIONS); } catch (RemoteException e) { Log.e(TAG, "Couldn't show user switcher", e); } } else { Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent( mContext, v, ContactsContract.Profile.CONTENT_URI, ContactsContract.QuickContact.MODE_LARGE, null); mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT)); } } }); mModel.addUserTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { UserState us = (UserState) state; ImageView iv = (ImageView) view.findViewById(R.id.user_imageview); TextView tv = (TextView) view.findViewById(R.id.user_textview); tv.setText(state.label); iv.setImageDrawable(us.avatar); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_user, state.label)); } }); mDynamicSpannedTiles.add(quick); break; case CLOCK_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_time, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("android.intent.action.MAIN"); intent.setComponent(ComponentName.unflattenFromString("com.android.deskclock.AlarmProvider")); intent.addCategory("android.intent.category.LAUNCHER"); startSettingsActivity(intent); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(Intent.ACTION_QUICK_CLOCK); return true; } }); mModel.addTimeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State alarmState) { } }); mDynamicSpannedTiles.add(quick); break; case SIGNAL_TILE: if (mModel.deviceSupportsTelephony()) { // Mobile Network state quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_rssi, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { connManager.setMobileDataEnabled(connManager.getMobileDataEnabled() ? false : true); String strData = connManager.getMobileDataEnabled() ? strDataoff : strDataon; Toast.makeText(mContext, strData, Toast.LENGTH_SHORT).show(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Intent intent = new Intent(); intent.setComponent(new ComponentName( "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity")); startSettingsActivity(intent); return true; } }); mModel.addRSSITile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { RSSIState rssiState = (RSSIState) state; ImageView iv = (ImageView) view.findViewById(R.id.rssi_image); ImageView iov = (ImageView) view.findViewById(R.id.rssi_overlay_image); TextView tv = (TextView) view.findViewById(R.id.rssi_textview); iv.setImageResource(rssiState.signalIconId); if (rssiState.dataTypeIconId > 0) { iov.setImageResource(rssiState.dataTypeIconId); } else { iov.setImageDrawable(null); } tv.setText(state.label); view.setContentDescription(mContext.getResources().getString( R.string.accessibility_quick_settings_mobile, rssiState.signalContentDescription, rssiState.dataContentDescription, state.label)); } }); } break; case BRIGHTNESS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_brightness, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBar.collapseAllPanels(true); showBrightnessDialog(); } }); mModel.addBrightnessTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.brightness_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); dismissBrightnessDialog(mBrightnessDialogShortTimeout); } }); mDynamicSpannedTiles.add(quick); break; case SETTINGS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_settings, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SETTINGS); } }); mModel.addSettingsTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.settings_tileview); tv.setText(state.label); } }); mDynamicSpannedTiles.add(quick); break; case WIFI_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_wifi, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { wifiManager.setWifiEnabled(wifiManager.isWifiEnabled() ? false : true); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIFI_SETTINGS); return true; } }); mModel.addWifiTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { WifiState wifiState = (WifiState) state; TextView tv = (TextView) view.findViewById(R.id.wifi_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, wifiState.iconId, 0, 0); tv.setText(wifiState.label); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_wifi, wifiState.signalContentDescription, (wifiState.connected) ? wifiState.label : "")); } }); break; case TWOG_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_twog, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE); } catch (SettingNotFoundException e) { e.printStackTrace(); } if (mDataState == PhoneConstants.NT_MODE_GSM_ONLY) { tm.toggle2G(false); } else { tm.toggle2G(true); } mModel.refresh2gTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.add2gTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.twog_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case LTE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_lte, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE); } catch (SettingNotFoundException e) { e.printStackTrace(); } if (mDataState == PhoneConstants.NT_MODE_LTE_CDMA_EVDO || mDataState == PhoneConstants.NT_MODE_GLOBAL) { tm.toggleLTE(false); } else { tm.toggleLTE(true); } mModel.refreshLTETile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addLTETile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.lte_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case VIBRATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_vibrate, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_VIB); mModel.refreshVibrateTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addVibrateTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.vibrate_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case SILENT_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_silent, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT); mModel.refreshSilentTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addSilentTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.silent_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case TORCH_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_torch, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_TORCH); mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // maybe something here? return true; } }); mModel.addTorchTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.torch_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case FCHARGE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_fcharge, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFastCharge(isFastChargeOn() ? false : true); mModel.refreshFChargeTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // What do we put here? return true; } }); mModel.addFChargeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.fcharge_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case WIFI_TETHER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_wifi_tether, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mWifiApState = wifiManager.getWifiApState(); if (mWifiApState == WifiManager.WIFI_AP_STATE_DISABLED || mWifiApState == WifiManager.WIFI_AP_STATE_DISABLING) { changeWifiState(true); } else { changeWifiState(false); } mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addWifiTetherTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.wifi_tether_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case USB_TETHER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_usb_tether, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = updateUsbState() ? false : true; if (connManager.setUsbTethering(enabled) == ConnectivityManager.TETHER_ERROR_NO_ERROR) { mHandler.postDelayed(delayedRefresh, 1000); } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addUSBTetherTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.usb_tether_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case SYNC_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_sync, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = ContentResolver.getMasterSyncAutomatically(); ContentResolver.setMasterSyncAutomatically(enabled ? false : true); mModel.refreshSyncTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SYNC_SETTINGS); return true; } }); mModel.addSyncTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.sync_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case NFC_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_nfc, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext); - boolean enabled = mNfcAdapter.isEnabled(); + boolean enabled = false; + if (mNfcAdapter != null) { + enabled = mNfcAdapter.isEnabled(); + } if (enabled) { mNfcAdapter.disable(); } else { mNfcAdapter.enable(); } mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addNFCTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.nfc_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case ROTATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_rotation_lock, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean locked = RotationPolicy.isRotationLocked(mContext); RotationPolicy.setRotationLock(mContext, !locked); } }); mModel.addRotationLockTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.rotation_lock_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case BATTERY_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_battery, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSettingsActivity(Intent.ACTION_POWER_USAGE_SUMMARY); } }); mModel.addBatteryTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { QuickSettingsModel.BatteryState batteryState = (QuickSettingsModel.BatteryState) state; TextView tv = (TextView) view.findViewById(R.id.battery_textview); ImageView iv = (ImageView) view.findViewById(R.id.battery_image); Drawable d = batteryState.pluggedIn ? mChargingBatteryLevels : mBatteryLevels; String t; if (batteryState.batteryLevel == 100) { t = mContext.getString(R.string.quick_settings_battery_charged_label); } else { t = batteryState.pluggedIn ? mContext.getString(R.string.quick_settings_battery_charging_label, batteryState.batteryLevel) : mContext.getString(R.string.status_bar_settings_battery_meter_format, batteryState.batteryLevel); } iv.setImageDrawable(d); iv.setImageLevel(batteryState.batteryLevel); tv.setText(t); view.setContentDescription( mContext.getString(R.string.accessibility_quick_settings_battery, t)); } }); break; case AIRPLANE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_airplane, inflater); mModel.addAirplaneModeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.airplane_mode_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); String airplaneState = mContext.getString( (state.enabled) ? R.string.accessibility_desc_on : R.string.accessibility_desc_off); view.setContentDescription( mContext.getString(R.string.accessibility_quick_settings_airplane, airplaneState)); tv.setText(state.label); } }); break; case BLUETOOTH_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_bluetooth, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter.isEnabled()) { adapter.disable(); } else { adapter.enable(); } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS); return true; } }); mModel.addBluetoothTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { BluetoothState bluetoothState = (BluetoothState) state; TextView tv = (TextView) view.findViewById(R.id.bluetooth_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); Resources r = mContext.getResources(); String label = state.label; /* * //TODO: Show connected bluetooth device label * Set<BluetoothDevice> btDevices = * mBluetoothController.getBondedBluetoothDevices(); if * (btDevices.size() == 1) { // Show the name of the * bluetooth device you are connected to label = * btDevices.iterator().next().getName(); } else if * (btDevices.size() > 1) { // Show a generic label * about the number of bluetooth devices label = * r.getString(R.string * .quick_settings_bluetooth_multiple_devices_label, * btDevices.size()); } */ view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_bluetooth, bluetoothState.stateContentDescription)); tv.setText(label); } }); break; case GPS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_location, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(), LocationManager.GPS_PROVIDER, gpsEnabled ? false : true); TextView tv = (TextView) v.findViewById(R.id.location_textview); tv.setText(gpsEnabled ? strGPSoff : strGPSon); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); return true; } }); mModel.addLocationTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); TextView tv = (TextView) view.findViewById(R.id.location_textview); String newString = state.label; if ((newString == null) || (newString.equals(""))) { tv.setText(gpsEnabled ? strGPSon : strGPSoff); } else { tv.setText(state.label); } } }); break; case IME_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_ime, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mBar.collapseAllPanels(true); Intent intent = new Intent(Settings.ACTION_SHOW_INPUT_METHOD_PICKER); PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); pendingIntent.send(); } catch (Exception e) { } } }); mModel.addImeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.ime_textview); if (state.label != null) { tv.setText(state.label); } } }); break; } return quick; } private ArrayList<String> getCustomUserTiles() { ArrayList<String> tiles = new ArrayList<String>(); if (userToggles == null) return getDefaultTiles(); String[] splitter = userToggles.split("\\" + TOGGLE_PIPE); for (String toggle : splitter) { tiles.add(toggle); } return tiles; } private ArrayList<String> getDefaultTiles() { ArrayList<String> tiles = new ArrayList<String>(); tiles.add(USER_TOGGLE); tiles.add(BRIGHTNESS_TOGGLE); tiles.add(SETTINGS_TOGGLE); tiles.add(WIFI_TOGGLE); if (mModel.deviceSupportsTelephony()) { tiles.add(SIGNAL_TOGGLE); } if (mContext.getResources().getBoolean(R.bool.quick_settings_show_rotation_lock)) { tiles.add(ROTATE_TOGGLE); } tiles.add(BATTERY_TOGGLE); tiles.add(AIRPLANE_TOGGLE); if (mModel.deviceSupportsBluetooth()) { tiles.add(BLUETOOTH_TOGGLE); } return tiles; } private void addUserTiles(ViewGroup parent, LayoutInflater inflater) { if (parent.getChildCount() > 0) parent.removeAllViews(); toggles = getCustomUserTiles(); if (mDynamicSpannedTiles.size() > 0) mDynamicSpannedTiles.clear(); if (!toggles.get(0).equals("")) { for (String toggle : toggles) { parent.addView(getTile(getToggleMap().get(toggle), parent, inflater)); } } } private void addTemporaryTiles(final ViewGroup parent, final LayoutInflater inflater) { // Alarm tile QuickSettingsTileView alarmTile = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); alarmTile.setContent(R.layout.quick_settings_tile_alarm, inflater); alarmTile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO: Jump into the alarm application Intent intent = new Intent(); intent.setComponent(new ComponentName( "com.android.deskclock", "com.android.deskclock.AlarmClock")); startSettingsActivity(intent); } }); mModel.addAlarmTile(alarmTile, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State alarmState) { TextView tv = (TextView) view.findViewById(R.id.alarm_textview); tv.setText(alarmState.label); view.setVisibility(alarmState.enabled ? View.VISIBLE : View.GONE); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_alarm, alarmState.label)); } }); parent.addView(alarmTile); // Wifi Display QuickSettingsTileView wifiDisplayTile = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); wifiDisplayTile.setContent(R.layout.quick_settings_tile_wifi_display, inflater); wifiDisplayTile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIFI_DISPLAY_SETTINGS); } }); mModel.addWifiDisplayTile(wifiDisplayTile, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.wifi_display_textview); tv.setText(state.label); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); view.setVisibility(state.enabled ? View.VISIBLE : View.GONE); } }); parent.addView(wifiDisplayTile); // Bug reports QuickSettingsTileView bugreportTile = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); bugreportTile.setContent(R.layout.quick_settings_tile_bugreport, inflater); bugreportTile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBar.collapseAllPanels(true); showBugreportDialog(); } }); mModel.addBugreportTile(bugreportTile, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { view.setVisibility(state.enabled ? View.VISIBLE : View.GONE); } }); parent.addView(bugreportTile); /* * QuickSettingsTileView mediaTile = (QuickSettingsTileView) * inflater.inflate(R.layout.quick_settings_tile, parent, false); * mediaTile.setContent(R.layout.quick_settings_tile_media, inflater); * parent.addView(mediaTile); QuickSettingsTileView imeTile = * (QuickSettingsTileView) * inflater.inflate(R.layout.quick_settings_tile, parent, false); * imeTile.setContent(R.layout.quick_settings_tile_ime, inflater); * imeTile.setOnClickListener(new View.OnClickListener() { * @Override public void onClick(View v) { parent.removeViewAt(0); } }); * parent.addView(imeTile); */ } void updateResources() { Resources r = mContext.getResources(); // Update the model mModel.updateResources(getCustomUserTiles()); // Update the User, Time, and Settings tiles spans, and reset everything // else int span = r.getInteger(R.integer.quick_settings_user_time_settings_tile_span); for (QuickSettingsTileView v : mDynamicSpannedTiles) { v.setColumnSpan(span); } ((QuickSettingsContainerView) mContainerView).updateResources(); mContainerView.requestLayout(); // Reset the dialog boolean isBrightnessDialogVisible = false; if (mBrightnessDialog != null) { removeAllBrightnessDialogCallbacks(); isBrightnessDialogVisible = mBrightnessDialog.isShowing(); mBrightnessDialog.dismiss(); } mBrightnessDialog = null; if (isBrightnessDialogVisible) { showBrightnessDialog(); } } private void removeAllBrightnessDialogCallbacks() { mHandler.removeCallbacks(mDismissBrightnessDialogRunnable); } private Runnable mDismissBrightnessDialogRunnable = new Runnable() { public void run() { if (mBrightnessDialog != null && mBrightnessDialog.isShowing()) { mBrightnessDialog.dismiss(); } removeAllBrightnessDialogCallbacks(); }; }; private void showBrightnessDialog() { if (mBrightnessDialog == null) { mBrightnessDialog = new Dialog(mContext); mBrightnessDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mBrightnessDialog.setContentView(R.layout.quick_settings_brightness_dialog); mBrightnessDialog.setCanceledOnTouchOutside(true); mBrightnessController = new BrightnessController(mContext, (ImageView) mBrightnessDialog.findViewById(R.id.brightness_icon), (ToggleSlider) mBrightnessDialog.findViewById(R.id.brightness_slider)); mBrightnessController.addStateChangedCallback(mModel); mBrightnessDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { mBrightnessController = null; } }); mBrightnessDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); mBrightnessDialog.getWindow().getAttributes().privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS; mBrightnessDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); } if (!mBrightnessDialog.isShowing()) { try { WindowManagerGlobal.getWindowManagerService().dismissKeyguard(); } catch (RemoteException e) { } mBrightnessDialog.show(); dismissBrightnessDialog(mBrightnessDialogLongTimeout); } } private void dismissBrightnessDialog(int timeout) { removeAllBrightnessDialogCallbacks(); if (mBrightnessDialog != null) { mHandler.postDelayed(mDismissBrightnessDialogRunnable, timeout); } } private void showBugreportDialog() { final AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setPositiveButton(com.android.internal.R.string.report, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { // Add a little delay before executing, to give the // dialog a chance to go away before it takes a // screenshot. mHandler.postDelayed(new Runnable() { @Override public void run() { try { ActivityManagerNative.getDefault() .requestBugReport(); } catch (RemoteException e) { } } }, 500); } } }); builder.setMessage(com.android.internal.R.string.bugreport_message); builder.setTitle(com.android.internal.R.string.bugreport_title); builder.setCancelable(true); final Dialog dialog = builder.create(); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); try { WindowManagerGlobal.getWindowManagerService().dismissKeyguard(); } catch (RemoteException e) { } dialog.show(); } private void updateWifiDisplayStatus() { mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus(); applyWifiDisplayStatus(); } private void applyWifiDisplayStatus() { mModel.onWifiDisplayStateChanged(mWifiDisplayStatus); } private void applyBluetoothStatus() { mModel.onBluetoothStateChange(mBluetoothState); } void reloadUserInfo() { if (mUserInfoTask != null) { mUserInfoTask.cancel(false); mUserInfoTask = null; } if (mTilesSetUp) { queryForUserInformation(); } } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED.equals(action)) { WifiDisplayStatus status = (WifiDisplayStatus) intent.getParcelableExtra( DisplayManager.EXTRA_WIFI_DISPLAY_STATUS); mWifiDisplayStatus = status; applyWifiDisplayStatus(); } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) { int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); mBluetoothState.enabled = (state == BluetoothAdapter.STATE_ON); applyBluetoothStatus(); } else if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action)) { int status = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, BluetoothAdapter.STATE_DISCONNECTED); mBluetoothState.connected = (status == BluetoothAdapter.STATE_CONNECTED); applyBluetoothStatus(); } else if (Intent.ACTION_USER_SWITCHED.equals(action)) { reloadUserInfo(); } } }; private final BroadcastReceiver mProfileReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (ContactsContract.Intents.ACTION_PROFILE_CHANGED.equals(action) || Intent.ACTION_USER_INFO_CHANGED.equals(action)) { try { final int userId = ActivityManagerNative.getDefault().getCurrentUser().id; if (getSendingUserId() == userId) { reloadUserInfo(); } } catch (RemoteException e) { Log.e(TAG, "Couldn't get current user id for profile change", e); } } } }; public boolean isFastChargeOn() { try { File fastcharge = new File(FAST_CHARGE_DIR, FAST_CHARGE_FILE); FileReader reader = new FileReader(fastcharge); BufferedReader breader = new BufferedReader(reader); return (breader.readLine().equals("1")); } catch (IOException e) { Log.e("FChargeToggle", "Couldn't read fast_charge file"); return false; } } public void updateFastCharge(boolean on) { try { File fastcharge = new File(FAST_CHARGE_DIR, FAST_CHARGE_FILE); FileWriter fwriter = new FileWriter(fastcharge); BufferedWriter bwriter = new BufferedWriter(fwriter); bwriter.write(on ? "1" : "0"); bwriter.close(); } catch (IOException e) { Log.e("FChargeToggle", "Couldn't write fast_charge file"); } } private void changeWifiState(final boolean desiredState) { if (wifiManager == null) { Log.d("WifiButton", "No wifiManager."); return; } AsyncTask.execute(new Runnable() { public void run() { int wifiState = wifiManager.getWifiState(); if (desiredState && ((wifiState == WifiManager.WIFI_STATE_ENABLING) || (wifiState == WifiManager.WIFI_STATE_ENABLED))) { wifiManager.setWifiEnabled(false); } wifiManager.setWifiApEnabled(null, desiredState); return; } }); } public boolean updateUsbState() { String[] mUsbRegexs = connManager.getTetherableUsbRegexs(); String[] tethered = connManager.getTetheredIfaces(); usbTethered = false; for (String s : tethered) { for (String regex : mUsbRegexs) { if (s.matches(regex)) { return true; } else { return false; } } } return false; } final Runnable delayedRefresh = new Runnable () { public void run() { mModel.refreshWifiTetherTile(); mModel.refreshUSBTetherTile(); mModel.refreshNFCTile(); mModel.refreshTorchTile(); } }; private void updateSettings() { ContentResolver resolver = mContext.getContentResolver(); userToggles = Settings.System.getString(resolver, Settings.System.QUICK_TOGGLES); setupQuickSettings(); updateWifiDisplayStatus(); updateResources(); } class SettingsObserver extends ContentObserver { SettingsObserver(Handler handler) { super(handler); } void observe() { ContentResolver resolver = mContext.getContentResolver(); resolver.registerContentObserver(Settings.System .getUriFor(Settings.System.QUICK_TOGGLES), false, this); updateSettings(); } @Override public void onChange(boolean selfChange) { updateSettings(); } } }
true
true
private QuickSettingsTileView getTile(int tile, ViewGroup parent, LayoutInflater inflater) { QuickSettingsTileView quick = null; switch (tile) { case USER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_user, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBar.collapseAllPanels(true); final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE); if (um.getUsers(true).size() > 1) { try { WindowManagerGlobal.getWindowManagerService().lockNow( LockPatternUtils.USER_SWITCH_LOCK_OPTIONS); } catch (RemoteException e) { Log.e(TAG, "Couldn't show user switcher", e); } } else { Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent( mContext, v, ContactsContract.Profile.CONTENT_URI, ContactsContract.QuickContact.MODE_LARGE, null); mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT)); } } }); mModel.addUserTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { UserState us = (UserState) state; ImageView iv = (ImageView) view.findViewById(R.id.user_imageview); TextView tv = (TextView) view.findViewById(R.id.user_textview); tv.setText(state.label); iv.setImageDrawable(us.avatar); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_user, state.label)); } }); mDynamicSpannedTiles.add(quick); break; case CLOCK_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_time, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("android.intent.action.MAIN"); intent.setComponent(ComponentName.unflattenFromString("com.android.deskclock.AlarmProvider")); intent.addCategory("android.intent.category.LAUNCHER"); startSettingsActivity(intent); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(Intent.ACTION_QUICK_CLOCK); return true; } }); mModel.addTimeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State alarmState) { } }); mDynamicSpannedTiles.add(quick); break; case SIGNAL_TILE: if (mModel.deviceSupportsTelephony()) { // Mobile Network state quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_rssi, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { connManager.setMobileDataEnabled(connManager.getMobileDataEnabled() ? false : true); String strData = connManager.getMobileDataEnabled() ? strDataoff : strDataon; Toast.makeText(mContext, strData, Toast.LENGTH_SHORT).show(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Intent intent = new Intent(); intent.setComponent(new ComponentName( "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity")); startSettingsActivity(intent); return true; } }); mModel.addRSSITile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { RSSIState rssiState = (RSSIState) state; ImageView iv = (ImageView) view.findViewById(R.id.rssi_image); ImageView iov = (ImageView) view.findViewById(R.id.rssi_overlay_image); TextView tv = (TextView) view.findViewById(R.id.rssi_textview); iv.setImageResource(rssiState.signalIconId); if (rssiState.dataTypeIconId > 0) { iov.setImageResource(rssiState.dataTypeIconId); } else { iov.setImageDrawable(null); } tv.setText(state.label); view.setContentDescription(mContext.getResources().getString( R.string.accessibility_quick_settings_mobile, rssiState.signalContentDescription, rssiState.dataContentDescription, state.label)); } }); } break; case BRIGHTNESS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_brightness, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBar.collapseAllPanels(true); showBrightnessDialog(); } }); mModel.addBrightnessTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.brightness_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); dismissBrightnessDialog(mBrightnessDialogShortTimeout); } }); mDynamicSpannedTiles.add(quick); break; case SETTINGS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_settings, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SETTINGS); } }); mModel.addSettingsTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.settings_tileview); tv.setText(state.label); } }); mDynamicSpannedTiles.add(quick); break; case WIFI_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_wifi, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { wifiManager.setWifiEnabled(wifiManager.isWifiEnabled() ? false : true); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIFI_SETTINGS); return true; } }); mModel.addWifiTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { WifiState wifiState = (WifiState) state; TextView tv = (TextView) view.findViewById(R.id.wifi_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, wifiState.iconId, 0, 0); tv.setText(wifiState.label); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_wifi, wifiState.signalContentDescription, (wifiState.connected) ? wifiState.label : "")); } }); break; case TWOG_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_twog, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE); } catch (SettingNotFoundException e) { e.printStackTrace(); } if (mDataState == PhoneConstants.NT_MODE_GSM_ONLY) { tm.toggle2G(false); } else { tm.toggle2G(true); } mModel.refresh2gTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.add2gTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.twog_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case LTE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_lte, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE); } catch (SettingNotFoundException e) { e.printStackTrace(); } if (mDataState == PhoneConstants.NT_MODE_LTE_CDMA_EVDO || mDataState == PhoneConstants.NT_MODE_GLOBAL) { tm.toggleLTE(false); } else { tm.toggleLTE(true); } mModel.refreshLTETile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addLTETile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.lte_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case VIBRATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_vibrate, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_VIB); mModel.refreshVibrateTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addVibrateTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.vibrate_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case SILENT_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_silent, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT); mModel.refreshSilentTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addSilentTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.silent_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case TORCH_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_torch, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_TORCH); mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // maybe something here? return true; } }); mModel.addTorchTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.torch_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case FCHARGE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_fcharge, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFastCharge(isFastChargeOn() ? false : true); mModel.refreshFChargeTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // What do we put here? return true; } }); mModel.addFChargeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.fcharge_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case WIFI_TETHER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_wifi_tether, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mWifiApState = wifiManager.getWifiApState(); if (mWifiApState == WifiManager.WIFI_AP_STATE_DISABLED || mWifiApState == WifiManager.WIFI_AP_STATE_DISABLING) { changeWifiState(true); } else { changeWifiState(false); } mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addWifiTetherTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.wifi_tether_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case USB_TETHER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_usb_tether, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = updateUsbState() ? false : true; if (connManager.setUsbTethering(enabled) == ConnectivityManager.TETHER_ERROR_NO_ERROR) { mHandler.postDelayed(delayedRefresh, 1000); } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addUSBTetherTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.usb_tether_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case SYNC_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_sync, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = ContentResolver.getMasterSyncAutomatically(); ContentResolver.setMasterSyncAutomatically(enabled ? false : true); mModel.refreshSyncTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SYNC_SETTINGS); return true; } }); mModel.addSyncTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.sync_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case NFC_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_nfc, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext); boolean enabled = mNfcAdapter.isEnabled(); if (enabled) { mNfcAdapter.disable(); } else { mNfcAdapter.enable(); } mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addNFCTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.nfc_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case ROTATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_rotation_lock, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean locked = RotationPolicy.isRotationLocked(mContext); RotationPolicy.setRotationLock(mContext, !locked); } }); mModel.addRotationLockTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.rotation_lock_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case BATTERY_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_battery, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSettingsActivity(Intent.ACTION_POWER_USAGE_SUMMARY); } }); mModel.addBatteryTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { QuickSettingsModel.BatteryState batteryState = (QuickSettingsModel.BatteryState) state; TextView tv = (TextView) view.findViewById(R.id.battery_textview); ImageView iv = (ImageView) view.findViewById(R.id.battery_image); Drawable d = batteryState.pluggedIn ? mChargingBatteryLevels : mBatteryLevels; String t; if (batteryState.batteryLevel == 100) { t = mContext.getString(R.string.quick_settings_battery_charged_label); } else { t = batteryState.pluggedIn ? mContext.getString(R.string.quick_settings_battery_charging_label, batteryState.batteryLevel) : mContext.getString(R.string.status_bar_settings_battery_meter_format, batteryState.batteryLevel); } iv.setImageDrawable(d); iv.setImageLevel(batteryState.batteryLevel); tv.setText(t); view.setContentDescription( mContext.getString(R.string.accessibility_quick_settings_battery, t)); } }); break; case AIRPLANE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_airplane, inflater); mModel.addAirplaneModeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.airplane_mode_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); String airplaneState = mContext.getString( (state.enabled) ? R.string.accessibility_desc_on : R.string.accessibility_desc_off); view.setContentDescription( mContext.getString(R.string.accessibility_quick_settings_airplane, airplaneState)); tv.setText(state.label); } }); break; case BLUETOOTH_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_bluetooth, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter.isEnabled()) { adapter.disable(); } else { adapter.enable(); } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS); return true; } }); mModel.addBluetoothTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { BluetoothState bluetoothState = (BluetoothState) state; TextView tv = (TextView) view.findViewById(R.id.bluetooth_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); Resources r = mContext.getResources(); String label = state.label; /* * //TODO: Show connected bluetooth device label * Set<BluetoothDevice> btDevices = * mBluetoothController.getBondedBluetoothDevices(); if * (btDevices.size() == 1) { // Show the name of the * bluetooth device you are connected to label = * btDevices.iterator().next().getName(); } else if * (btDevices.size() > 1) { // Show a generic label * about the number of bluetooth devices label = * r.getString(R.string * .quick_settings_bluetooth_multiple_devices_label, * btDevices.size()); } */ view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_bluetooth, bluetoothState.stateContentDescription)); tv.setText(label); } }); break; case GPS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_location, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(), LocationManager.GPS_PROVIDER, gpsEnabled ? false : true); TextView tv = (TextView) v.findViewById(R.id.location_textview); tv.setText(gpsEnabled ? strGPSoff : strGPSon); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); return true; } }); mModel.addLocationTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); TextView tv = (TextView) view.findViewById(R.id.location_textview); String newString = state.label; if ((newString == null) || (newString.equals(""))) { tv.setText(gpsEnabled ? strGPSon : strGPSoff); } else { tv.setText(state.label); } } }); break; case IME_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_ime, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mBar.collapseAllPanels(true); Intent intent = new Intent(Settings.ACTION_SHOW_INPUT_METHOD_PICKER); PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); pendingIntent.send(); } catch (Exception e) { } } }); mModel.addImeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.ime_textview); if (state.label != null) { tv.setText(state.label); } } }); break; } return quick; }
private QuickSettingsTileView getTile(int tile, ViewGroup parent, LayoutInflater inflater) { QuickSettingsTileView quick = null; switch (tile) { case USER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_user, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBar.collapseAllPanels(true); final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE); if (um.getUsers(true).size() > 1) { try { WindowManagerGlobal.getWindowManagerService().lockNow( LockPatternUtils.USER_SWITCH_LOCK_OPTIONS); } catch (RemoteException e) { Log.e(TAG, "Couldn't show user switcher", e); } } else { Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent( mContext, v, ContactsContract.Profile.CONTENT_URI, ContactsContract.QuickContact.MODE_LARGE, null); mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT)); } } }); mModel.addUserTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { UserState us = (UserState) state; ImageView iv = (ImageView) view.findViewById(R.id.user_imageview); TextView tv = (TextView) view.findViewById(R.id.user_textview); tv.setText(state.label); iv.setImageDrawable(us.avatar); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_user, state.label)); } }); mDynamicSpannedTiles.add(quick); break; case CLOCK_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_time, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("android.intent.action.MAIN"); intent.setComponent(ComponentName.unflattenFromString("com.android.deskclock.AlarmProvider")); intent.addCategory("android.intent.category.LAUNCHER"); startSettingsActivity(intent); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(Intent.ACTION_QUICK_CLOCK); return true; } }); mModel.addTimeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State alarmState) { } }); mDynamicSpannedTiles.add(quick); break; case SIGNAL_TILE: if (mModel.deviceSupportsTelephony()) { // Mobile Network state quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_rssi, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { connManager.setMobileDataEnabled(connManager.getMobileDataEnabled() ? false : true); String strData = connManager.getMobileDataEnabled() ? strDataoff : strDataon; Toast.makeText(mContext, strData, Toast.LENGTH_SHORT).show(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Intent intent = new Intent(); intent.setComponent(new ComponentName( "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity")); startSettingsActivity(intent); return true; } }); mModel.addRSSITile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { RSSIState rssiState = (RSSIState) state; ImageView iv = (ImageView) view.findViewById(R.id.rssi_image); ImageView iov = (ImageView) view.findViewById(R.id.rssi_overlay_image); TextView tv = (TextView) view.findViewById(R.id.rssi_textview); iv.setImageResource(rssiState.signalIconId); if (rssiState.dataTypeIconId > 0) { iov.setImageResource(rssiState.dataTypeIconId); } else { iov.setImageDrawable(null); } tv.setText(state.label); view.setContentDescription(mContext.getResources().getString( R.string.accessibility_quick_settings_mobile, rssiState.signalContentDescription, rssiState.dataContentDescription, state.label)); } }); } break; case BRIGHTNESS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_brightness, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBar.collapseAllPanels(true); showBrightnessDialog(); } }); mModel.addBrightnessTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.brightness_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); dismissBrightnessDialog(mBrightnessDialogShortTimeout); } }); mDynamicSpannedTiles.add(quick); break; case SETTINGS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_settings, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SETTINGS); } }); mModel.addSettingsTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.settings_tileview); tv.setText(state.label); } }); mDynamicSpannedTiles.add(quick); break; case WIFI_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_wifi, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { wifiManager.setWifiEnabled(wifiManager.isWifiEnabled() ? false : true); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIFI_SETTINGS); return true; } }); mModel.addWifiTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { WifiState wifiState = (WifiState) state; TextView tv = (TextView) view.findViewById(R.id.wifi_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, wifiState.iconId, 0, 0); tv.setText(wifiState.label); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_wifi, wifiState.signalContentDescription, (wifiState.connected) ? wifiState.label : "")); } }); break; case TWOG_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_twog, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE); } catch (SettingNotFoundException e) { e.printStackTrace(); } if (mDataState == PhoneConstants.NT_MODE_GSM_ONLY) { tm.toggle2G(false); } else { tm.toggle2G(true); } mModel.refresh2gTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.add2gTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.twog_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case LTE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_lte, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE); } catch (SettingNotFoundException e) { e.printStackTrace(); } if (mDataState == PhoneConstants.NT_MODE_LTE_CDMA_EVDO || mDataState == PhoneConstants.NT_MODE_GLOBAL) { tm.toggleLTE(false); } else { tm.toggleLTE(true); } mModel.refreshLTETile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addLTETile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.lte_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case VIBRATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_vibrate, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_VIB); mModel.refreshVibrateTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addVibrateTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.vibrate_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case SILENT_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_silent, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT); mModel.refreshSilentTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addSilentTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.silent_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case TORCH_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_torch, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_TORCH); mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // maybe something here? return true; } }); mModel.addTorchTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.torch_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case FCHARGE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_fcharge, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateFastCharge(isFastChargeOn() ? false : true); mModel.refreshFChargeTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // What do we put here? return true; } }); mModel.addFChargeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.fcharge_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case WIFI_TETHER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_wifi_tether, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mWifiApState = wifiManager.getWifiApState(); if (mWifiApState == WifiManager.WIFI_AP_STATE_DISABLED || mWifiApState == WifiManager.WIFI_AP_STATE_DISABLING) { changeWifiState(true); } else { changeWifiState(false); } mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addWifiTetherTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.wifi_tether_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case USB_TETHER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_usb_tether, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = updateUsbState() ? false : true; if (connManager.setUsbTethering(enabled) == ConnectivityManager.TETHER_ERROR_NO_ERROR) { mHandler.postDelayed(delayedRefresh, 1000); } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addUSBTetherTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.usb_tether_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case SYNC_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_sync, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = ContentResolver.getMasterSyncAutomatically(); ContentResolver.setMasterSyncAutomatically(enabled ? false : true); mModel.refreshSyncTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SYNC_SETTINGS); return true; } }); mModel.addSyncTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.sync_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case NFC_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_nfc, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext); boolean enabled = false; if (mNfcAdapter != null) { enabled = mNfcAdapter.isEnabled(); } if (enabled) { mNfcAdapter.disable(); } else { mNfcAdapter.enable(); } mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addNFCTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.nfc_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case ROTATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_rotation_lock, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean locked = RotationPolicy.isRotationLocked(mContext); RotationPolicy.setRotationLock(mContext, !locked); } }); mModel.addRotationLockTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.rotation_lock_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); } }); break; case BATTERY_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_battery, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSettingsActivity(Intent.ACTION_POWER_USAGE_SUMMARY); } }); mModel.addBatteryTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { QuickSettingsModel.BatteryState batteryState = (QuickSettingsModel.BatteryState) state; TextView tv = (TextView) view.findViewById(R.id.battery_textview); ImageView iv = (ImageView) view.findViewById(R.id.battery_image); Drawable d = batteryState.pluggedIn ? mChargingBatteryLevels : mBatteryLevels; String t; if (batteryState.batteryLevel == 100) { t = mContext.getString(R.string.quick_settings_battery_charged_label); } else { t = batteryState.pluggedIn ? mContext.getString(R.string.quick_settings_battery_charging_label, batteryState.batteryLevel) : mContext.getString(R.string.status_bar_settings_battery_meter_format, batteryState.batteryLevel); } iv.setImageDrawable(d); iv.setImageLevel(batteryState.batteryLevel); tv.setText(t); view.setContentDescription( mContext.getString(R.string.accessibility_quick_settings_battery, t)); } }); break; case AIRPLANE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_airplane, inflater); mModel.addAirplaneModeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.airplane_mode_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); String airplaneState = mContext.getString( (state.enabled) ? R.string.accessibility_desc_on : R.string.accessibility_desc_off); view.setContentDescription( mContext.getString(R.string.accessibility_quick_settings_airplane, airplaneState)); tv.setText(state.label); } }); break; case BLUETOOTH_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_bluetooth, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter.isEnabled()) { adapter.disable(); } else { adapter.enable(); } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS); return true; } }); mModel.addBluetoothTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { BluetoothState bluetoothState = (BluetoothState) state; TextView tv = (TextView) view.findViewById(R.id.bluetooth_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); Resources r = mContext.getResources(); String label = state.label; /* * //TODO: Show connected bluetooth device label * Set<BluetoothDevice> btDevices = * mBluetoothController.getBondedBluetoothDevices(); if * (btDevices.size() == 1) { // Show the name of the * bluetooth device you are connected to label = * btDevices.iterator().next().getName(); } else if * (btDevices.size() > 1) { // Show a generic label * about the number of bluetooth devices label = * r.getString(R.string * .quick_settings_bluetooth_multiple_devices_label, * btDevices.size()); } */ view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_bluetooth, bluetoothState.stateContentDescription)); tv.setText(label); } }); break; case GPS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_location, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(), LocationManager.GPS_PROVIDER, gpsEnabled ? false : true); TextView tv = (TextView) v.findViewById(R.id.location_textview); tv.setText(gpsEnabled ? strGPSoff : strGPSon); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); return true; } }); mModel.addLocationTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); TextView tv = (TextView) view.findViewById(R.id.location_textview); String newString = state.label; if ((newString == null) || (newString.equals(""))) { tv.setText(gpsEnabled ? strGPSon : strGPSoff); } else { tv.setText(state.label); } } }); break; case IME_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_ime, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mBar.collapseAllPanels(true); Intent intent = new Intent(Settings.ACTION_SHOW_INPUT_METHOD_PICKER); PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); pendingIntent.send(); } catch (Exception e) { } } }); mModel.addImeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.ime_textview); if (state.label != null) { tv.setText(state.label); } } }); break; } return quick; }
diff --git a/src/blay09/mods/irc/IRCConnection.java b/src/blay09/mods/irc/IRCConnection.java index 547cc071..3cf6b647 100644 --- a/src/blay09/mods/irc/IRCConnection.java +++ b/src/blay09/mods/irc/IRCConnection.java @@ -1,422 +1,422 @@ // Copyright (c) 2013, Christopher "blay09" Baker // All rights reserved. package blay09.mods.irc; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import blay09.mods.irc.config.ConfigurationHandler; import blay09.mods.irc.config.GlobalConfig; import blay09.mods.irc.config.Globals; import blay09.mods.irc.config.NickServSettings; import blay09.mods.irc.config.ServerConfig; public class IRCConnection implements Runnable { private static final int IRC_PORT = 6667; private static final String LOGIN = "EiraIRC"; private static final String DESCRIPTION = "EiraIRC Bot"; private String host; private String currentNick; private ServerConfig config; private boolean connected; private Map<String, List<String>> channelUserMap; private List<String> privateChannels; private int tickTimer; private Thread thread; private Socket socket; private BufferedWriter writer; private BufferedReader reader; public IRCConnection(String host, boolean clientSide) { this.host = host; config = ConfigurationHandler.getServerConfig(host); config.clientSide = clientSide; channelUserMap = new HashMap<String, List<String>>(); if(clientSide) { if(config.nick.isEmpty()) { config.nick = Minecraft.getMinecraft().thePlayer.username; } privateChannels = new ArrayList<String>(); } } public boolean connect() { try { socket = new Socket(host, IRC_PORT); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (UnknownHostException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } thread = new Thread(this); thread.start(); return true; } public List<String> getUserList(String channel) { List<String> list = channelUserMap.get(channel); if(list == null) { list = new ArrayList<String>(); channelUserMap.put(channel, list); } return channelUserMap.get(channel); } public List<String> getPrivateChannels() { return privateChannels; } public void onUserJoin(String channel, String user) { String nick = Utils.getNickFromUser(user); EiraIRC.instance.getEventHandler().onIRCJoin(this, channel, user, nick); List<String> userList = channelUserMap.get(channel); if(userList == null) { userList = new ArrayList<String>(); channelUserMap.put(channel, userList); } userList.add(nick); } public void nickServ() { NickServSettings settings = NickServSettings.settings.get(host); if(settings == null) { return; } if(!config.nickServName.isEmpty() && !config.nickServPassword.isEmpty()) { sendPrivateMessage(settings.getBotName(), settings.getCommand() + " " + config.nickServName + " " + config.nickServPassword); } } public void onNickChange(String user, String newNick) { String oldNick = Utils.getNickFromUser(user); for(List<String> list : channelUserMap.values()) { if(list.contains(oldNick)) { list.remove(oldNick); list.add(newNick); } } EiraIRC.instance.getEventHandler().onIRCNickChange(this, Utils.getNickFromUser(user), newNick); } public void onPrivateMessage(String user, String message) { String nick = Utils.getNickFromUser(user); if(nick.equals("jtv") && host.equals(Globals.TWITCH_SERVER)) { // ignore them for now, maybe transfer Twitch colors to MC colors at some point later return; } if(config.clientSide) { EiraIRC.instance.getEventHandler().onIRCPrivateMessage(this, user, Utils.getNickFromUser(user), message); return; } message = message.toUpperCase(); if(message.equals("HELP")) { sendPrivateMessage(nick, "***** EiraIRC Help *****"); sendPrivateMessage(nick, "EiraIRC connects a Minecraft client or a whole server"); sendPrivateMessage(nick, "to one or multiple IRC channels and servers."); sendPrivateMessage(nick, "Visit <...> for more information on this bot."); sendPrivateMessage(nick, " "); sendPrivateMessage(nick, "The following commands are available:"); sendPrivateMessage(nick, "WHO Prints out a list of all players online"); sendPrivateMessage(nick, "HELP Prints this command list"); sendPrivateMessage(nick, "ALIAS Look up the username of an online player"); sendPrivateMessage(nick, "MSG Send a private message to an online player"); sendPrivateMessage(nick, "***** End of Help *****"); return; } else if(message.equals("WHO")) { List<EntityPlayerMP> playerEntityList = MinecraftServer.getServer().getConfigurationManager().playerEntityList; sendPrivateMessage(nick, playerEntityList.size() + " players online:"); String s = "* "; for(int i = 0; i < playerEntityList.size(); i++) { EntityPlayerMP entityPlayer = playerEntityList.get(i); String alias = Utils.getAliasForPlayer(entityPlayer); if(s.length() + alias.length() + 2 >= 100) { sendPrivateMessage(nick, s); s = "* "; } if(s.length() > 2) { s += ", "; } s += alias; } if(s.length() > 2) { sendPrivateMessage(nick, s); } return; } else if(message.startsWith("ALIAS ")) { if(!GlobalConfig.enableAliases) { sendPrivateMessage(nick, "Aliases are not enabled on this server."); return; } int i = message.indexOf(" ", 7); String alias = message.substring(7); List<EntityPlayer> playerEntityList = MinecraftServer.getServer().getConfigurationManager().playerEntityList; for(EntityPlayer entity : playerEntityList) { if(Utils.getAliasForPlayer(entity).equals(alias)) { sendPrivateMessage(nick, "The username for '" + alias + "' is '" + entity.username + "'."); return; } } sendPrivateMessage(nick, "That player cannot be found."); return; } else if(message.startsWith("MSG ")) { if(!GlobalConfig.allowPrivateMessages || !config.allowPrivateMessages) { sendPrivateMessage(nick, "Private messages are disabled on this server."); return; } int i = message.indexOf(" ", 5); String playerName = message.substring(4, i); EntityPlayer entityPlayer = MinecraftServer.getServer().getConfigurationManager().getPlayerForUsername(playerName); if(entityPlayer == null) { List<EntityPlayer> playerEntityList = MinecraftServer.getServer().getConfigurationManager().playerEntityList; for(EntityPlayer entity : playerEntityList) { if(Utils.getAliasForPlayer(entity).equals(playerName)) { entityPlayer = entity; } } if(entityPlayer == null) { sendPrivateMessage(nick, "That player cannot be found."); return; } } String targetMessage = message.substring(i + 1); EiraIRC.instance.getEventHandler().onIRCPrivateMessageToPlayer(this, user, nick, entityPlayer, targetMessage); sendPrivateMessage(nick, "Message sent to " + playerName + ": " + targetMessage); return; } sendPrivateMessage(nick, "Unknown command. Type HELP for a list of all commands."); } public void onPrivateEmote(String user, String message) { EiraIRC.instance.getEventHandler().onIRCPrivateEmote(this, user, Utils.getNickFromUser(user), message); } public void onChannelEmote(String channel, String user, String message) { EiraIRC.instance.getEventHandler().onIRCEmote(this, channel, user, Utils.getNickFromUser(user), message); } public void onChannelMessage(String channel, String user, String message) { EiraIRC.instance.getEventHandler().onIRCMessage(this, channel, user, Utils.getNickFromUser(user), message); } public void onUserPart(String channel, String user) { String nick = Utils.getNickFromUser(user); EiraIRC.instance.getEventHandler().onIRCPart(this, channel, user, nick); List<String> userList = channelUserMap.get(channel); if(userList == null) { userList = new ArrayList<String>(); userList = channelUserMap.put(channel, userList); } userList.remove(nick); } @Override public void run() { try { if(!config.serverPassword.isEmpty()) { writer.write("PASS " + config.serverPassword + "\r\n"); writer.flush(); } changeNick(config.nick.isEmpty() ? GlobalConfig.nick + (int) (Math.random() * 10000) : config.nick); writer.write("USER " + LOGIN + " \"\" \"\" :" + DESCRIPTION + "\r\n"); writer.flush(); String line = null; while((line = reader.readLine()) != null) { // Ping if(line.startsWith("PING ")) { writer.write("PONG " + line.substring(5) + "\r\n"); writer.flush(); continue; } // Message if(line.contains(" PRIVMSG ")) { int i = line.indexOf(" PRIVMSG "); String user = line.substring(1, i); int j = line.indexOf(":", i); String channel = line.substring(i + 9, j - 1); String message = null; if(line.contains("ACTION")) { message = line.substring(j + 9, line.length() - 1); if(channel.equals(currentNick)) { onPrivateEmote(user, message); } else { onChannelEmote(channel, user, message); } } else { message = line.substring(j + 1); - if(channel.equals(currentNick)) { + if(channel.equalsIgnoreCase(currentNick)) { onPrivateMessage(user, message); } else { onChannelMessage(channel, user, message); } } continue; } // User Part if(line.contains(" PART ")) { int i = line.indexOf(" PART "); String user = line.substring(1, i); String channel = line.substring(i + 6); onUserPart(channel, user); } // User Join if(line.contains(" JOIN ")) { int i = line.indexOf(" JOIN "); String user = line.substring(1, i); String channel = line.substring(i + 6); onUserJoin(channel, user); } // Nick Change Success if(line.contains(" NICK ")) { int i = line.indexOf(" NICK "); String user = line.substring(1, i); String nick = line.substring(i + 7); onNickChange(user, nick); } // Nick Already in Use if(line.contains(" 433 ")) { changeNick(config.nick + "_"); continue; } // Names List if(line.contains(" 353 ")) { int i = line.indexOf(" = "); int j = line.indexOf(":", i); String channel = line.substring(i + 3, j - 1); List<String> userList = channelUserMap.get(channel); if(userList == null) { userList = new ArrayList<String>(); channelUserMap.put(channel, userList); } else { userList.clear(); } String[] userArray = line.substring(j + 1).split(" "); for(int k = 0; k < userArray.length; k++) { if(userArray[k].startsWith("+") || userArray[k].startsWith("@")) { userArray[k] = userArray[k].substring(1); } userList.add(userArray[k]); } continue; } // End of MOTD if(line.contains(" 376 ")) { EiraIRC.instance.getEventHandler().onIRCConnect(this); nickServ(); connected = true; for(String channel : config.channels) { joinChannel(channel); } continue; } - System.out.println(line); +// System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } EiraIRC.instance.getEventHandler().onIRCDisconnect(this); EiraIRC.instance.removeConnection(this); if(connected) { if(connect()) { EiraIRC.instance.addConnection(this); } } } public void joinChannel(String channel) throws IOException { writer.write("JOIN " + channel + "\r\n"); writer.flush(); if(!config.channels.contains(channel)) { config.channels.add(channel); ConfigurationHandler.save(); } } public void changeNick(String nick) throws IOException { writer.write("NICK " + nick + "\r\n"); writer.flush(); currentNick = nick; } public void sendChannelMessage(String channel, String message) { try { writer.write("PRIVMSG " + channel + " :" + message + "\r\n"); writer.flush(); } catch (IOException e) { e.printStackTrace(); } } public void sendPrivateMessage(String nick, String message) { try { writer.write("PRIVMSG " + nick + " :" + message + "\r\n"); writer.flush(); } catch (IOException e) { e.printStackTrace(); } if(config.clientSide && !privateChannels.contains(nick)) { NickServSettings settings = NickServSettings.settings.get(host); if(settings == null) { return; } if(!nick.equals(settings.getBotName())) { privateChannels.add(nick); } } } public String getHost() { return host; } public void broadcastMessage(String message, String requiredFlags) { for(String channel : config.channels) { if(config.hasChannelFlags(channel, requiredFlags)) { sendChannelMessage(channel, message); } } } public void disconnect() { try { connected = false; if(socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } public void leaveChannel(String channel) throws IOException { writer.write("PART " + channel + "\r\n"); writer.flush(); config.channels.remove(channel); ConfigurationHandler.save(); } public ServerConfig getConfig() { return config; } }
false
true
public void run() { try { if(!config.serverPassword.isEmpty()) { writer.write("PASS " + config.serverPassword + "\r\n"); writer.flush(); } changeNick(config.nick.isEmpty() ? GlobalConfig.nick + (int) (Math.random() * 10000) : config.nick); writer.write("USER " + LOGIN + " \"\" \"\" :" + DESCRIPTION + "\r\n"); writer.flush(); String line = null; while((line = reader.readLine()) != null) { // Ping if(line.startsWith("PING ")) { writer.write("PONG " + line.substring(5) + "\r\n"); writer.flush(); continue; } // Message if(line.contains(" PRIVMSG ")) { int i = line.indexOf(" PRIVMSG "); String user = line.substring(1, i); int j = line.indexOf(":", i); String channel = line.substring(i + 9, j - 1); String message = null; if(line.contains("ACTION")) { message = line.substring(j + 9, line.length() - 1); if(channel.equals(currentNick)) { onPrivateEmote(user, message); } else { onChannelEmote(channel, user, message); } } else { message = line.substring(j + 1); if(channel.equals(currentNick)) { onPrivateMessage(user, message); } else { onChannelMessage(channel, user, message); } } continue; } // User Part if(line.contains(" PART ")) { int i = line.indexOf(" PART "); String user = line.substring(1, i); String channel = line.substring(i + 6); onUserPart(channel, user); } // User Join if(line.contains(" JOIN ")) { int i = line.indexOf(" JOIN "); String user = line.substring(1, i); String channel = line.substring(i + 6); onUserJoin(channel, user); } // Nick Change Success if(line.contains(" NICK ")) { int i = line.indexOf(" NICK "); String user = line.substring(1, i); String nick = line.substring(i + 7); onNickChange(user, nick); } // Nick Already in Use if(line.contains(" 433 ")) { changeNick(config.nick + "_"); continue; } // Names List if(line.contains(" 353 ")) { int i = line.indexOf(" = "); int j = line.indexOf(":", i); String channel = line.substring(i + 3, j - 1); List<String> userList = channelUserMap.get(channel); if(userList == null) { userList = new ArrayList<String>(); channelUserMap.put(channel, userList); } else { userList.clear(); } String[] userArray = line.substring(j + 1).split(" "); for(int k = 0; k < userArray.length; k++) { if(userArray[k].startsWith("+") || userArray[k].startsWith("@")) { userArray[k] = userArray[k].substring(1); } userList.add(userArray[k]); } continue; } // End of MOTD if(line.contains(" 376 ")) { EiraIRC.instance.getEventHandler().onIRCConnect(this); nickServ(); connected = true; for(String channel : config.channels) { joinChannel(channel); } continue; } System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } EiraIRC.instance.getEventHandler().onIRCDisconnect(this); EiraIRC.instance.removeConnection(this); if(connected) { if(connect()) { EiraIRC.instance.addConnection(this); } } }
public void run() { try { if(!config.serverPassword.isEmpty()) { writer.write("PASS " + config.serverPassword + "\r\n"); writer.flush(); } changeNick(config.nick.isEmpty() ? GlobalConfig.nick + (int) (Math.random() * 10000) : config.nick); writer.write("USER " + LOGIN + " \"\" \"\" :" + DESCRIPTION + "\r\n"); writer.flush(); String line = null; while((line = reader.readLine()) != null) { // Ping if(line.startsWith("PING ")) { writer.write("PONG " + line.substring(5) + "\r\n"); writer.flush(); continue; } // Message if(line.contains(" PRIVMSG ")) { int i = line.indexOf(" PRIVMSG "); String user = line.substring(1, i); int j = line.indexOf(":", i); String channel = line.substring(i + 9, j - 1); String message = null; if(line.contains("ACTION")) { message = line.substring(j + 9, line.length() - 1); if(channel.equals(currentNick)) { onPrivateEmote(user, message); } else { onChannelEmote(channel, user, message); } } else { message = line.substring(j + 1); if(channel.equalsIgnoreCase(currentNick)) { onPrivateMessage(user, message); } else { onChannelMessage(channel, user, message); } } continue; } // User Part if(line.contains(" PART ")) { int i = line.indexOf(" PART "); String user = line.substring(1, i); String channel = line.substring(i + 6); onUserPart(channel, user); } // User Join if(line.contains(" JOIN ")) { int i = line.indexOf(" JOIN "); String user = line.substring(1, i); String channel = line.substring(i + 6); onUserJoin(channel, user); } // Nick Change Success if(line.contains(" NICK ")) { int i = line.indexOf(" NICK "); String user = line.substring(1, i); String nick = line.substring(i + 7); onNickChange(user, nick); } // Nick Already in Use if(line.contains(" 433 ")) { changeNick(config.nick + "_"); continue; } // Names List if(line.contains(" 353 ")) { int i = line.indexOf(" = "); int j = line.indexOf(":", i); String channel = line.substring(i + 3, j - 1); List<String> userList = channelUserMap.get(channel); if(userList == null) { userList = new ArrayList<String>(); channelUserMap.put(channel, userList); } else { userList.clear(); } String[] userArray = line.substring(j + 1).split(" "); for(int k = 0; k < userArray.length; k++) { if(userArray[k].startsWith("+") || userArray[k].startsWith("@")) { userArray[k] = userArray[k].substring(1); } userList.add(userArray[k]); } continue; } // End of MOTD if(line.contains(" 376 ")) { EiraIRC.instance.getEventHandler().onIRCConnect(this); nickServ(); connected = true; for(String channel : config.channels) { joinChannel(channel); } continue; } // System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } EiraIRC.instance.getEventHandler().onIRCDisconnect(this); EiraIRC.instance.removeConnection(this); if(connected) { if(connect()) { EiraIRC.instance.addConnection(this); } } }
diff --git a/examples/itests/tests/src/test/java/org/apache/servicemix/examples/IntegrationTest.java b/examples/itests/tests/src/test/java/org/apache/servicemix/examples/IntegrationTest.java index e0a17bcc..b02e51c1 100644 --- a/examples/itests/tests/src/test/java/org/apache/servicemix/examples/IntegrationTest.java +++ b/examples/itests/tests/src/test/java/org/apache/servicemix/examples/IntegrationTest.java @@ -1,348 +1,348 @@ /* * 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.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import java.util.jar.Manifest; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.List; import javax.xml.transform.Source; import org.apache.cxf.Bus; import org.apache.servicemix.examples.cxf.HelloWorld; import org.apache.servicemix.jbi.jaxp.StringSource; import org.apache.servicemix.nmr.api.Channel; import org.apache.servicemix.nmr.api.Endpoint; import org.apache.servicemix.nmr.api.Exchange; import org.apache.servicemix.nmr.api.NMR; import org.apache.servicemix.nmr.api.Pattern; import org.apache.servicemix.nmr.api.Status; import org.apache.servicemix.platform.testing.support.AbstractIntegrationTest; import org.apache.servicemix.util.FileUtil; import org.springframework.osgi.test.platform.OsgiPlatform; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; 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.servicemix.specs", "org.apache.servicemix.specs.activation-api-1.1"), getBundle("org.apache.geronimo.specs", "geronimo-annotation_1.0_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.geronimo.specs", "geronimo-j2ee-connector_1.5_spec"), getBundle("org.apache.geronimo.specs", "geronimo-jta_1.1_spec"), //for activemq getBundle("org.springframework", "spring-jms"), getBundle("org.springframework", "spring-tx"), getBundle("org.apache.geronimo.specs", "geronimo-j2ee-management_1.1_spec"), getBundle("org.apache.geronimo.specs", "geronimo-jms_1.1_spec"), - getBundle("commons-pool", "commons-pool"), + getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.commons-pool"), getBundle("org.apache.xbean", "xbean-spring"), getBundle("org.apache.activemq", "activemq-core"), getBundle("org.apache.activemq", "activemq-ra"), getBundle("org.apache.activemq", "activemq-console"), getBundle("org.apache.activemq", "activemq-pool"), getBundle("org.apache.activemq", "kahadb"), //for ws-security getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.opensaml"), getBundle("org.apache.ws.security", "wss4j"), getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.jbi-api-1.0"), 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"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.cglib"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.jaxb-impl"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.neethi"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.saaj-impl"), getBundle("org.codehaus.woodstox", "stax2-api"), getBundle("org.codehaus.woodstox", "woodstox-core-asl"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.wsdl4j"), getBundle("org.apache.ws.commons.schema", "XmlSchema"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlresolver"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.bcel"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xerces"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xalan"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlsec"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.jetty-bundle"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.javax.mail"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.commons-codec"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.commons-httpclient"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.abdera"), getBundle("org.codehaus.jettison", "jettison"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlbeans"), getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.jsr311-api-1.0"), getBundle("org.ops4j.pax.web", "pax-web-api"), getBundle("org.ops4j.pax.web", "pax-web-spi"), getBundle("org.ops4j.pax.web", "pax-web-runtime"), getBundle("org.ops4j.pax.web", "pax-web-jetty"), getBundle("org.ops4j.pax.web", "pax-web-extender-whiteboard"), getBundle("org.apache.servicemix", "servicemix-utils"), getBundle("org.fusesource.commonman", "commons-management"), getBundle("org.apache.felix.karaf", "org.apache.felix.karaf.management"), getBundle("org.apache.cxf", "cxf-bundle"), 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.management"), 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"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-http-osgi"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-ws-security-osgi"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-jms-osgi"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-soap-handler-osgi"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-handler-cfg"), getBundle("org.apache.servicemix.examples", "cxf-ws-addressing"), getBundle("org.apache.servicemix.examples", "cxf-jaxrs"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-nmr-osgi"), }; } public void testJbiComponent() throws Exception { Thread.sleep(5000); installBundle("org.apache.servicemix.examples", "cxf-osgi", null, "jar"); Thread.sleep(5000); } public void testHttpOsgi() throws Exception { Thread.sleep(5000); waitOnContextCreation("org.apache.servicemix.examples.itests.cxf-http-osgi"); Thread.sleep(5000); ServiceReference ref = bundleContext.getServiceReference(HelloWorld.class.getName()); assertNotNull("Service Reference is null", ref); org.apache.servicemix.examples.cxf.HelloWorld helloWorld = null; helloWorld = (org.apache.servicemix.examples.cxf.HelloWorld) bundleContext.getService(ref); assertNotNull("Cannot find the service", helloWorld); assertEquals("Hello Bonjour", helloWorld.sayHi("Bonjour")); } public void testJmsOsgi() throws Exception { Thread.sleep(5000); waitOnContextCreation("org.apache.servicemix.examples.itests.cxf-jms-osgi"); Thread.sleep(5000); ServiceReference ref = bundleContext.getServiceReference(HelloWorld.class.getName()); assertNotNull("Service Reference is null", ref); org.apache.servicemix.examples.cxf.HelloWorld helloWorld = null; helloWorld = (org.apache.servicemix.examples.cxf.HelloWorld) bundleContext.getService(ref); assertNotNull("Cannot find the service", helloWorld); assertEquals("Hello Bonjour", helloWorld.sayHi("Bonjour")); } public void testNMROsgi() throws Exception { Thread.sleep(5000); waitOnContextCreation("org.apache.servicemix.examples.itests.cxf-nmr-osgi"); Thread.sleep(5000); NMR nmr = getOsgiService(NMR.class); assertNotNull(nmr); Channel client = nmr.createChannel(); Exchange e = client.createExchange(Pattern.InOut); for (Endpoint ep : nmr.getEndpointRegistry().getServices()) { e.setTarget(nmr.getEndpointRegistry().lookup(nmr.getEndpointRegistry().getProperties(ep))); e.getIn().setBody(new StringSource("<?xml version=\"1.0\" encoding=\"UTF-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns2:sayHi xmlns:ns2=\"http://cxf.examples.servicemix.apache.org/\"><arg0>Bonjour</arg0></ns2:sayHi></soap:Body></soap:Envelope>")); boolean res = client.sendSync(e); assertTrue(res); } } protected Manifest getManifest() { Manifest mf = super.getManifest(); String importP = mf.getMainAttributes().getValue(Constants.IMPORT_PACKAGE); mf.getMainAttributes().putValue(Constants.IMPORT_PACKAGE, importP + ",META-INF.cxf, org.apache.servicemix.jbi.jaxp"); String exportP = mf.getMainAttributes().getValue(Constants.EXPORT_PACKAGE); mf.getMainAttributes().putValue(Constants.EXPORT_PACKAGE, exportP + ",org.apache.handlers, " + "org.apache.springcfg.handlers, " + "org.apache.handlers.types,org.apache.servicemix.examples.cxf," + "org.apache.servicemix.examples.cxf.soaphandler," + "org.apache.servicemix.examples.cxf.springcfghandler," + "org.apache.servicemix.examples.cxf.wsaddressing," + "org.apache.servicemix.util," + "org.apache.hello_world_soap_http," + "org.apache.cxf," + "org.apache.cxf.bus," + "org.apache.cxf.interceptor" ); return mf; } public void testSoapHandlerOsgi() throws Exception { Thread.sleep(5000); waitOnContextCreation("org.apache.servicemix.examples.itests.cxf-soap-handler-osgi"); Thread.sleep(5000); ServiceReference ref = bundleContext.getServiceReference(org.apache.handlers.AddNumbers.class.getName()); assertNotNull("Service Reference is null", ref); org.apache.handlers.AddNumbers addNumbers = null; addNumbers = (org.apache.handlers.AddNumbers) bundleContext.getService(ref); assertNotNull("Cannot find the service", addNumbers); assertEquals(2, addNumbers.addNumbers(1,1)); } public void testSpringConfigHandlerOsgi() throws Exception { Thread.sleep(5000); waitOnContextCreation("org.apache.servicemix.examples.itests.cxf-handler-cfg"); Thread.sleep(5000); ServiceReference ref = bundleContext.getServiceReference(org.apache.springcfg.handlers.AddNumbers.class.getName()); assertNotNull("Service Reference is null", ref); org.apache.springcfg.handlers.AddNumbers addNumbers = null; addNumbers = (org.apache.springcfg.handlers.AddNumbers) bundleContext.getService(ref); assertNotNull("Cannot find the service", addNumbers); assertEquals(1016, addNumbers.addNumbers(10, 16)); } public void testWsAddressingOsgi() throws Exception { Thread.sleep(5000); waitOnContextCreation("cxf-ws-addressing"); ServiceReference busref = bundleContext.getServiceReference(org.apache.cxf.bus.CXFBusImpl.class.getName()); assertNotNull("Bus Reference is null", busref); Bus bus = (Bus)bundleContext.getService(busref); ByteArrayOutputStream input = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(input, true); org.apache.cxf.interceptor.LoggingInInterceptor in = new org.apache.cxf.interceptor.LoggingInInterceptor(writer); bus.getInInterceptors().add(in); ByteArrayOutputStream output = new ByteArrayOutputStream(); PrintWriter outwriter = new PrintWriter(output, true); org.apache.cxf.interceptor.LoggingOutInterceptor out = new org.apache.cxf.interceptor.LoggingOutInterceptor(outwriter); bus.getOutInterceptors().add(out); ServiceReference ref = bundleContext.getServiceReference(org.apache.hello_world_soap_http.Greeter.class.getName()); assertNotNull("Service Reference is null", ref); org.apache.hello_world_soap_http.Greeter greeter = null; greeter = (org.apache.hello_world_soap_http.Greeter) bundleContext.getService(ref); assertNotNull("Cannot find the service", greeter); assertEquals("Bonjour", greeter.sayHi()); String expectedOut = "<Address>http://www.w3.org/2005/08/addressing/anonymous</Address>"; String expectedIn = "<RelatesTo xmlns=\"http://www.w3.org/2005/08/addressing\">"; assertTrue(output.toString().indexOf(expectedOut) != -1); assertTrue(input.toString().indexOf(expectedIn) != -1); } public void testJaxRS() throws Exception { Thread.sleep(5000); waitOnContextCreation("cxf-jaxrs"); URL url = new URL("http://localhost:8080/cxf/crm/customerservice/customers/123"); InputStream in = url.openStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int c = 0; while ((c = in.read()) != -1) { bos.write(c); } in.close(); bos.close(); System.out.println(bos.toString()); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Customer><id>123</id><name>John</name></Customer>", bos.toString()); } public void testWSSecurity() throws Exception { Thread.sleep(5000); waitOnContextCreation("org.apache.servicemix.examples.itests.cxf-ws-security-osgi"); Thread.sleep(5000); URLConnection connection = new URL("http://localhost:8080/cxf/HelloWorldSecurity") .openConnection(); connection.setDoInput(true); connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); // Post the request file. InputStream fis = getClass().getClassLoader().getResourceAsStream("org/apache/servicemix/request.xml"); FileUtil.copyInputStream(fis, os); // Read the response. InputStream is = connection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileUtil.copyInputStream(is, baos); assertTrue(baos.toString().indexOf("Hello John Doe") >= 0); } }
true
true
protected String[] getTestBundlesNames() { return new String[] { getBundle("org.apache.felix", "org.apache.felix.prefs"), getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.activation-api-1.1"), getBundle("org.apache.geronimo.specs", "geronimo-annotation_1.0_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.geronimo.specs", "geronimo-j2ee-connector_1.5_spec"), getBundle("org.apache.geronimo.specs", "geronimo-jta_1.1_spec"), //for activemq getBundle("org.springframework", "spring-jms"), getBundle("org.springframework", "spring-tx"), getBundle("org.apache.geronimo.specs", "geronimo-j2ee-management_1.1_spec"), getBundle("org.apache.geronimo.specs", "geronimo-jms_1.1_spec"), getBundle("commons-pool", "commons-pool"), getBundle("org.apache.xbean", "xbean-spring"), getBundle("org.apache.activemq", "activemq-core"), getBundle("org.apache.activemq", "activemq-ra"), getBundle("org.apache.activemq", "activemq-console"), getBundle("org.apache.activemq", "activemq-pool"), getBundle("org.apache.activemq", "kahadb"), //for ws-security getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.opensaml"), getBundle("org.apache.ws.security", "wss4j"), getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.jbi-api-1.0"), 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"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.cglib"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.jaxb-impl"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.neethi"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.saaj-impl"), getBundle("org.codehaus.woodstox", "stax2-api"), getBundle("org.codehaus.woodstox", "woodstox-core-asl"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.wsdl4j"), getBundle("org.apache.ws.commons.schema", "XmlSchema"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlresolver"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.bcel"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xerces"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xalan"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlsec"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.jetty-bundle"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.javax.mail"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.commons-codec"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.commons-httpclient"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.abdera"), getBundle("org.codehaus.jettison", "jettison"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlbeans"), getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.jsr311-api-1.0"), getBundle("org.ops4j.pax.web", "pax-web-api"), getBundle("org.ops4j.pax.web", "pax-web-spi"), getBundle("org.ops4j.pax.web", "pax-web-runtime"), getBundle("org.ops4j.pax.web", "pax-web-jetty"), getBundle("org.ops4j.pax.web", "pax-web-extender-whiteboard"), getBundle("org.apache.servicemix", "servicemix-utils"), getBundle("org.fusesource.commonman", "commons-management"), getBundle("org.apache.felix.karaf", "org.apache.felix.karaf.management"), getBundle("org.apache.cxf", "cxf-bundle"), 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.management"), 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"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-http-osgi"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-ws-security-osgi"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-jms-osgi"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-soap-handler-osgi"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-handler-cfg"), getBundle("org.apache.servicemix.examples", "cxf-ws-addressing"), getBundle("org.apache.servicemix.examples", "cxf-jaxrs"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-nmr-osgi"), }; }
protected String[] getTestBundlesNames() { return new String[] { getBundle("org.apache.felix", "org.apache.felix.prefs"), getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.activation-api-1.1"), getBundle("org.apache.geronimo.specs", "geronimo-annotation_1.0_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.geronimo.specs", "geronimo-j2ee-connector_1.5_spec"), getBundle("org.apache.geronimo.specs", "geronimo-jta_1.1_spec"), //for activemq getBundle("org.springframework", "spring-jms"), getBundle("org.springframework", "spring-tx"), getBundle("org.apache.geronimo.specs", "geronimo-j2ee-management_1.1_spec"), getBundle("org.apache.geronimo.specs", "geronimo-jms_1.1_spec"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.commons-pool"), getBundle("org.apache.xbean", "xbean-spring"), getBundle("org.apache.activemq", "activemq-core"), getBundle("org.apache.activemq", "activemq-ra"), getBundle("org.apache.activemq", "activemq-console"), getBundle("org.apache.activemq", "activemq-pool"), getBundle("org.apache.activemq", "kahadb"), //for ws-security getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.opensaml"), getBundle("org.apache.ws.security", "wss4j"), getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.jbi-api-1.0"), 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"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.cglib"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.jaxb-impl"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.neethi"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.saaj-impl"), getBundle("org.codehaus.woodstox", "stax2-api"), getBundle("org.codehaus.woodstox", "woodstox-core-asl"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.wsdl4j"), getBundle("org.apache.ws.commons.schema", "XmlSchema"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlresolver"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.bcel"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xerces"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xalan"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlsec"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.jetty-bundle"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.javax.mail"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.commons-codec"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.commons-httpclient"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.abdera"), getBundle("org.codehaus.jettison", "jettison"), getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlbeans"), getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.jsr311-api-1.0"), getBundle("org.ops4j.pax.web", "pax-web-api"), getBundle("org.ops4j.pax.web", "pax-web-spi"), getBundle("org.ops4j.pax.web", "pax-web-runtime"), getBundle("org.ops4j.pax.web", "pax-web-jetty"), getBundle("org.ops4j.pax.web", "pax-web-extender-whiteboard"), getBundle("org.apache.servicemix", "servicemix-utils"), getBundle("org.fusesource.commonman", "commons-management"), getBundle("org.apache.felix.karaf", "org.apache.felix.karaf.management"), getBundle("org.apache.cxf", "cxf-bundle"), 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.management"), 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"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-http-osgi"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-ws-security-osgi"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-jms-osgi"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-soap-handler-osgi"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-handler-cfg"), getBundle("org.apache.servicemix.examples", "cxf-ws-addressing"), getBundle("org.apache.servicemix.examples", "cxf-jaxrs"), getBundle("org.apache.servicemix.examples", "org.apache.servicemix.examples.itests.cxf-nmr-osgi"), }; }
diff --git a/vme-service/src/main/java/org/fao/fi/vme/msaccess/tables/Meetings.java b/vme-service/src/main/java/org/fao/fi/vme/msaccess/tables/Meetings.java index f67cd93c..01e652d8 100644 --- a/vme-service/src/main/java/org/fao/fi/vme/msaccess/tables/Meetings.java +++ b/vme-service/src/main/java/org/fao/fi/vme/msaccess/tables/Meetings.java @@ -1,121 +1,121 @@ package org.fao.fi.vme.msaccess.tables; import java.net.MalformedURLException; import java.net.URL; import org.fao.fi.vme.VmeException; import org.fao.fi.vme.domain.InformationSource; import org.fao.fi.vme.domain.util.MultiLingualStringUtil; import org.fao.fi.vme.msaccess.formatter.MeetingDateParser; import org.fao.fi.vme.msaccess.mapping.TableDomainMapper; public class Meetings implements TableDomainMapper { private int ID; private String RFB_ID; private int Year_ID; private String Meeting_Date; private String Report_Summary; private String Committee; private String Citation; private String Link_Tagged_File; private String Link_Source; public int getID() { return ID; } public void setID(int iD) { ID = iD; } public String getRFB_ID() { return RFB_ID; } public void setRFB_ID(String rFB_ID) { RFB_ID = rFB_ID; } public int getYear_ID() { return Year_ID; } public void setYear_ID(int year_ID) { Year_ID = year_ID; } public String getMeeting_Date() { return Meeting_Date; } public void setMeeting_Date(String meeting_Date) { Meeting_Date = meeting_Date; } public String getReport_Summary() { return Report_Summary; } public void setReport_Summary(String report_Summary) { Report_Summary = report_Summary; } public String getCommittee() { return Committee; } public void setCommittee(String committee) { Committee = committee; } public String getCitation() { return Citation; } public void setCitation(String citation) { Citation = citation; } public String getLink_Tagged_File() { return Link_Tagged_File; } public void setLink_Tagged_File(String link_Tagged_File) { Link_Tagged_File = link_Tagged_File; } public String getLink_Source() { return Link_Source; } public void setLink_Source(String link_Source) { Link_Source = link_Source; } @Override public Object map() { InformationSource is = new InformationSource(); // TODO what are the types? is.setSourceType(0); MultiLingualStringUtil u = new MultiLingualStringUtil(); is.setCommittee(u.english(this.Committee)); MeetingDateParser p = new MeetingDateParser(this.Meeting_Date); is.setMeetingStartDate(p.getStart()); is.setMeetingEndDate(p.getEnd()); is.setId(this.ID); is.setReportSummary(u.english(this.getReport_Summary())); try { URL url = new URL(this.getLink_Source()); is.setUrl(url); } catch (MalformedURLException e) { throw new VmeException(e); } - is.setCitation(u.english(this.getLink_Tagged_File())); + is.setCitation(u.english(this.getCitation())); return is; } }
true
true
public Object map() { InformationSource is = new InformationSource(); // TODO what are the types? is.setSourceType(0); MultiLingualStringUtil u = new MultiLingualStringUtil(); is.setCommittee(u.english(this.Committee)); MeetingDateParser p = new MeetingDateParser(this.Meeting_Date); is.setMeetingStartDate(p.getStart()); is.setMeetingEndDate(p.getEnd()); is.setId(this.ID); is.setReportSummary(u.english(this.getReport_Summary())); try { URL url = new URL(this.getLink_Source()); is.setUrl(url); } catch (MalformedURLException e) { throw new VmeException(e); } is.setCitation(u.english(this.getLink_Tagged_File())); return is; }
public Object map() { InformationSource is = new InformationSource(); // TODO what are the types? is.setSourceType(0); MultiLingualStringUtil u = new MultiLingualStringUtil(); is.setCommittee(u.english(this.Committee)); MeetingDateParser p = new MeetingDateParser(this.Meeting_Date); is.setMeetingStartDate(p.getStart()); is.setMeetingEndDate(p.getEnd()); is.setId(this.ID); is.setReportSummary(u.english(this.getReport_Summary())); try { URL url = new URL(this.getLink_Source()); is.setUrl(url); } catch (MalformedURLException e) { throw new VmeException(e); } is.setCitation(u.english(this.getCitation())); return is; }
diff --git a/src/java/org/apache/cassandra/io/compress/DeflateCompressor.java b/src/java/org/apache/cassandra/io/compress/DeflateCompressor.java index 1894f1141..ba5e83ab3 100644 --- a/src/java/org/apache/cassandra/io/compress/DeflateCompressor.java +++ b/src/java/org/apache/cassandra/io/compress/DeflateCompressor.java @@ -1,111 +1,111 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cassandra.io.compress; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.Inflater; public class DeflateCompressor implements ICompressor { public static final DeflateCompressor instance = new DeflateCompressor(); private final ThreadLocal<Deflater> deflater; private final ThreadLocal<Inflater> inflater; public static DeflateCompressor create(Map<String, String> compressionOptions) { // no specific options supported so far return instance; } private DeflateCompressor() { deflater = new ThreadLocal<Deflater>() { @Override protected Deflater initialValue() { return new Deflater(); } }; inflater = new ThreadLocal<Inflater>() { @Override protected Inflater initialValue() { return new Inflater(); } }; } public int initialCompressedBufferLength(int chunkLength) { return chunkLength; } public int compress(byte[] input, int inputOffset, int inputLength, ICompressor.WrappedArray output, int outputOffset) throws IOException { Deflater def = deflater.get(); def.reset(); def.setInput(input, inputOffset, inputLength); def.finish(); if (def.needsInput()) return 0; int offs = outputOffset; while (true) { offs += def.deflate(output.buffer, offs, output.buffer.length - offs); - if (def.needsInput()) + if (def.finished()) { return offs - outputOffset; } else { // We're not done, output was too small. Increase it and continue byte[] newBuffer = new byte[(output.buffer.length*4)/3 + 1]; System.arraycopy(output.buffer, 0, newBuffer, 0, offs); output.buffer = newBuffer; } } } public int uncompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws IOException { Inflater inf = inflater.get(); inf.reset(); inf.setInput(input, inputOffset, inputLength); if (inf.needsInput()) return 0; // We assume output is big enough try { return inf.inflate(output, outputOffset, output.length - outputOffset); } catch (DataFormatException e) { throw new IOException(e); } } }
true
true
public int compress(byte[] input, int inputOffset, int inputLength, ICompressor.WrappedArray output, int outputOffset) throws IOException { Deflater def = deflater.get(); def.reset(); def.setInput(input, inputOffset, inputLength); def.finish(); if (def.needsInput()) return 0; int offs = outputOffset; while (true) { offs += def.deflate(output.buffer, offs, output.buffer.length - offs); if (def.needsInput()) { return offs - outputOffset; } else { // We're not done, output was too small. Increase it and continue byte[] newBuffer = new byte[(output.buffer.length*4)/3 + 1]; System.arraycopy(output.buffer, 0, newBuffer, 0, offs); output.buffer = newBuffer; } } }
public int compress(byte[] input, int inputOffset, int inputLength, ICompressor.WrappedArray output, int outputOffset) throws IOException { Deflater def = deflater.get(); def.reset(); def.setInput(input, inputOffset, inputLength); def.finish(); if (def.needsInput()) return 0; int offs = outputOffset; while (true) { offs += def.deflate(output.buffer, offs, output.buffer.length - offs); if (def.finished()) { return offs - outputOffset; } else { // We're not done, output was too small. Increase it and continue byte[] newBuffer = new byte[(output.buffer.length*4)/3 + 1]; System.arraycopy(output.buffer, 0, newBuffer, 0, offs); output.buffer = newBuffer; } } }
diff --git a/samigo-app/src/java/com/corejsf/UploadRenderer.java b/samigo-app/src/java/com/corejsf/UploadRenderer.java index 6e0de815a..615c07387 100644 --- a/samigo-app/src/java/com/corejsf/UploadRenderer.java +++ b/samigo-app/src/java/com/corejsf/UploadRenderer.java @@ -1,124 +1,124 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * Copyright (c) 2004 Sun Microsystems from the Java Series, Core Java ServerFaces * source freely distributable. * see http://www.sun.com/books/java_series.html *********************************************************************************** * Modifications Copyright (c) 2005 * The Regents of the University of Michigan, Trustees of Indiana University, * Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation * * Licensed under the Educational Community License Version 1.0 (the "License"); * By obtaining, using and/or copying this Original Work, you agree that you have read, * understand, and will comply with the terms and conditions of the Educational Community License. * You may obtain a copy of the License at: * * http://cvs.sakaiproject.org/licenses/license_1_0.html * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **********************************************************************************/ package com.corejsf; import java.io.File; import java.io.IOException; import javax.servlet.ServletContext; import javax.faces.FacesException; import javax.faces.component.EditableValueHolder; import javax.faces.component.UIComponent; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.el.ValueBinding; import javax.faces.render.Renderer; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItem; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class UploadRenderer extends Renderer { private static Log log = LogFactory.getLog(UploadRenderer.class); private static final String UPLOAD = ".upload"; public UploadRenderer() { } public void encodeBegin(FacesContext context, UIComponent component) throws IOException { if (!component.isRendered()) return; ResponseWriter writer = context.getResponseWriter(); ExternalContext external = context.getExternalContext(); HttpServletRequest request = (HttpServletRequest) external.getRequest(); String clientId = component.getClientId(context); log.debug("** encodeBegin, clientId ="+clientId); encodeUploadField(writer, clientId, component); } public void encodeUploadField(ResponseWriter writer, String clientId, UIComponent component) throws IOException { // write <input type=file> for browsing and upload writer.startElement("input", component); writer.writeAttribute("type","file","type"); writer.writeAttribute("name",clientId + UPLOAD,"clientId"); writer.writeAttribute("size", "50", null); writer.endElement("input"); writer.flush(); } public void decode(FacesContext context, UIComponent component){ log.debug("**** decode ="); boolean mediaIsValid = true; ExternalContext external = context.getExternalContext(); HttpServletRequest request = (HttpServletRequest) external.getRequest(); String clientId = component.getClientId(context); FileItem item = (FileItem) request.getAttribute(clientId+UPLOAD); // check if file > maxSize allowed log.debug("clientId ="+ clientId); log.debug("fileItem ="+ item); // if (item!=null) log.debug("***UploadRender: fileItem size ="+ item.getSize()); Long maxSize = (Long)((ServletContext)external.getContext()).getAttribute("FILEUPLOAD_SIZE_MAX"); - if (item.getSize()/1000 > maxSize.intValue()){ + if (item!=null && item.getSize()/1000 > maxSize.intValue()){ ((ServletContext)external.getContext()).setAttribute("TEMP_FILEUPLOAD_SIZE", new Long(item.getSize()/1000)); mediaIsValid = false; } Object target; ValueBinding binding = component.getValueBinding("target"); if (binding != null) target = binding.getValue(context); else target = component.getAttributes().get("target"); String repositoryPath = (String)((ServletContext)external.getContext()).getAttribute("FILEUPLOAD_REPOSITORY_PATH"); log.debug("****"+repositoryPath); if (target != null){ File dir = new File(repositoryPath+target.toString()); //directory where file would be saved if (!dir.exists()) dir.mkdirs(); if (item!= null && !("").equals(item.getName())){ String filename = item.getName(); filename = filename.replace('\\','/'); // replace c:\filename to c:/filename filename = filename.substring(filename.lastIndexOf("/")+1); File file = new File(dir.getPath()+"/"+filename); log.debug("**1. filename="+file.getPath()); try { if (mediaIsValid) item.write(file); // change value so we can evoke the listener ((EditableValueHolder) component).setSubmittedValue(file.getPath()); } catch (Exception ex){ throw new FacesException(ex); } } } } }
true
true
public void decode(FacesContext context, UIComponent component){ log.debug("**** decode ="); boolean mediaIsValid = true; ExternalContext external = context.getExternalContext(); HttpServletRequest request = (HttpServletRequest) external.getRequest(); String clientId = component.getClientId(context); FileItem item = (FileItem) request.getAttribute(clientId+UPLOAD); // check if file > maxSize allowed log.debug("clientId ="+ clientId); log.debug("fileItem ="+ item); // if (item!=null) log.debug("***UploadRender: fileItem size ="+ item.getSize()); Long maxSize = (Long)((ServletContext)external.getContext()).getAttribute("FILEUPLOAD_SIZE_MAX"); if (item.getSize()/1000 > maxSize.intValue()){ ((ServletContext)external.getContext()).setAttribute("TEMP_FILEUPLOAD_SIZE", new Long(item.getSize()/1000)); mediaIsValid = false; } Object target; ValueBinding binding = component.getValueBinding("target"); if (binding != null) target = binding.getValue(context); else target = component.getAttributes().get("target"); String repositoryPath = (String)((ServletContext)external.getContext()).getAttribute("FILEUPLOAD_REPOSITORY_PATH"); log.debug("****"+repositoryPath); if (target != null){ File dir = new File(repositoryPath+target.toString()); //directory where file would be saved if (!dir.exists()) dir.mkdirs(); if (item!= null && !("").equals(item.getName())){ String filename = item.getName(); filename = filename.replace('\\','/'); // replace c:\filename to c:/filename filename = filename.substring(filename.lastIndexOf("/")+1); File file = new File(dir.getPath()+"/"+filename); log.debug("**1. filename="+file.getPath()); try { if (mediaIsValid) item.write(file); // change value so we can evoke the listener ((EditableValueHolder) component).setSubmittedValue(file.getPath()); } catch (Exception ex){ throw new FacesException(ex); } } } }
public void decode(FacesContext context, UIComponent component){ log.debug("**** decode ="); boolean mediaIsValid = true; ExternalContext external = context.getExternalContext(); HttpServletRequest request = (HttpServletRequest) external.getRequest(); String clientId = component.getClientId(context); FileItem item = (FileItem) request.getAttribute(clientId+UPLOAD); // check if file > maxSize allowed log.debug("clientId ="+ clientId); log.debug("fileItem ="+ item); // if (item!=null) log.debug("***UploadRender: fileItem size ="+ item.getSize()); Long maxSize = (Long)((ServletContext)external.getContext()).getAttribute("FILEUPLOAD_SIZE_MAX"); if (item!=null && item.getSize()/1000 > maxSize.intValue()){ ((ServletContext)external.getContext()).setAttribute("TEMP_FILEUPLOAD_SIZE", new Long(item.getSize()/1000)); mediaIsValid = false; } Object target; ValueBinding binding = component.getValueBinding("target"); if (binding != null) target = binding.getValue(context); else target = component.getAttributes().get("target"); String repositoryPath = (String)((ServletContext)external.getContext()).getAttribute("FILEUPLOAD_REPOSITORY_PATH"); log.debug("****"+repositoryPath); if (target != null){ File dir = new File(repositoryPath+target.toString()); //directory where file would be saved if (!dir.exists()) dir.mkdirs(); if (item!= null && !("").equals(item.getName())){ String filename = item.getName(); filename = filename.replace('\\','/'); // replace c:\filename to c:/filename filename = filename.substring(filename.lastIndexOf("/")+1); File file = new File(dir.getPath()+"/"+filename); log.debug("**1. filename="+file.getPath()); try { if (mediaIsValid) item.write(file); // change value so we can evoke the listener ((EditableValueHolder) component).setSubmittedValue(file.getPath()); } catch (Exception ex){ throw new FacesException(ex); } } } }
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java index 24bb7b78..a4f20181 100644 --- a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java +++ b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java @@ -1,236 +1,238 @@ /* * 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.inputmethod.latin; import android.content.ContentResolver; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; /** * Group class for static methods to help with creation and getting of the binary dictionary * file from the dictionary provider */ public class BinaryDictionaryFileDumper { private static final String TAG = BinaryDictionaryFileDumper.class.getSimpleName(); /** * The size of the temporary buffer to copy files. */ static final int FILE_READ_BUFFER_SIZE = 1024; private static final String DICTIONARY_PROJECTION[] = { "id" }; // Prevents this class to be accidentally instantiated. private BinaryDictionaryFileDumper() { } /** * Return for a given locale or dictionary id the provider URI to get the dictionary. */ private static Uri getProviderUri(String path) { return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) .authority(BinaryDictionary.DICTIONARY_PACK_AUTHORITY).appendPath( path).build(); } /** * Queries a content provider for the list of word lists for a specific locale * available to copy into Latin IME. */ private static List<String> getWordListIds(final Locale locale, final Context context) { final ContentResolver resolver = context.getContentResolver(); final Uri dictionaryPackUri = getProviderUri(locale.toString()); final Cursor c = resolver.query(dictionaryPackUri, DICTIONARY_PROJECTION, null, null, null); if (null == c) return Collections.<String>emptyList(); if (c.getCount() <= 0 || !c.moveToFirst()) { c.close(); return Collections.<String>emptyList(); } final List<String> list = new ArrayList<String>(); do { final String id = c.getString(0); if (TextUtils.isEmpty(id)) continue; list.add(id); } while (c.moveToNext()); c.close(); return list; } /** * Helper method to encapsulate exception handling. */ private static AssetFileDescriptor openAssetFileDescriptor(final ContentResolver resolver, final Uri uri) { try { return resolver.openAssetFileDescriptor(uri, "r"); } catch (FileNotFoundException e) { // I don't want to log the word list URI here for security concerns Log.e(TAG, "Could not find a word list from the dictionary provider."); return null; } } /** * Caches a word list the id of which is passed as an argument. This will write the file * to the cache file name designated by its id and locale, overwriting it if already present * and creating it (and its containing directory) if necessary. */ private static AssetFileAddress cacheWordList(final String id, final Locale locale, final ContentResolver resolver, final Context context) { final int COMPRESSED_CRYPTED_COMPRESSED = 0; final int CRYPTED_COMPRESSED = 1; final int COMPRESSED_CRYPTED = 2; final int COMPRESSED_ONLY = 3; final int CRYPTED_ONLY = 4; final int NONE = 5; final int MODE_MIN = COMPRESSED_CRYPTED_COMPRESSED; final int MODE_MAX = NONE; final Uri wordListUri = getProviderUri(id); final String outputFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context); for (int mode = MODE_MIN; mode <= MODE_MAX; ++mode) { InputStream originalSourceStream = null; InputStream inputStream = null; FileOutputStream outputStream = null; AssetFileDescriptor afd = null; try { // Open input. afd = openAssetFileDescriptor(resolver, wordListUri); // If we can't open it at all, don't even try a number of times. if (null == afd) return null; originalSourceStream = afd.createInputStream(); // Open output. outputStream = new FileOutputStream(outputFileName); // Get the appropriate decryption method for this try switch (mode) { case COMPRESSED_CRYPTED_COMPRESSED: inputStream = FileTransforms.getUncompressedStream( FileTransforms.getDecryptedStream( FileTransforms.getUncompressedStream( originalSourceStream))); break; case CRYPTED_COMPRESSED: inputStream = FileTransforms.getUncompressedStream( FileTransforms.getDecryptedStream(originalSourceStream)); break; case COMPRESSED_CRYPTED: inputStream = FileTransforms.getDecryptedStream( FileTransforms.getUncompressedStream(originalSourceStream)); break; case COMPRESSED_ONLY: inputStream = FileTransforms.getUncompressedStream(originalSourceStream); break; case CRYPTED_ONLY: inputStream = FileTransforms.getDecryptedStream(originalSourceStream); break; case NONE: inputStream = originalSourceStream; break; } copyFileTo(inputStream, outputStream); if (0 >= resolver.delete(wordListUri, null, null)) { Log.e(TAG, "Could not have the dictionary pack delete a word list"); } // Success! Close files (through the finally{} clause) and return. return AssetFileAddress.makeFromFileName(outputFileName); } catch (Exception e) { - Log.e(TAG, "Can't open word list in mode " + mode + " : " + e); + if (DEBUG) { + Log.i(TAG, "Can't open word list in mode " + mode + " : " + e); + } // Try the next method. } finally { // Ignore exceptions while closing files. try { // afd.close() will close inputStream, we should not call inputStream.close(). if (null != afd) afd.close(); } catch (Exception e) { Log.e(TAG, "Exception while closing a cross-process file descriptor : " + e); } try { if (null != outputStream) outputStream.close(); } catch (Exception e) { Log.e(TAG, "Exception while closing a file : " + e); } } } // We could not copy the file at all. This is very unexpected. // I'd rather not print the word list ID to the log out of security concerns Log.e(TAG, "Could not copy a word list. Will not be able to use it."); // If we can't copy it we should probably delete it to avoid trying to copy it over // and over each time we open LatinIME. if (0 >= resolver.delete(wordListUri, null, null)) { Log.e(TAG, "In addition, we were unable to delete it."); } return null; } /** * Queries a content provider for word list data for some locale and cache the returned files * * This will query a content provider for word list data for a given locale, and copy the * files locally so that they can be mmap'ed. This may overwrite previously cached word lists * with newer versions if a newer version is made available by the content provider. * @returns the addresses of the word list files, or null if no data could be obtained. * @throw FileNotFoundException if the provider returns non-existent data. * @throw IOException if the provider-returned data could not be read. */ public static List<AssetFileAddress> cacheWordListsFromContentProvider(final Locale locale, final Context context) { final ContentResolver resolver = context.getContentResolver(); final List<String> idList = getWordListIds(locale, context); final List<AssetFileAddress> fileAddressList = new ArrayList<AssetFileAddress>(); for (String id : idList) { final AssetFileAddress afd = cacheWordList(id, locale, resolver, context); if (null != afd) { fileAddressList.add(afd); } } return fileAddressList; } /** * Copies the data in an input stream to a target file. * @param input the stream to be copied. * @param outputFile an outputstream to copy the data to. */ private static void copyFileTo(final InputStream input, final FileOutputStream output) throws FileNotFoundException, IOException { final byte[] buffer = new byte[FILE_READ_BUFFER_SIZE]; for (int readBytes = input.read(buffer); readBytes >= 0; readBytes = input.read(buffer)) output.write(buffer, 0, readBytes); input.close(); } }
true
true
private static AssetFileAddress cacheWordList(final String id, final Locale locale, final ContentResolver resolver, final Context context) { final int COMPRESSED_CRYPTED_COMPRESSED = 0; final int CRYPTED_COMPRESSED = 1; final int COMPRESSED_CRYPTED = 2; final int COMPRESSED_ONLY = 3; final int CRYPTED_ONLY = 4; final int NONE = 5; final int MODE_MIN = COMPRESSED_CRYPTED_COMPRESSED; final int MODE_MAX = NONE; final Uri wordListUri = getProviderUri(id); final String outputFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context); for (int mode = MODE_MIN; mode <= MODE_MAX; ++mode) { InputStream originalSourceStream = null; InputStream inputStream = null; FileOutputStream outputStream = null; AssetFileDescriptor afd = null; try { // Open input. afd = openAssetFileDescriptor(resolver, wordListUri); // If we can't open it at all, don't even try a number of times. if (null == afd) return null; originalSourceStream = afd.createInputStream(); // Open output. outputStream = new FileOutputStream(outputFileName); // Get the appropriate decryption method for this try switch (mode) { case COMPRESSED_CRYPTED_COMPRESSED: inputStream = FileTransforms.getUncompressedStream( FileTransforms.getDecryptedStream( FileTransforms.getUncompressedStream( originalSourceStream))); break; case CRYPTED_COMPRESSED: inputStream = FileTransforms.getUncompressedStream( FileTransforms.getDecryptedStream(originalSourceStream)); break; case COMPRESSED_CRYPTED: inputStream = FileTransforms.getDecryptedStream( FileTransforms.getUncompressedStream(originalSourceStream)); break; case COMPRESSED_ONLY: inputStream = FileTransforms.getUncompressedStream(originalSourceStream); break; case CRYPTED_ONLY: inputStream = FileTransforms.getDecryptedStream(originalSourceStream); break; case NONE: inputStream = originalSourceStream; break; } copyFileTo(inputStream, outputStream); if (0 >= resolver.delete(wordListUri, null, null)) { Log.e(TAG, "Could not have the dictionary pack delete a word list"); } // Success! Close files (through the finally{} clause) and return. return AssetFileAddress.makeFromFileName(outputFileName); } catch (Exception e) { Log.e(TAG, "Can't open word list in mode " + mode + " : " + e); // Try the next method. } finally { // Ignore exceptions while closing files. try { // afd.close() will close inputStream, we should not call inputStream.close(). if (null != afd) afd.close(); } catch (Exception e) { Log.e(TAG, "Exception while closing a cross-process file descriptor : " + e); } try { if (null != outputStream) outputStream.close(); } catch (Exception e) { Log.e(TAG, "Exception while closing a file : " + e); } } } // We could not copy the file at all. This is very unexpected. // I'd rather not print the word list ID to the log out of security concerns Log.e(TAG, "Could not copy a word list. Will not be able to use it."); // If we can't copy it we should probably delete it to avoid trying to copy it over // and over each time we open LatinIME. if (0 >= resolver.delete(wordListUri, null, null)) { Log.e(TAG, "In addition, we were unable to delete it."); } return null; }
private static AssetFileAddress cacheWordList(final String id, final Locale locale, final ContentResolver resolver, final Context context) { final int COMPRESSED_CRYPTED_COMPRESSED = 0; final int CRYPTED_COMPRESSED = 1; final int COMPRESSED_CRYPTED = 2; final int COMPRESSED_ONLY = 3; final int CRYPTED_ONLY = 4; final int NONE = 5; final int MODE_MIN = COMPRESSED_CRYPTED_COMPRESSED; final int MODE_MAX = NONE; final Uri wordListUri = getProviderUri(id); final String outputFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context); for (int mode = MODE_MIN; mode <= MODE_MAX; ++mode) { InputStream originalSourceStream = null; InputStream inputStream = null; FileOutputStream outputStream = null; AssetFileDescriptor afd = null; try { // Open input. afd = openAssetFileDescriptor(resolver, wordListUri); // If we can't open it at all, don't even try a number of times. if (null == afd) return null; originalSourceStream = afd.createInputStream(); // Open output. outputStream = new FileOutputStream(outputFileName); // Get the appropriate decryption method for this try switch (mode) { case COMPRESSED_CRYPTED_COMPRESSED: inputStream = FileTransforms.getUncompressedStream( FileTransforms.getDecryptedStream( FileTransforms.getUncompressedStream( originalSourceStream))); break; case CRYPTED_COMPRESSED: inputStream = FileTransforms.getUncompressedStream( FileTransforms.getDecryptedStream(originalSourceStream)); break; case COMPRESSED_CRYPTED: inputStream = FileTransforms.getDecryptedStream( FileTransforms.getUncompressedStream(originalSourceStream)); break; case COMPRESSED_ONLY: inputStream = FileTransforms.getUncompressedStream(originalSourceStream); break; case CRYPTED_ONLY: inputStream = FileTransforms.getDecryptedStream(originalSourceStream); break; case NONE: inputStream = originalSourceStream; break; } copyFileTo(inputStream, outputStream); if (0 >= resolver.delete(wordListUri, null, null)) { Log.e(TAG, "Could not have the dictionary pack delete a word list"); } // Success! Close files (through the finally{} clause) and return. return AssetFileAddress.makeFromFileName(outputFileName); } catch (Exception e) { if (DEBUG) { Log.i(TAG, "Can't open word list in mode " + mode + " : " + e); } // Try the next method. } finally { // Ignore exceptions while closing files. try { // afd.close() will close inputStream, we should not call inputStream.close(). if (null != afd) afd.close(); } catch (Exception e) { Log.e(TAG, "Exception while closing a cross-process file descriptor : " + e); } try { if (null != outputStream) outputStream.close(); } catch (Exception e) { Log.e(TAG, "Exception while closing a file : " + e); } } } // We could not copy the file at all. This is very unexpected. // I'd rather not print the word list ID to the log out of security concerns Log.e(TAG, "Could not copy a word list. Will not be able to use it."); // If we can't copy it we should probably delete it to avoid trying to copy it over // and over each time we open LatinIME. if (0 >= resolver.delete(wordListUri, null, null)) { Log.e(TAG, "In addition, we were unable to delete it."); } return null; }
diff --git a/achartengine/src/org/achartengine/chart/BarChart.java b/achartengine/src/org/achartengine/chart/BarChart.java index bb4d927..fb3c695 100644 --- a/achartengine/src/org/achartengine/chart/BarChart.java +++ b/achartengine/src/org/achartengine/chart/BarChart.java @@ -1,312 +1,315 @@ /** * Copyright (C) 2009 - 2012 SC 4ViewSoft SRL * * 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.achartengine.chart; import org.achartengine.model.XYMultipleSeriesDataset; import org.achartengine.model.XYSeries; import org.achartengine.renderer.SimpleSeriesRenderer; import org.achartengine.renderer.XYMultipleSeriesRenderer; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.RectF; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.GradientDrawable.Orientation; /** * The bar chart rendering class. */ public class BarChart extends XYChart { /** The constant to identify this chart type. */ public static final String TYPE = "Bar"; /** The legend shape width. */ private static final int SHAPE_WIDTH = 12; /** The chart type. */ protected Type mType = Type.DEFAULT; /** * The bar chart type enum. */ public enum Type { DEFAULT, STACKED; } BarChart() { } /** * Builds a new bar chart instance. * * @param dataset the multiple series dataset * @param renderer the multiple series renderer * @param type the bar chart type */ public BarChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, Type type) { super(dataset, renderer); mType = type; } @Override protected ClickableArea[] clickableAreasForPoints(float[] points, double[] values, float yAxisValue, int seriesIndex, int startIndex) { int seriesNr = mDataset.getSeriesCount(); int length = points.length; ClickableArea[] ret = new ClickableArea[length / 2]; float halfDiffX = getHalfDiffX(points, length, seriesNr); for (int i = 0; i < length; i += 2) { float x = points[i]; float y = points[i + 1]; if (mType == Type.STACKED) { ret[i / 2] = new ClickableArea(new RectF(x - halfDiffX, y, x + halfDiffX, yAxisValue), values[i], values[i + 1]); } else { float startX = x - seriesNr * halfDiffX + seriesIndex * 2 * halfDiffX; ret[i / 2] = new ClickableArea(new RectF(startX, y, startX + 2 * halfDiffX, yAxisValue), values[i], values[i + 1]); } } return ret; } /** * The graphical representation of a series. * * @param canvas the canvas to paint to * @param paint the paint to be used for drawing * @param points the array of points to be used for drawing the series * @param seriesRenderer the series renderer * @param yAxisValue the minimum value of the y axis * @param seriesIndex the index of the series currently being drawn * @param startIndex the start index of the rendering points */ public void drawSeries(Canvas canvas, Paint paint, float[] points, SimpleSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, int startIndex) { int seriesNr = mDataset.getSeriesCount(); int length = points.length; paint.setColor(seriesRenderer.getColor()); paint.setStyle(Style.FILL); float halfDiffX = getHalfDiffX(points, length, seriesNr); for (int i = 0; i < length; i += 2) { float x = points[i]; float y = points[i + 1]; drawBar(canvas, x, yAxisValue, x, y, halfDiffX, seriesNr, seriesIndex, paint); } paint.setColor(seriesRenderer.getColor()); } /** * Draws a bar. * * @param canvas the canvas * @param xMin the X axis minimum * @param yMin the Y axis minimum * @param xMax the X axis maximum * @param yMax the Y axis maximum * @param halfDiffX half the size of a bar * @param seriesNr the total number of series * @param seriesIndex the current series index * @param paint the paint */ protected void drawBar(Canvas canvas, float xMin, float yMin, float xMax, float yMax, float halfDiffX, int seriesNr, int seriesIndex, Paint paint) { int scale = mDataset.getSeriesAt(seriesIndex).getScaleNumber(); if (mType == Type.STACKED) { drawBar(canvas, xMin - halfDiffX, yMax, xMax + halfDiffX, yMin, scale, seriesIndex, paint); } else { float startX = xMin - seriesNr * halfDiffX + seriesIndex * 2 * halfDiffX; drawBar(canvas, startX, yMax, startX + 2 * halfDiffX, yMin, scale, seriesIndex, paint); } } /** * Draws a bar. * * @param canvas the canvas * @param xMin the X axis minimum * @param yMin the Y axis minimum * @param xMax the X axis maximum * @param yMax the Y axis maximum * @param scale the scale index * @param seriesIndex the current series index * @param paint the paint */ private void drawBar(Canvas canvas, float xMin, float yMin, float xMax, float yMax, int scale, int seriesIndex, Paint paint) { SimpleSeriesRenderer renderer = mRenderer.getSeriesRendererAt(seriesIndex); if (renderer.isGradientEnabled()) { float minY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStopValue() }, scale)[1]; float maxY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStartValue() }, scale)[1]; float gradientMinY = Math.max(minY, yMin); float gradientMaxY = Math.min(maxY, yMax); int gradientMinColor = renderer.getGradientStopColor(); int gradientMaxColor = renderer.getGradientStartColor(); int gradientStartColor = gradientMaxColor; int gradientStopColor = gradientMinColor; if (yMin < minY) { paint.setColor(gradientMinColor); canvas.drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(gradientMinY), paint); } else { gradientStopColor = getGradientPartialColor(gradientMinColor, gradientMaxColor, (maxY - gradientMinY) / (maxY - minY)); } if (yMax > maxY) { paint.setColor(gradientMaxColor); canvas.drawRect(Math.round(xMin), Math.round(gradientMaxY), Math.round(xMax), Math.round(yMax), paint); } else { gradientStartColor = getGradientPartialColor(gradientMaxColor, gradientMinColor, (gradientMaxY - minY) / (maxY - minY)); } GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[] { gradientStartColor, gradientStopColor }); gradient.setBounds(Math.round(xMin), Math.round(gradientMinY), Math.round(xMax), Math.round(gradientMaxY)); gradient.draw(canvas); } else { + if (yMin == yMax) { + yMin = yMax - 1; + } canvas .drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(yMax), paint); } } private int getGradientPartialColor(int minColor, int maxColor, float fraction) { int alpha = Math.round(fraction * Color.alpha(minColor) + (1 - fraction) * Color.alpha(maxColor)); int r = Math.round(fraction * Color.red(minColor) + (1 - fraction) * Color.red(maxColor)); int g = Math.round(fraction * Color.green(minColor) + (1 - fraction) * Color.green(maxColor)); int b = Math.round(fraction * Color.blue(minColor) + (1 - fraction) * Color.blue((maxColor))); return Color.argb(alpha, r, g, b); } /** * The graphical representation of the series values as text. * * @param canvas the canvas to paint to * @param series the series to be painted * @param renderer the series renderer * @param paint the paint to be used for drawing * @param points the array of points to be used for drawing the series * @param seriesIndex the index of the series currently being drawn * @param startIndex the start index of the rendering points */ protected void drawChartValuesText(Canvas canvas, XYSeries series, SimpleSeriesRenderer renderer, Paint paint, float[] points, int seriesIndex, int startIndex) { int seriesNr = mDataset.getSeriesCount(); float halfDiffX = getHalfDiffX(points, points.length, seriesNr); for (int i = 0; i < points.length; i += 2) { int index = startIndex + i / 2; if (!isNullValue(series.getY(index))) { float x = points[i]; if (mType == Type.DEFAULT) { x += seriesIndex * 2 * halfDiffX - (seriesNr - 1.5f) * halfDiffX; } drawText(canvas, getLabel(series.getY(index)), x, points[i + 1] - renderer.getChartValuesSpacing(), paint, 0); } } } /** * Returns the legend shape width. * * @param seriesIndex the series index * @return the legend shape width */ public int getLegendShapeWidth(int seriesIndex) { return SHAPE_WIDTH; } /** * The graphical representation of the legend shape. * * @param canvas the canvas to paint to * @param renderer the series renderer * @param x the x value of the point the shape should be drawn at * @param y the y value of the point the shape should be drawn at * @param seriesIndex the series index * @param paint the paint to be used for drawing */ public void drawLegendShape(Canvas canvas, SimpleSeriesRenderer renderer, float x, float y, int seriesIndex, Paint paint) { float halfShapeWidth = SHAPE_WIDTH / 2; canvas.drawRect(x, y - halfShapeWidth, x + SHAPE_WIDTH, y + halfShapeWidth, paint); } /** * Calculates and returns the half-distance in the graphical representation of * 2 consecutive points. * * @param points the points * @param length the points length * @param seriesNr the series number * @return the calculated half-distance value */ protected float getHalfDiffX(float[] points, int length, int seriesNr) { int div = length; if (length > 2) { div = length - 2; } float halfDiffX = (points[length - 2] - points[0]) / div; if (halfDiffX == 0) { halfDiffX = 10; } if (mType != Type.STACKED) { halfDiffX /= seriesNr; } return (float) (halfDiffX / (getCoeficient() * (1 + mRenderer.getBarSpacing()))); } /** * Returns the value of a constant used to calculate the half-distance. * * @return the constant value */ protected float getCoeficient() { return 1f; } /** * Returns if the chart should display the null values. * * @return if null values should be rendered */ protected boolean isRenderNullValues() { return true; } /** * Returns the default axis minimum. * * @return the default axis minimum */ public double getDefaultMinimum() { return 0; } /** * Returns the chart type identifier. * * @return the chart type */ public String getChartType() { return TYPE; } }
true
true
private void drawBar(Canvas canvas, float xMin, float yMin, float xMax, float yMax, int scale, int seriesIndex, Paint paint) { SimpleSeriesRenderer renderer = mRenderer.getSeriesRendererAt(seriesIndex); if (renderer.isGradientEnabled()) { float minY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStopValue() }, scale)[1]; float maxY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStartValue() }, scale)[1]; float gradientMinY = Math.max(minY, yMin); float gradientMaxY = Math.min(maxY, yMax); int gradientMinColor = renderer.getGradientStopColor(); int gradientMaxColor = renderer.getGradientStartColor(); int gradientStartColor = gradientMaxColor; int gradientStopColor = gradientMinColor; if (yMin < minY) { paint.setColor(gradientMinColor); canvas.drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(gradientMinY), paint); } else { gradientStopColor = getGradientPartialColor(gradientMinColor, gradientMaxColor, (maxY - gradientMinY) / (maxY - minY)); } if (yMax > maxY) { paint.setColor(gradientMaxColor); canvas.drawRect(Math.round(xMin), Math.round(gradientMaxY), Math.round(xMax), Math.round(yMax), paint); } else { gradientStartColor = getGradientPartialColor(gradientMaxColor, gradientMinColor, (gradientMaxY - minY) / (maxY - minY)); } GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[] { gradientStartColor, gradientStopColor }); gradient.setBounds(Math.round(xMin), Math.round(gradientMinY), Math.round(xMax), Math.round(gradientMaxY)); gradient.draw(canvas); } else { canvas .drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(yMax), paint); } }
private void drawBar(Canvas canvas, float xMin, float yMin, float xMax, float yMax, int scale, int seriesIndex, Paint paint) { SimpleSeriesRenderer renderer = mRenderer.getSeriesRendererAt(seriesIndex); if (renderer.isGradientEnabled()) { float minY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStopValue() }, scale)[1]; float maxY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStartValue() }, scale)[1]; float gradientMinY = Math.max(minY, yMin); float gradientMaxY = Math.min(maxY, yMax); int gradientMinColor = renderer.getGradientStopColor(); int gradientMaxColor = renderer.getGradientStartColor(); int gradientStartColor = gradientMaxColor; int gradientStopColor = gradientMinColor; if (yMin < minY) { paint.setColor(gradientMinColor); canvas.drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(gradientMinY), paint); } else { gradientStopColor = getGradientPartialColor(gradientMinColor, gradientMaxColor, (maxY - gradientMinY) / (maxY - minY)); } if (yMax > maxY) { paint.setColor(gradientMaxColor); canvas.drawRect(Math.round(xMin), Math.round(gradientMaxY), Math.round(xMax), Math.round(yMax), paint); } else { gradientStartColor = getGradientPartialColor(gradientMaxColor, gradientMinColor, (gradientMaxY - minY) / (maxY - minY)); } GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[] { gradientStartColor, gradientStopColor }); gradient.setBounds(Math.round(xMin), Math.round(gradientMinY), Math.round(xMax), Math.round(gradientMaxY)); gradient.draw(canvas); } else { if (yMin == yMax) { yMin = yMax - 1; } canvas .drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(yMax), paint); } }
diff --git a/java/src/eu/semaine/components/dialogue/actionproposers/UtteranceProposer.java b/java/src/eu/semaine/components/dialogue/actionproposers/UtteranceProposer.java index e70fd10a..cd3734d6 100644 --- a/java/src/eu/semaine/components/dialogue/actionproposers/UtteranceProposer.java +++ b/java/src/eu/semaine/components/dialogue/actionproposers/UtteranceProposer.java @@ -1,689 +1,704 @@ /** * Copyright (C) 2008 University of Twente, HMI. All rights reserved. * Use is subject to license terms -- see license.txt. */ package eu.semaine.components.dialogue.actionproposers; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import javax.jms.JMSException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import eu.semaine.components.Component; import eu.semaine.components.dialogue.util.DialogueAct; import eu.semaine.jms.message.SEMAINEEmmaMessage; import eu.semaine.jms.message.SEMAINEMessage; import eu.semaine.jms.message.SEMAINEXMLMessage; import eu.semaine.jms.receiver.EmmaReceiver; import eu.semaine.jms.receiver.UserStateReceiver; import eu.semaine.jms.receiver.XMLReceiver; import eu.semaine.jms.sender.FMLSender; import eu.semaine.datatypes.xml.BML; import eu.semaine.datatypes.xml.FML; import eu.semaine.datatypes.xml.SSML; import eu.semaine.datatypes.xml.SemaineML; import eu.semaine.util.XMLTool; /** * This class waits for the Agent to have the turn, takes the analysis of the user input * and chooses a response for the agent * * @author Mark tM * @version 0.1 - dummy class * */ public class UtteranceProposer extends Component { /* A representation of the four characters */ private enum Personality {Poppy, Obadiah, Spike, Prudence} /* The minimum number of sentences before a sentence can be repeated */ private static final int MIN_REPEAT_RATE = 10; /* The files with the response-model */ private String contextFile = "/eu/semaine/components/dialogue/data/Context.csv"; private String groupFile = "/eu/semaine/components/dialogue/data/SentenceGroups.xml"; /* The current personality */ private Personality currPersonality; /* The number of responses the current personality has uttered so far */ private int personalityConversationLength = 0; /* The number of sentences since a new topic was introduced by SAL */ private int newTopicSentenceCount = 0; /* The personality the user wants to talk to next */ private Personality nextPersonality = null; /* A history of all personalities if they have talked or not */ private HashMap<Personality, Boolean> personalityHistory = new HashMap<Personality, Boolean>(); /* * The conversation state * 0 - Neutral state * 1 - Start of character, name asked * 2 - Character has started and asked for a name * 7 - Character has started and asked 'how are you' * 3 - System decision change of speaker made * 4 - System decision change of speaker made and a character will be suggested * 5 - User has desire to talk to another character, a character is asked * 6 - User has desire to talk to another character, a character is suggested */ private int convState = 1; /* For random data */ private Random rand = new Random(); /* A list with all context-templates, used for picking a response */ private ArrayList<ContextTemplate> templates ; /* A map with all response-groups plus its corresponding utterances */ private HashMap<String,ArrayList<String>> groupData; /* The response-history */ private ArrayList<String> pastResponses = new ArrayList<String>(); /* A list with sentences which can be uttered always */ private ArrayList<String> safeResponses = new ArrayList<String>(); /* Receivers and Senders */ //private UserStateReceiver userStateReceiver; //private EmmaReceiver emmaReceiver; private XMLReceiver userStateReceiver; private FMLSender fmlSender; /** * Creates a new UtteranceProposer * + Creates the Senders and Receivers * + Import response-model data * + Sets a random starting personality * @throws JMSException */ public UtteranceProposer() throws JMSException { super("UtteranceProposer"); /* Creates the Senders and Receivers */ // emmaReceiver = new EmmaReceiver("semaine.data.state.user", "datatype = 'EMMA'"); // receivers.add(emmaReceiver); // userStateReceiver = new UserStateReceiver("semaine.data.state.user", "datatype = 'UserState'"); // receivers.add(userStateReceiver); userStateReceiver = new XMLReceiver("semaine.data.state.user.behaviour", ""); receivers.add(userStateReceiver); fmlSender = new FMLSender("semaine.data.action.candidate.function", getName()); senders.add(fmlSender); // so it can be started etc /* Import response-model data */ DataImporter importer = new DataImporter( contextFile, groupFile ); templates = importer.importContextData(); groupData = importer.importGroupData(); /* Initialize some lists */ safeResponses.add("*Group* Start new subject"); safeResponses.add("*Group* Tell me more"); personalityHistory.put( Personality.Poppy, false ); personalityHistory.put( Personality.Obadiah, false ); personalityHistory.put( Personality.Spike, false ); personalityHistory.put( Personality.Prudence, false ); /* Set a random starting personality */ currPersonality = choosePersonality(); } /** * Starts the conversation if this is called for the first time */ @Override protected void act( ) throws JMSException { if( pastResponses.size() == 0 && startOfConversation() ) { personalityConversationLength = 0; return; } } /** * Called when a new message arrives * Checks whether the message is an EmmaMessage containing processed input. * If so, then it will use this input to pick a response */ @Override protected void react(SEMAINEMessage m) throws JMSException { if( m instanceof SEMAINEXMLMessage ) { SEMAINEXMLMessage xml = (SEMAINEXMLMessage)m; Element text = XMLTool.getChildElementByTagNameNS(xml.getDocument().getDocumentElement(), SemaineML.E_TEXT, SemaineML.namespaceURI); if( text != null ) { String utterance = text.getTextContent(); DialogueAct act = new DialogueAct(utterance); if( act != null ) { List<Element> features = XMLTool.getChildrenByTagNameNS(text, SemaineML.E_FEATURE, SemaineML.namespaceURI); for( Element feature : features ) { String f = feature.getAttribute( "name" ); if( f.equals("positive") ) act.setPositive(true); if( f.equals("negative") ) act.setNegative(true); if( f.equals("agree") ) act.setAgree(true); if( f.equals("disagree") ) act.setDisagree(true); if( f.equals("about other people") ) act.setAboutOtherPeople(true); if( f.equals("about other character") ) act.setAboutOtherCharacter(true); if( f.equals("about current character") ) act.setAboutCurrentCharacter(true); if( f.equals("about own feelings") ) act.setAboutOwnFeelings(true); if( f.equals("pragmatic") ) act.setPragmatic(true); if( f.equals("about self") ) act.setTalkAboutSelf(true); if( f.equals("future") ) act.setFuture(true); if( f.equals("past") ) act.setPast(true); if( f.equals("event") ) act.setEvent(true); if( f.equals("action") ) act.setAction(true); if( f.equals("laugh") ) act.setLaugh(true); if( f.equals("change speaker") ) act.setChangeSpeaker(true); if( f.equals("target character") ) act.setTargetCharacter( feature.getAttribute("target") ); } pickResponse(act); } } } // if( m instanceof SEMAINEEmmaMessage ) { // SEMAINEEmmaMessage em = (SEMAINEEmmaMessage)m; // Element interpretation = em.getTopLevelInterpretation(); // if ( interpretation != null && interpretation.getAttribute("processed").equals("true") ) { // List<Element> texts = em.getTextElements(interpretation); // DialogueAct act = null; // for (Element text : texts) { // String utterance = text.getTextContent(); // if( utterance != null ) { // act = new DialogueAct(utterance); // } // } // if( act != null ) { // List<Element> features = em.getFeatureElements( interpretation ); // for( Element feature : features ) { // String f = feature.getAttribute( "name" ); // if( f.equals("positive") ) act.setPositive(true); // if( f.equals("negative") ) act.setNegative(true); // if( f.equals("agree") ) act.setAgree(true); // if( f.equals("disagree") ) act.setDisagree(true); // if( f.equals("about other people") ) act.setAboutOtherPeople(true); // if( f.equals("about other character") ) act.setAboutOtherCharacter(true); // if( f.equals("about current character") ) act.setAboutCurrentCharacter(true); // if( f.equals("about own feelings") ) act.setAboutOwnFeelings(true); // if( f.equals("pragmatic") ) act.setPragmatic(true); // if( f.equals("about self") ) act.setTalkAboutSelf(true); // if( f.equals("future") ) act.setFuture(true); // if( f.equals("past") ) act.setPast(true); // if( f.equals("event") ) act.setEvent(true); // if( f.equals("action") ) act.setAction(true); // if( f.equals("laugh") ) act.setLaugh(true); // if( f.equals("change speaker") ) act.setChangeSpeaker(true); // if( f.equals("target character") ) act.setTargetCharacter( feature.getAttribute("target") ); // } // System.out.println("Choosing response"); // pickResponse(act); // } // } // } } /** * Tries to pick a response based on the given DialogueAct (which contains * of the detected utterance + detected features) * @param act * @throws JMSException */ public void pickResponse( DialogueAct act ) throws JMSException { if( changeOfCharacter(act) ) { return; } if( startOfConversation() ) { personalityConversationLength = 0; return; } personalityConversationLength++; HashMap<String,Integer> scores = giveResponseRatings(act); String reaction; int maxReactions = 4; int firstScore = -1; int latestScore = -1; ArrayList<String> bestResponses = new ArrayList<String>(); while( scores.keySet().size()>0 && ( bestResponses.size() < maxReactions || ( bestResponses.size() > maxReactions && latestScore == firstScore ) ) ) { reaction = getMaxScorer( scores ); if( firstScore == -1 ) { firstScore = scores.get(reaction); } if( ! pastResponses.contains(reaction) ) { latestScore = scores.get(reaction); bestResponses.add(reaction); } System.out.println("- "+scores.get(reaction) + " - " + reaction); scores.remove(reaction); } String response = bestResponses.get( rand.nextInt( bestResponses.size() ) ); if( firstScore <= 0 ) { response = safeResponses.get( rand.nextInt(safeResponses.size()) ); while( pastResponses.contains(response) || (newTopicSentenceCount < 3 && response.equals("*Group* Start new subject")) ) { response = safeResponses.get( rand.nextInt(safeResponses.size()) ); } } if( groupData.containsKey(currPersonality+":"+response) ) { ArrayList<String> options = new ArrayList<String>(groupData.get(currPersonality+":"+response)); response = options.get( rand.nextInt(options.size()) ); while( pastResponses.contains(response) && options.size() > 1) { options.remove(response); response = options.get( rand.nextInt(options.size()) ); } } while( pastResponses.size() > MIN_REPEAT_RATE ) { pastResponses.remove(0); } newTopicSentenceCount++; respond(response); } /** * Regulates the start of a conversation (done at the start of each * character) * @return * @throws JMSException */ public boolean startOfConversation( ) throws JMSException { if( convState == 1 ) { String response = ""; if( currPersonality == Personality.Poppy ) { if( personalityHistory.get( Personality.Poppy ) ) { // Character has talked before response = "Hi! I'm Poppy. How are you?"; convState = 0; } else { // Character hasn't talked before response = "Hi, I'm Poppy, the eternal optimist. What's your name? "; convState = 2; } } else if( currPersonality == Personality.Obadiah ) { if( personalityHistory.get( Personality.Obadiah ) ) { // Character has talked before response = "Hello, I'm Obidiah. What's the matter?"; convState = 0; } else { // Character hasn't talked before response = "Hello, my name is Obadiah, and I'm feeling very depressed right now. And who are you?"; convState = 2; } } else if( currPersonality == Personality.Spike ) { if( personalityHistory.get( Personality.Spike ) ) { // Character has talked before response = "Well I'm Spike, what's your problem?"; convState = 0; } else { // Character hasn't talked before response = "I'm Spike and I've a bit of a temper. Who are you?"; convState = 2; } } else if( currPersonality == Personality.Prudence ) { if( personalityHistory.get( Personality.Prudence ) ) { // Character has talked before response = "Hello, it's Prudence. What would you like to talk about?"; convState = 0; } else { // Character hasn't talked before response = "Hello there, I'm Prudence and I'm very matter of fact. So tell me, what is your name?"; convState = 2; } } respond(response); return true; } if( convState == 2 ) { String response = ""; if( currPersonality == Personality.Poppy ) { response = "Ok, and how are you today?"; convState = 7; } else if( currPersonality == Personality.Obadiah ) { response = "Ah. So how are you feeling today? Not great I suppose."; convState = 7; } else if( currPersonality == Personality.Spike ) { response = "And what state are you in today?"; convState = 7; } else if( currPersonality == Personality.Prudence ) { response = "I see. And how are you today?"; convState = 7; } respond(response); return true; } if( convState == 7 ) { String response = ""; if( currPersonality == Personality.Poppy ) { response = "Is that so ' tell me about it"; convState = 0; } else if( currPersonality == Personality.Obadiah ) { response = "Is that so - Tell me more about it "; convState = 0; } else if( currPersonality == Personality.Spike ) { response = "Is that so - Tell me more about it "; convState = 0; } else if( currPersonality == Personality.Prudence ) { response = "Is that so - Tell me more about it "; convState = 0; } respond(response); return true; } return false; } /** * Regulates the process of changing the character * @param act * @return * @throws JMSException */ public boolean changeOfCharacter( DialogueAct act ) throws JMSException { String response = null; if( convState == 0 && systemWantsSpeakerChange() ) { if( rand.nextBoolean() ) { response = "Would you like to talk to someone else?"; convState = 3; } else { nextPersonality = choosePersonality(); response = "Why don't you talk to " + nextPersonality + "?"; convState = 4; } } else if( convState == 0 && act.isChangeSpeaker() && act.getTargetCharacter() == null ) { if( rand.nextBoolean() ) { response = "Who would you like to talk to?"; convState = 5; } else { nextPersonality = choosePersonality(); response = "Why don't you talk to " + nextPersonality + "?"; convState = 6; } } else if( convState == 0 && act.isChangeSpeaker() && act.getTargetCharacter() != null ) { response = null; currPersonality = getPersonality( act.getTargetCharacter() ); convState = 1; return false; } else if( convState == 3 && act.isDisagree() ) { convState = 0; } else if( convState == 3 && act.isAgree() ) { if( act.getTargetCharacter() == null ) { if( rand.nextBoolean() ) { response = "Who would you like to talk to?"; convState = 5; } else { nextPersonality = choosePersonality(); response = "Why don't you talk to " + nextPersonality + "?"; convState = 6; } } else { response = null; currPersonality = getPersonality( act.getTargetCharacter() ); convState = 1; return false; } } else if( convState == 3 ) { - response = "I'm sorry, I didn't understand that."; + if( !pastResponses.get(pastResponses.size()-1).equals("I'm sorry, I didn't understand that.") ) { + response = "I'm sorry, I didn't understand that."; + } else { + convState = 0; + return false; + } }else if( convState == 4 && act.isDisagree() ) { response = "Would you like to talk to someone else?"; nextPersonality = null; convState = 3; } else if( convState == 4 && act.isAgree() ) { response = null; currPersonality = nextPersonality; nextPersonality = null; convState = 1; return false; } else if( convState == 4 ) { - response = "I'm sorry, I didn't understand that."; + if( !pastResponses.get(pastResponses.size()-1).equals("I'm sorry, I didn't understand that.") ) { + response = "I'm sorry, I didn't understand that."; + } else { + convState = 0; + return false; + } } else if( convState == 5 ) { if( act.getTargetCharacter() != null ) { response = null; currPersonality = getPersonality( act.getTargetCharacter() ); convState = 1; return false; } else { response = "I'm sorry, who do you want to talk to?"; } } else if( convState == 6 ) { if( act.isDisagree() ) { if( act.getTargetCharacter() != null ) { response = null; currPersonality = getPersonality( act.getTargetCharacter() ); nextPersonality = null; convState = 1; return false; } else { response = "Then who would you like to talk to?"; nextPersonality = null; convState = 5; } } else if( act.isAgree() ) { response = null; currPersonality = nextPersonality; convState = 1; return false; } else { - response = "I'm sorry, I didn't understand that."; + if( !pastResponses.get(pastResponses.size()-1).equals("I'm sorry, I didn't understand that.") ) { + response = "I'm sorry, I didn't understand that."; + } else { + convState = 0; + return false; + } } } if( response != null ) { respond(response); return true; } else { return false; } } /** * @return true if the System decides to change the speaker * TODO: implement */ public boolean systemWantsSpeakerChange() { if( personalityConversationLength >= 10 ) { if( rand.nextInt(3) == 0 ) { return true; } } return false; } /** * Returns a map with all possible responses plus the ratings of those * responses (based on the response model) * @param act * @return */ public HashMap<String,Integer> giveResponseRatings( DialogueAct act ) { ArrayList<Integer> props = new ArrayList<Integer>(); HashMap<String,Integer> scores = new HashMap<String, Integer>(); if( currPersonality == Personality.Poppy ) { props.add( 1 ); }else if( currPersonality == Personality.Obadiah ) { props.add( 2 ); } else if( currPersonality == Personality.Prudence ) { props.add( 3 ); } else if( currPersonality == Personality.Spike ) { props.add( 4 ); } if( act.isPositive() ) props.add( 8 ); if( act.isNegative() ) props.add( 9 ); if( act.isAgree() ) props.add( 10 ); if( act.isDisagree() ) props.add( 11 ); if( act.isAboutOtherPeople() ) props.add( 12 ); if( act.isAboutOtherCharacter() ) props.add( 13 ); if( act.isAboutCurrentCharacter() ) props.add( 14 ); if( act.isAboutOwnFeelings() ) props.add( 15 ); if( act.isPragmatic() ) props.add( 16 ); if( act.isTalkAboutSelf() ) props.add( 17 ); if( act.isPast() && act.isEvent() ) props.add( 18 ); if( act.isFuture() && act.isEvent() ) props.add( 19 ); if( act.isPast() && act.isAction() ) props.add( 20 ); if( act.isFuture() && act.isAction() ) props.add( 21 ); if( act.isLaugh() ) props.add( 22 ); int score; for( ContextTemplate template : templates ) { ArrayList<Integer> required = template.getRequiredFeatures(); ArrayList<Integer> optional = template.getExtraFeatures(); score = 10; String reaction = template.getReaction(); for( int feature : props ) { if( !required.contains(feature) && !optional.contains(feature) ) { score -= 2; } } for( int feature : required ) { if( !props.contains(feature) ) { score -= 10; } } for( int feature : optional ) { if( !props.contains(feature) ) { score -= 1; } } if( ! scores.containsKey(reaction) || scores.get(reaction) < score ) { scores.put(reaction, score); } } return scores; } /** * Returns the best possible utterance from the given map with responses and scores * @param scores * @return */ public String getMaxScorer( HashMap<String, Integer> scores ) { String maxString = ""; int maxScore = -99; for( Map.Entry<String,Integer> entry : scores.entrySet() ) { if( entry.getValue() > maxScore ) { maxString = entry.getKey(); maxScore = scores.get(entry.getKey()); } } return maxString; } /** * Returns a random personality * @return */ public Personality choosePersonality() { Personality p = currPersonality; while( p == currPersonality ) { switch( rand.nextInt(4) ) { case 0: p = Personality.Poppy; break; case 1: p = Personality.Obadiah; break; case 2: p = Personality.Spike; break; case 3: p = Personality.Prudence; break; } } return p; } /** * Returns the Personality based on the String representation of the character * @param p * @return */ public Personality getPersonality( String p ) { p = p.toLowerCase(); if( p.equals("poppy") ) { return Personality.Poppy; } else if( p.equals("obadiah") ) { return Personality.Obadiah; } else if( p.equals("spike") ) { return Personality.Spike; } else if( p.equals("prudence") ) { return Personality.Prudence; } else { return null; } } /** * Sends the chosen response to the FML-channel * @param response * @throws JMSException */ public void respond( String response ) throws JMSException { String id = "s1"; pastResponses.add(response); Document doc = XMLTool.newDocument("fml-apml", null, FML.version); Element root = doc.getDocumentElement(); Element bml = XMLTool.appendChildElement(root, BML.E_BML, BML.namespaceURI); bml.setAttribute(BML.A_ID, "bml1"); Element fml = XMLTool.appendChildElement(root, FML.E_FML, FML.namespaceURI); fml.setAttribute(FML.A_ID, "fml1"); Element speech = XMLTool.appendChildElement(bml, BML.E_SPEECH); speech.setAttribute(BML.A_ID, id); speech.setAttribute(BML.E_TEXT, response); speech.setAttribute(BML.E_LANGUAGE, "en_US"); //speech.setTextContent(response); int counter=1; for( String word : response.split(" ") ) { Element mark = XMLTool.appendChildElement(speech, SSML.E_MARK, SSML.namespaceURI); mark.setAttribute(SSML.A_NAME, id+":tm"+counter); Node text = doc.createTextNode(word); speech.appendChild(text); counter++; } Element mark = XMLTool.appendChildElement(speech, SSML.E_MARK); mark.setAttribute(SSML.A_NAME, id+":tm"+counter); fmlSender.sendXML(doc, meta.getTime()); } }
false
true
public boolean changeOfCharacter( DialogueAct act ) throws JMSException { String response = null; if( convState == 0 && systemWantsSpeakerChange() ) { if( rand.nextBoolean() ) { response = "Would you like to talk to someone else?"; convState = 3; } else { nextPersonality = choosePersonality(); response = "Why don't you talk to " + nextPersonality + "?"; convState = 4; } } else if( convState == 0 && act.isChangeSpeaker() && act.getTargetCharacter() == null ) { if( rand.nextBoolean() ) { response = "Who would you like to talk to?"; convState = 5; } else { nextPersonality = choosePersonality(); response = "Why don't you talk to " + nextPersonality + "?"; convState = 6; } } else if( convState == 0 && act.isChangeSpeaker() && act.getTargetCharacter() != null ) { response = null; currPersonality = getPersonality( act.getTargetCharacter() ); convState = 1; return false; } else if( convState == 3 && act.isDisagree() ) { convState = 0; } else if( convState == 3 && act.isAgree() ) { if( act.getTargetCharacter() == null ) { if( rand.nextBoolean() ) { response = "Who would you like to talk to?"; convState = 5; } else { nextPersonality = choosePersonality(); response = "Why don't you talk to " + nextPersonality + "?"; convState = 6; } } else { response = null; currPersonality = getPersonality( act.getTargetCharacter() ); convState = 1; return false; } } else if( convState == 3 ) { response = "I'm sorry, I didn't understand that."; }else if( convState == 4 && act.isDisagree() ) { response = "Would you like to talk to someone else?"; nextPersonality = null; convState = 3; } else if( convState == 4 && act.isAgree() ) { response = null; currPersonality = nextPersonality; nextPersonality = null; convState = 1; return false; } else if( convState == 4 ) { response = "I'm sorry, I didn't understand that."; } else if( convState == 5 ) { if( act.getTargetCharacter() != null ) { response = null; currPersonality = getPersonality( act.getTargetCharacter() ); convState = 1; return false; } else { response = "I'm sorry, who do you want to talk to?"; } } else if( convState == 6 ) { if( act.isDisagree() ) { if( act.getTargetCharacter() != null ) { response = null; currPersonality = getPersonality( act.getTargetCharacter() ); nextPersonality = null; convState = 1; return false; } else { response = "Then who would you like to talk to?"; nextPersonality = null; convState = 5; } } else if( act.isAgree() ) { response = null; currPersonality = nextPersonality; convState = 1; return false; } else { response = "I'm sorry, I didn't understand that."; } } if( response != null ) { respond(response); return true; } else { return false; } }
public boolean changeOfCharacter( DialogueAct act ) throws JMSException { String response = null; if( convState == 0 && systemWantsSpeakerChange() ) { if( rand.nextBoolean() ) { response = "Would you like to talk to someone else?"; convState = 3; } else { nextPersonality = choosePersonality(); response = "Why don't you talk to " + nextPersonality + "?"; convState = 4; } } else if( convState == 0 && act.isChangeSpeaker() && act.getTargetCharacter() == null ) { if( rand.nextBoolean() ) { response = "Who would you like to talk to?"; convState = 5; } else { nextPersonality = choosePersonality(); response = "Why don't you talk to " + nextPersonality + "?"; convState = 6; } } else if( convState == 0 && act.isChangeSpeaker() && act.getTargetCharacter() != null ) { response = null; currPersonality = getPersonality( act.getTargetCharacter() ); convState = 1; return false; } else if( convState == 3 && act.isDisagree() ) { convState = 0; } else if( convState == 3 && act.isAgree() ) { if( act.getTargetCharacter() == null ) { if( rand.nextBoolean() ) { response = "Who would you like to talk to?"; convState = 5; } else { nextPersonality = choosePersonality(); response = "Why don't you talk to " + nextPersonality + "?"; convState = 6; } } else { response = null; currPersonality = getPersonality( act.getTargetCharacter() ); convState = 1; return false; } } else if( convState == 3 ) { if( !pastResponses.get(pastResponses.size()-1).equals("I'm sorry, I didn't understand that.") ) { response = "I'm sorry, I didn't understand that."; } else { convState = 0; return false; } }else if( convState == 4 && act.isDisagree() ) { response = "Would you like to talk to someone else?"; nextPersonality = null; convState = 3; } else if( convState == 4 && act.isAgree() ) { response = null; currPersonality = nextPersonality; nextPersonality = null; convState = 1; return false; } else if( convState == 4 ) { if( !pastResponses.get(pastResponses.size()-1).equals("I'm sorry, I didn't understand that.") ) { response = "I'm sorry, I didn't understand that."; } else { convState = 0; return false; } } else if( convState == 5 ) { if( act.getTargetCharacter() != null ) { response = null; currPersonality = getPersonality( act.getTargetCharacter() ); convState = 1; return false; } else { response = "I'm sorry, who do you want to talk to?"; } } else if( convState == 6 ) { if( act.isDisagree() ) { if( act.getTargetCharacter() != null ) { response = null; currPersonality = getPersonality( act.getTargetCharacter() ); nextPersonality = null; convState = 1; return false; } else { response = "Then who would you like to talk to?"; nextPersonality = null; convState = 5; } } else if( act.isAgree() ) { response = null; currPersonality = nextPersonality; convState = 1; return false; } else { if( !pastResponses.get(pastResponses.size()-1).equals("I'm sorry, I didn't understand that.") ) { response = "I'm sorry, I didn't understand that."; } else { convState = 0; return false; } } } if( response != null ) { respond(response); return true; } else { return false; } }
diff --git a/modules/plugin/arcsde/datastore/src/main/java/org/geotools/arcsde/pool/ArcSDEConnectionConfig.java b/modules/plugin/arcsde/datastore/src/main/java/org/geotools/arcsde/pool/ArcSDEConnectionConfig.java index 175768831..9f5176b36 100644 --- a/modules/plugin/arcsde/datastore/src/main/java/org/geotools/arcsde/pool/ArcSDEConnectionConfig.java +++ b/modules/plugin/arcsde/datastore/src/main/java/org/geotools/arcsde/pool/ArcSDEConnectionConfig.java @@ -1,153 +1,153 @@ /* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2002-2008, Open Source Geospatial Foundation (OSGeo) * * 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package org.geotools.arcsde.pool; /** * Represents a set of ArcSDE database connection parameters. * * @author Gabriel Roldan * @version $Id$ */ public class ArcSDEConnectionConfig { /** ArcSDE server parameter name */ public static final String SERVER_NAME_PARAM_NAME = "server"; /** ArcSDE server port parameter name */ public static final String PORT_NUMBER_PARAM_NAME = "port"; /** ArcSDE databse name parameter name */ public static final String INSTANCE_NAME_PARAM_NAME = "instance"; /** ArcSDE database user name parameter name */ public static final String USER_NAME_PARAM_NAME = "user"; /** ArcSDE database user password parameter name */ public static final String PASSWORD_PARAM_NAME = "password"; public static final String MIN_CONNECTIONS_PARAM_NAME = "pool.minConnections"; public static final String MAX_CONNECTIONS_PARAM_NAME = "pool.maxConnections"; public static final String CONNECTION_TIMEOUT_PARAM_NAME = "pool.timeOut"; /** name or IP of the ArcSDE server to connect to */ private String serverName; /** port number where the ArcSDE instance listens for connections */ private Integer portNumber; /** name of the ArcSDE database to connect to */ private String databaseName; /** database user name to connect as */ private String userName; /** database user password */ private String password; /** minimum number of connection held in reserve, often 0 */ private Integer minConnections = null; /** maximum number of connections */ private Integer maxConnections = null; /** time to hold onto an idle connection before cleaning it up */ private Integer connTimeOut = null; public ArcSDEConnectionConfig() throws IllegalArgumentException { } public String getServerName() { return serverName; } public void setServerName(String serverName) { this.serverName = serverName; } public Integer getPortNumber() { return portNumber; } public void setPortNumber(Integer portNumber) { this.portNumber = portNumber; } public String getDatabaseName() { return databaseName; } public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getMinConnections() { return minConnections; } public void setMinConnections(Integer minConnections) { this.minConnections = minConnections; } public Integer getMaxConnections() { return maxConnections; } public void setMaxConnections(Integer maxConnections) { this.maxConnections = maxConnections; } public Integer getConnTimeOut() { return connTimeOut; } public void setConnTimeOut(Integer connTimeOut) { this.connTimeOut = connTimeOut; } public String toString() { StringBuilder sb = new StringBuilder(getClass().getSimpleName()); sb.append("[server=").append(serverName); - sb.append(", port=)").append(portNumber); + sb.append(", port=").append(portNumber); sb.append(", database=").append(databaseName); - sb.append(", user=)").append(userName); - sb.append(", minConnections=)").append(minConnections); - sb.append(", maxConnections=)").append(maxConnections); - sb.append(", timeout=)").append(connTimeOut); + sb.append(", user=").append(userName); + sb.append(", minConnections=").append(minConnections); + sb.append(", maxConnections=").append(maxConnections); + sb.append(", timeout=").append(connTimeOut); sb.append("]"); return sb.toString(); } }
false
true
public String toString() { StringBuilder sb = new StringBuilder(getClass().getSimpleName()); sb.append("[server=").append(serverName); sb.append(", port=)").append(portNumber); sb.append(", database=").append(databaseName); sb.append(", user=)").append(userName); sb.append(", minConnections=)").append(minConnections); sb.append(", maxConnections=)").append(maxConnections); sb.append(", timeout=)").append(connTimeOut); sb.append("]"); return sb.toString(); }
public String toString() { StringBuilder sb = new StringBuilder(getClass().getSimpleName()); sb.append("[server=").append(serverName); sb.append(", port=").append(portNumber); sb.append(", database=").append(databaseName); sb.append(", user=").append(userName); sb.append(", minConnections=").append(minConnections); sb.append(", maxConnections=").append(maxConnections); sb.append(", timeout=").append(connTimeOut); sb.append("]"); return sb.toString(); }
diff --git a/src/at/theduke/spector/server/http/JettyServer.java b/src/at/theduke/spector/server/http/JettyServer.java index 71fe387..a7ac16d 100644 --- a/src/at/theduke/spector/server/http/JettyServer.java +++ b/src/at/theduke/spector/server/http/JettyServer.java @@ -1,60 +1,61 @@ package at.theduke.spector.server.http; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandler; import at.theduke.spector.server.EventReceiver; import at.theduke.spector.server.http.handler.EventSubmitHandler; public class JettyServer { public static void main(String[] args) { JettyServer server = new JettyServer(8081, new EventReceiver()); server.run(); } String host; int port; EventReceiver eventReceiver; public JettyServer(int port, EventReceiver receiver) { this.port = port; eventReceiver = receiver; } public void run() { + // Set log level to WARN for jetty. final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger("org.eclipse.jetty"); if (!(logger instanceof ch.qos.logback.classic.Logger)) { return; } ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger) logger; logbackLogger.setLevel(ch.qos.logback.classic.Level.WARN); Server server = new Server(port); ContextHandler context = new ContextHandler(); context.setContextPath("/events/submit"); context.setResourceBase("."); context.setClassLoader(Thread.currentThread().getContextClassLoader()); server.setHandler(context); EventSubmitHandler submitHandler = new EventSubmitHandler(); submitHandler.setEventReceiver(eventReceiver); context.setHandler(submitHandler); try { server.start(); server.join(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
true
public void run() { final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger("org.eclipse.jetty"); if (!(logger instanceof ch.qos.logback.classic.Logger)) { return; } ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger) logger; logbackLogger.setLevel(ch.qos.logback.classic.Level.WARN); Server server = new Server(port); ContextHandler context = new ContextHandler(); context.setContextPath("/events/submit"); context.setResourceBase("."); context.setClassLoader(Thread.currentThread().getContextClassLoader()); server.setHandler(context); EventSubmitHandler submitHandler = new EventSubmitHandler(); submitHandler.setEventReceiver(eventReceiver); context.setHandler(submitHandler); try { server.start(); server.join(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void run() { // Set log level to WARN for jetty. final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger("org.eclipse.jetty"); if (!(logger instanceof ch.qos.logback.classic.Logger)) { return; } ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger) logger; logbackLogger.setLevel(ch.qos.logback.classic.Level.WARN); Server server = new Server(port); ContextHandler context = new ContextHandler(); context.setContextPath("/events/submit"); context.setResourceBase("."); context.setClassLoader(Thread.currentThread().getContextClassLoader()); server.setHandler(context); EventSubmitHandler submitHandler = new EventSubmitHandler(); submitHandler.setEventReceiver(eventReceiver); context.setHandler(submitHandler); try { server.start(); server.join(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
diff --git a/src/web/org/openmrs/web/servlet/LogoutServlet.java b/src/web/org/openmrs/web/servlet/LogoutServlet.java index d0abdc52..e59d9061 100644 --- a/src/web/org/openmrs/web/servlet/LogoutServlet.java +++ b/src/web/org/openmrs/web/servlet/LogoutServlet.java @@ -1,53 +1,53 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.openmrs.api.context.Context; /** * Servlet called by the logout link in the webapp. This will call Context.logout() and then make * sure the current user's http session is cleaned up and ready for another user to log in * * @see Context#logout() */ public class LogoutServlet extends HttpServlet { public static final long serialVersionUID = 123423L; /** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession httpSession = request.getSession(); Context.logout(); - response.sendRedirect(request.getContextPath() + "?noredirect=true"); + response.sendRedirect(request.getContextPath() + "/index.htm?noredirect=true"); // clears attributes and makes sure that no one can access this session httpSession.invalidate(); } }
true
true
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession httpSession = request.getSession(); Context.logout(); response.sendRedirect(request.getContextPath() + "?noredirect=true"); // clears attributes and makes sure that no one can access this session httpSession.invalidate(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession httpSession = request.getSession(); Context.logout(); response.sendRedirect(request.getContextPath() + "/index.htm?noredirect=true"); // clears attributes and makes sure that no one can access this session httpSession.invalidate(); }
diff --git a/src/main/java/org/codehaus/mojo/jboss/AbstractJBossMojo.java b/src/main/java/org/codehaus/mojo/jboss/AbstractJBossMojo.java index 3db910b..3acfba8 100644 --- a/src/main/java/org/codehaus/mojo/jboss/AbstractJBossMojo.java +++ b/src/main/java/org/codehaus/mojo/jboss/AbstractJBossMojo.java @@ -1,125 +1,125 @@ package org.codehaus.mojo.jboss; /* * Copyright 2005 Jeff Genender. * * 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.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import java.io.IOException; import java.io.InputStream; /** * This class provides the general functionality for interacting with a local JBoss server. */ public abstract class AbstractJBossMojo extends AbstractMojo { /** * The location of JBoss Home. This is a required configuration parameter (unless JBOSS_HOME is set). * * @parameter expression="${env.JBOSS_HOME}" * @required */ protected String jbossHome; /** * The name of the server profile to use when starting the server. This might be something like "all", "default", or * "minimal". * * @parameter default-value="default" expression="${jboss.serverName}" */ protected String serverName; /** * Check that JBOSS_HOME is correctly configured. * * @throws MojoExecutionException */ protected void checkConfig() throws MojoExecutionException { getLog().debug( "Using JBOSS_HOME: " + jbossHome ); if ( jbossHome == null || jbossHome.equals( "" ) ) { throw new MojoExecutionException( "Neither JBOSS_HOME nor the jbossHome configuration parameter is set!" ); } } /** * Call the JBoss startup or shutdown script. * * @param commandName - The name of the command to run * @param params - The command line parameters * @throws MojoExecutionException */ protected void launch( String commandName, String params ) throws MojoExecutionException { checkConfig(); String osName = System.getProperty( "os.name" ); Runtime runtime = Runtime.getRuntime(); try { Process proc = null; if ( osName.startsWith( "Windows" ) ) { String command[] = - { "cmd.exe", "/C", "cd " + jbossHome + "\\bin & set JBOSS_HOME=\"" + jbossHome + "\" & " + commandName + ".bat " + " " + params }; + { "cmd.exe", "/C", "cd /D " + jbossHome + "\\bin & set JBOSS_HOME=\"" + jbossHome + "\" & " + commandName + ".bat " + " " + params }; proc = runtime.exec( command ); dump( proc.getInputStream() ); dump( proc.getErrorStream() ); } else { String command[] = { "sh", "-c", "cd " + jbossHome + "/bin; export JBOSS_HOME=\"" + jbossHome + "\"; ./" + commandName + ".sh " + " " + params }; proc = runtime.exec( command ); } } catch ( Exception e ) { throw new MojoExecutionException( "Unable to execute command: " + e.getMessage(), e ); } } protected void dump( final InputStream input ) { new Thread( new Runnable() { public void run() { try { byte[] b = new byte[1000]; while ( ( input.read( b ) ) != -1 ) { } } catch ( IOException e ) { e.printStackTrace(); } } } ).start(); } }
true
true
protected void launch( String commandName, String params ) throws MojoExecutionException { checkConfig(); String osName = System.getProperty( "os.name" ); Runtime runtime = Runtime.getRuntime(); try { Process proc = null; if ( osName.startsWith( "Windows" ) ) { String command[] = { "cmd.exe", "/C", "cd " + jbossHome + "\\bin & set JBOSS_HOME=\"" + jbossHome + "\" & " + commandName + ".bat " + " " + params }; proc = runtime.exec( command ); dump( proc.getInputStream() ); dump( proc.getErrorStream() ); } else { String command[] = { "sh", "-c", "cd " + jbossHome + "/bin; export JBOSS_HOME=\"" + jbossHome + "\"; ./" + commandName + ".sh " + " " + params }; proc = runtime.exec( command ); } } catch ( Exception e ) { throw new MojoExecutionException( "Unable to execute command: " + e.getMessage(), e ); } }
protected void launch( String commandName, String params ) throws MojoExecutionException { checkConfig(); String osName = System.getProperty( "os.name" ); Runtime runtime = Runtime.getRuntime(); try { Process proc = null; if ( osName.startsWith( "Windows" ) ) { String command[] = { "cmd.exe", "/C", "cd /D " + jbossHome + "\\bin & set JBOSS_HOME=\"" + jbossHome + "\" & " + commandName + ".bat " + " " + params }; proc = runtime.exec( command ); dump( proc.getInputStream() ); dump( proc.getErrorStream() ); } else { String command[] = { "sh", "-c", "cd " + jbossHome + "/bin; export JBOSS_HOME=\"" + jbossHome + "\"; ./" + commandName + ".sh " + " " + params }; proc = runtime.exec( command ); } } catch ( Exception e ) { throw new MojoExecutionException( "Unable to execute command: " + e.getMessage(), e ); } }
diff --git a/melati/src/main/java/org/melati/HttpBasicAuthenticationAccessHandler.java b/melati/src/main/java/org/melati/HttpBasicAuthenticationAccessHandler.java index 3f5fad418..c7e048dbb 100644 --- a/melati/src/main/java/org/melati/HttpBasicAuthenticationAccessHandler.java +++ b/melati/src/main/java/org/melati/HttpBasicAuthenticationAccessHandler.java @@ -1,247 +1,247 @@ /* * $Source$ * $Revision$ * * Part of Melati (http://melati.org), a framework for the rapid * development of clean, maintainable web applications. * * ------------------------------------- * Copyright (C) 2000 William Chesters * ------------------------------------- * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * A copy of the GPL should be in the file org/melati/COPYING in this tree. * Or see http://melati.org/License.html. * * Contact details for copyright holder: * * William Chesters <[email protected]> * http://paneris.org/~williamc * Obrechtstraat 114, 2517VX Den Haag, The Netherlands * * * ------ * Note * ------ * * I will assign copyright to PanEris (http://paneris.org) as soon as * we have sorted out what sort of legal existence we need to have for * that to make sense. When WebMacro's "Simple Public License" is * finalised, we'll offer it as an alternative license for Melati. * In the meantime, if you want to use Melati on non-GPL terms, * contact me! */ package org.melati; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import org.webmacro.*; import org.webmacro.util.*; import org.webmacro.engine.*; import org.webmacro.servlet.*; import org.melati.util.*; import org.melati.*; import org.melati.poem.*; /** * Flags up when something was illegal or not supported about an incoming HTTP * authorization */ class HttpAuthorizationMelatiException extends MelatiRuntimeException { public HttpAuthorizationMelatiException(String message) { super(message, null); } } /** * The information contained in an HTTP authorization */ class HttpAuthorization { public String type; public String username; public String password; public HttpAuthorization(String type, String username, String password) { this.type = type; this.username = username; this.password = password; } public static HttpAuthorization from(String authHeader) { // FIXME single space probably not only valid sep if (authHeader.regionMatches(0, "Basic ", 0, 6)) { String logpas = Base64.decode(authHeader.substring(6)); int colon = logpas.indexOf(':'); if (colon == -1) throw new HttpAuthorizationMelatiException( "The browser sent Basic Authorization credentials with no colon " + "(that's not legal)"); return new HttpAuthorization("Basic", logpas.substring(0, colon).trim(), logpas.substring(colon + 1).trim()); } else { int space = authHeader.indexOf(' '); if (space == -1) throw new HttpAuthorizationMelatiException( "The browser sent an Authorization header without a space, " + "so it can't be anything Melati understands: " + authHeader); String type = authHeader.substring(0, space); throw new HttpAuthorizationMelatiException( "The browser tried to authenticate using an authorization type " + "`" + type + "' which Melati doesn't understand"); } } public static HttpAuthorization from(HttpServletRequest request) { String header = request.getHeader("Authorization"); return header == null ? null : from(header); } } /** * An <TT>AccessHandler</TT> which uses the HTTP Basic Authentication scheme to * elicit and maintain the user's login and password. This implementation * doesn't use the servlet session at all, so it doesn't try to send cookies or * do URL rewriting. * * @see MelatiServlet#handle(org.webmacro.servlet.WebContext, org.melati.Melati) * @see MelatiServlet#init */ public class HttpBasicAuthenticationAccessHandler implements AccessHandler { private static final String className = new HttpBasicAuthenticationAccessHandler().getClass().getName(); public final String REALM = className + ".realm"; public final String USER = className + ".user"; protected boolean useSession() { return false; } /** * Force a login by sending a 401 error back to the browser. FIXME * Apache/Netscape appear not to do anything with <TT>message</TT>, which is * why it's just left as a <TT>String</TT>. */ protected void forceLogin(HttpServletResponse resp, String realm, String message) throws IOException { String desc = realm == null ? "<unknown>" : StringUtils.tr(realm, '"', ' '); resp.setHeader("WWW-Authenticate", "Basic realm=\"" + desc + "\""); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, message); } public Template handleAccessException( WebContext context, AccessPoemException accessException) throws Exception { String capName = accessException.capability.getName(); if (useSession()) context.getSession().putValue(REALM, capName); forceLogin(context.getResponse(), capName, accessException.getMessage()); return null; } public WebContext establishUser(WebContext context, Database database) throws PoemException, IOException, ServletException { HttpAuthorization auth = HttpAuthorization.from(context.getRequest()); if (auth == null) { // No attempt to log in: become `guest' PoemThread.setAccessToken(database.guestAccessToken()); return context; } else { // They are trying to log in // If allowed, we store the User in the session to avoid repeating the // SELECTion implied by firstWhereEq for every hit User sessionUser = useSession() ? (User)context.getSession().getValue(USER) : null; User user = null; if (sessionUser == null || !sessionUser.getLogin().equals(auth.username)) try { user = (User)database.getUserTable().getLoginColumn(). firstWhereEq(auth.username); } catch (NoSuchRowPoemException e) { } catch (AccessPoemException e) { // paranoia } else user = sessionUser; if (user == null || !user.getPassword().equals(auth.password)) { // Login/password authentication failed; we must trigger another - // attempt. But do we know what "realm" (= POEM capability name) for + // attempt. But do we know the "realm" (= POEM capability name) for // which they were originally found not to be authorized? String storedRealm; if (useSession() && (storedRealm = (String)context.getSession().getValue(REALM)) != null) { // The "realm" is stored in the session forceLogin(context.getResponse(), storedRealm, "Login/password not recognised"); return null; } else { // We don't know the "realm", so we just let the user try again as // `guest' and hopefully trigger the same problem and get the same // message all over again. Not very satisfactory but the alternative // is providing a default realm like "<unknown>". PoemThread.setAccessToken(database.guestAccessToken()); return context; } } else { // Login/password authentication succeeded PoemThread.setAccessToken(user); if (useSession() && user != sessionUser) context.getSession().putValue(USER, user); return context; } } } }
true
true
public WebContext establishUser(WebContext context, Database database) throws PoemException, IOException, ServletException { HttpAuthorization auth = HttpAuthorization.from(context.getRequest()); if (auth == null) { // No attempt to log in: become `guest' PoemThread.setAccessToken(database.guestAccessToken()); return context; } else { // They are trying to log in // If allowed, we store the User in the session to avoid repeating the // SELECTion implied by firstWhereEq for every hit User sessionUser = useSession() ? (User)context.getSession().getValue(USER) : null; User user = null; if (sessionUser == null || !sessionUser.getLogin().equals(auth.username)) try { user = (User)database.getUserTable().getLoginColumn(). firstWhereEq(auth.username); } catch (NoSuchRowPoemException e) { } catch (AccessPoemException e) { // paranoia } else user = sessionUser; if (user == null || !user.getPassword().equals(auth.password)) { // Login/password authentication failed; we must trigger another // attempt. But do we know what "realm" (= POEM capability name) for // which they were originally found not to be authorized? String storedRealm; if (useSession() && (storedRealm = (String)context.getSession().getValue(REALM)) != null) { // The "realm" is stored in the session forceLogin(context.getResponse(), storedRealm, "Login/password not recognised"); return null; } else { // We don't know the "realm", so we just let the user try again as // `guest' and hopefully trigger the same problem and get the same // message all over again. Not very satisfactory but the alternative // is providing a default realm like "<unknown>". PoemThread.setAccessToken(database.guestAccessToken()); return context; } } else { // Login/password authentication succeeded PoemThread.setAccessToken(user); if (useSession() && user != sessionUser) context.getSession().putValue(USER, user); return context; } } }
public WebContext establishUser(WebContext context, Database database) throws PoemException, IOException, ServletException { HttpAuthorization auth = HttpAuthorization.from(context.getRequest()); if (auth == null) { // No attempt to log in: become `guest' PoemThread.setAccessToken(database.guestAccessToken()); return context; } else { // They are trying to log in // If allowed, we store the User in the session to avoid repeating the // SELECTion implied by firstWhereEq for every hit User sessionUser = useSession() ? (User)context.getSession().getValue(USER) : null; User user = null; if (sessionUser == null || !sessionUser.getLogin().equals(auth.username)) try { user = (User)database.getUserTable().getLoginColumn(). firstWhereEq(auth.username); } catch (NoSuchRowPoemException e) { } catch (AccessPoemException e) { // paranoia } else user = sessionUser; if (user == null || !user.getPassword().equals(auth.password)) { // Login/password authentication failed; we must trigger another // attempt. But do we know the "realm" (= POEM capability name) for // which they were originally found not to be authorized? String storedRealm; if (useSession() && (storedRealm = (String)context.getSession().getValue(REALM)) != null) { // The "realm" is stored in the session forceLogin(context.getResponse(), storedRealm, "Login/password not recognised"); return null; } else { // We don't know the "realm", so we just let the user try again as // `guest' and hopefully trigger the same problem and get the same // message all over again. Not very satisfactory but the alternative // is providing a default realm like "<unknown>". PoemThread.setAccessToken(database.guestAccessToken()); return context; } } else { // Login/password authentication succeeded PoemThread.setAccessToken(user); if (useSession() && user != sessionUser) context.getSession().putValue(USER, user); return context; } } }
diff --git a/src/com/modcrafting/ultrabans/commands/Ipban.java b/src/com/modcrafting/ultrabans/commands/Ipban.java index ed903e3..860c4be 100644 --- a/src/com/modcrafting/ultrabans/commands/Ipban.java +++ b/src/com/modcrafting/ultrabans/commands/Ipban.java @@ -1,164 +1,164 @@ package com.modcrafting.ultrabans.commands; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import com.modcrafting.ultrabans.UltraBan; public class Ipban implements CommandExecutor{ public static final Logger log = Logger.getLogger("Minecraft"); UltraBan plugin; String permission = "ultraban.ipban"; public Ipban(UltraBan ultraBan) { this.plugin = ultraBan; } public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { YamlConfiguration config = (YamlConfiguration) plugin.getConfig(); boolean auth = false; boolean broadcast = true; Player player = null; String admin = config.getString("defAdminName", "server"); String reason = config.getString("defReason", "not sure"); if (sender instanceof Player){ player = (Player)sender; if(player.hasPermission(permission) || player.isOp()) auth = true; admin = player.getName(); }else{ auth = true; } if (!auth){ sender.sendMessage(ChatColor.RED + "You do not have the required permissions."); return true; } if (args.length < 1) return false; String p = args[0]; //Enhanced Variables if(args.length > 1){ if(args[1].equalsIgnoreCase("-s")){ broadcast = false; reason = plugin.util.combineSplit(2, args, " "); }else{ if(args[1].equalsIgnoreCase("-a")){ admin = config.getString("defAdminName", "server"); reason = plugin.util.combineSplit(2, args, " "); }else{ reason = plugin.util.combineSplit(1, args, " "); } } } //Validate IP format if(plugin.util.validIP(p)){ plugin.bannedIPs.add(p); String pname = plugin.db.getName(p); if (pname != null){ plugin.db.addPlayer(pname, reason, admin, 0, 1); plugin.bannedPlayers.add(pname); }else{ plugin.db.setAddress(p, p); plugin.db.addPlayer(p, reason, admin, 0, 1); } String banMsgBroadcast = config.getString("messages.banMsgBroadcast", "%victim% was banned by %admin%. Reason: %reason%"); if(banMsgBroadcast.contains(plugin.regexAdmin)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexAdmin, admin); if(banMsgBroadcast.contains(plugin.regexReason)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexReason, reason); if(banMsgBroadcast.contains(plugin.regexVictim)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexVictim, p.toLowerCase()); if(banMsgBroadcast != null){ if(broadcast){ plugin.getServer().broadcastMessage(plugin.util.formatMessage(banMsgBroadcast)); }else{ sender.sendMessage(ChatColor.ITALIC + "Silent: " + plugin.util.formatMessage(banMsgBroadcast)); } } log.log(Level.INFO, "[UltraBan] " + admin + " banned ip " + p + "."); return true; } if(plugin.autoComplete) p = plugin.util.expandName(p); //Player Checks Player victim = plugin.getServer().getPlayer(p); String victimip = null; if(victim == null){ victim = plugin.getServer().getOfflinePlayer(p).getPlayer(); if(victim != null){ if(victim.hasPermission( "ultraban.override.ipban")){ sender.sendMessage(ChatColor.RED + "Your ipban has been denied!"); return true; } }else{ victimip = plugin.db.getAddress(p); if(victimip == null){ sender.sendMessage(ChatColor.GRAY + "IP address not found by Ultrabans for " + p); sender.sendMessage(ChatColor.GRAY + "Processed as a normal ban for " + p); plugin.db.addPlayer(p.toLowerCase(), reason, admin, 0, 0); plugin.bannedPlayers.add(p.toLowerCase()); log.log(Level.INFO, "[UltraBan] " + admin + " banned player " + p + "."); return true; } } }else{ if(victim.getName() == admin){ sender.sendMessage(ChatColor.RED + "You cannot ipban yourself!"); return true; } if(victim.hasPermission( "ultraban.override.ipban")){ sender.sendMessage(ChatColor.RED + "Your ipban has been denied! Player Notified!"); victim.sendMessage(ChatColor.RED + "Player: " + admin + " Attempted to ipban you!"); return true; } victimip = plugin.db.getAddress(victim.getName().toLowerCase()); } if(plugin.bannedIPs.contains(victimip)){ sender.sendMessage(ChatColor.BLUE + victim.getName() + ChatColor.GRAY + " is already banned for " + plugin.db.getBanReason(p.toLowerCase())); return true; } if(victimip == null){ sender.sendMessage(ChatColor.GRAY + "IP address not found by Ultrabans for " + p.toLowerCase()); sender.sendMessage(ChatColor.GRAY + "Processed as a normal ban for " + p.toLowerCase()); plugin.db.addPlayer(victim.getName(), reason, admin, 0, 0); log.log(Level.INFO, "[UltraBan] " + admin + " banned player " + p.toLowerCase() + "."); String banMsgVictim = config.getString("messages.banMsgVictim", "You have been banned by %admin%. Reason: %reason%"); if(banMsgVictim.contains(plugin.regexAdmin)) banMsgVictim = banMsgVictim.replaceAll(plugin.regexAdmin, admin); if(banMsgVictim.contains(plugin.regexReason)) banMsgVictim = banMsgVictim.replaceAll(plugin.regexReason, reason); victim.kickPlayer(plugin.util.formatMessage(banMsgVictim)); return true; } String banMsgVictim = config.getString("messages.banMsgVictim", "You have been banned by %admin%. Reason: %reason%"); if(banMsgVictim.contains(plugin.regexAdmin)) banMsgVictim = banMsgVictim.replaceAll(plugin.regexAdmin, admin); if(banMsgVictim.contains(plugin.regexReason)) banMsgVictim = banMsgVictim.replaceAll(plugin.regexReason, reason); String banMsgBroadcast = config.getString("messages.banMsgBroadcast", "%victim% was banned by %admin%. Reason: %reason%"); if(banMsgBroadcast.contains(plugin.regexAdmin)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexAdmin, admin); if(banMsgBroadcast.contains(plugin.regexReason)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexReason, reason); if(banMsgBroadcast.contains(plugin.regexVictim)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexVictim, p.toLowerCase()); plugin.bannedPlayers.add(p.toLowerCase()); plugin.bannedIPs.add(victimip); plugin.db.addPlayer(p.toLowerCase(), reason, admin, 0, 1); - victim.kickPlayer(plugin.util.formatMessage(banMsgVictim)); + if(victim != null && victim.isOnline()) victim.kickPlayer(plugin.util.formatMessage(banMsgVictim)); if(banMsgBroadcast != null){ if(broadcast){ plugin.getServer().broadcastMessage(plugin.util.formatMessage(banMsgBroadcast)); }else{ sender.sendMessage(ChatColor.ITALIC + "Silent: " + plugin.util.formatMessage(banMsgBroadcast)); } } log.log(Level.INFO, "[UltraBan] " + admin + " banned player " + p.toLowerCase() + "."); return true; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { YamlConfiguration config = (YamlConfiguration) plugin.getConfig(); boolean auth = false; boolean broadcast = true; Player player = null; String admin = config.getString("defAdminName", "server"); String reason = config.getString("defReason", "not sure"); if (sender instanceof Player){ player = (Player)sender; if(player.hasPermission(permission) || player.isOp()) auth = true; admin = player.getName(); }else{ auth = true; } if (!auth){ sender.sendMessage(ChatColor.RED + "You do not have the required permissions."); return true; } if (args.length < 1) return false; String p = args[0]; //Enhanced Variables if(args.length > 1){ if(args[1].equalsIgnoreCase("-s")){ broadcast = false; reason = plugin.util.combineSplit(2, args, " "); }else{ if(args[1].equalsIgnoreCase("-a")){ admin = config.getString("defAdminName", "server"); reason = plugin.util.combineSplit(2, args, " "); }else{ reason = plugin.util.combineSplit(1, args, " "); } } } //Validate IP format if(plugin.util.validIP(p)){ plugin.bannedIPs.add(p); String pname = plugin.db.getName(p); if (pname != null){ plugin.db.addPlayer(pname, reason, admin, 0, 1); plugin.bannedPlayers.add(pname); }else{ plugin.db.setAddress(p, p); plugin.db.addPlayer(p, reason, admin, 0, 1); } String banMsgBroadcast = config.getString("messages.banMsgBroadcast", "%victim% was banned by %admin%. Reason: %reason%"); if(banMsgBroadcast.contains(plugin.regexAdmin)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexAdmin, admin); if(banMsgBroadcast.contains(plugin.regexReason)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexReason, reason); if(banMsgBroadcast.contains(plugin.regexVictim)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexVictim, p.toLowerCase()); if(banMsgBroadcast != null){ if(broadcast){ plugin.getServer().broadcastMessage(plugin.util.formatMessage(banMsgBroadcast)); }else{ sender.sendMessage(ChatColor.ITALIC + "Silent: " + plugin.util.formatMessage(banMsgBroadcast)); } } log.log(Level.INFO, "[UltraBan] " + admin + " banned ip " + p + "."); return true; } if(plugin.autoComplete) p = plugin.util.expandName(p); //Player Checks Player victim = plugin.getServer().getPlayer(p); String victimip = null; if(victim == null){ victim = plugin.getServer().getOfflinePlayer(p).getPlayer(); if(victim != null){ if(victim.hasPermission( "ultraban.override.ipban")){ sender.sendMessage(ChatColor.RED + "Your ipban has been denied!"); return true; } }else{ victimip = plugin.db.getAddress(p); if(victimip == null){ sender.sendMessage(ChatColor.GRAY + "IP address not found by Ultrabans for " + p); sender.sendMessage(ChatColor.GRAY + "Processed as a normal ban for " + p); plugin.db.addPlayer(p.toLowerCase(), reason, admin, 0, 0); plugin.bannedPlayers.add(p.toLowerCase()); log.log(Level.INFO, "[UltraBan] " + admin + " banned player " + p + "."); return true; } } }else{ if(victim.getName() == admin){ sender.sendMessage(ChatColor.RED + "You cannot ipban yourself!"); return true; } if(victim.hasPermission( "ultraban.override.ipban")){ sender.sendMessage(ChatColor.RED + "Your ipban has been denied! Player Notified!"); victim.sendMessage(ChatColor.RED + "Player: " + admin + " Attempted to ipban you!"); return true; } victimip = plugin.db.getAddress(victim.getName().toLowerCase()); } if(plugin.bannedIPs.contains(victimip)){ sender.sendMessage(ChatColor.BLUE + victim.getName() + ChatColor.GRAY + " is already banned for " + plugin.db.getBanReason(p.toLowerCase())); return true; } if(victimip == null){ sender.sendMessage(ChatColor.GRAY + "IP address not found by Ultrabans for " + p.toLowerCase()); sender.sendMessage(ChatColor.GRAY + "Processed as a normal ban for " + p.toLowerCase()); plugin.db.addPlayer(victim.getName(), reason, admin, 0, 0); log.log(Level.INFO, "[UltraBan] " + admin + " banned player " + p.toLowerCase() + "."); String banMsgVictim = config.getString("messages.banMsgVictim", "You have been banned by %admin%. Reason: %reason%"); if(banMsgVictim.contains(plugin.regexAdmin)) banMsgVictim = banMsgVictim.replaceAll(plugin.regexAdmin, admin); if(banMsgVictim.contains(plugin.regexReason)) banMsgVictim = banMsgVictim.replaceAll(plugin.regexReason, reason); victim.kickPlayer(plugin.util.formatMessage(banMsgVictim)); return true; } String banMsgVictim = config.getString("messages.banMsgVictim", "You have been banned by %admin%. Reason: %reason%"); if(banMsgVictim.contains(plugin.regexAdmin)) banMsgVictim = banMsgVictim.replaceAll(plugin.regexAdmin, admin); if(banMsgVictim.contains(plugin.regexReason)) banMsgVictim = banMsgVictim.replaceAll(plugin.regexReason, reason); String banMsgBroadcast = config.getString("messages.banMsgBroadcast", "%victim% was banned by %admin%. Reason: %reason%"); if(banMsgBroadcast.contains(plugin.regexAdmin)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexAdmin, admin); if(banMsgBroadcast.contains(plugin.regexReason)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexReason, reason); if(banMsgBroadcast.contains(plugin.regexVictim)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexVictim, p.toLowerCase()); plugin.bannedPlayers.add(p.toLowerCase()); plugin.bannedIPs.add(victimip); plugin.db.addPlayer(p.toLowerCase(), reason, admin, 0, 1); victim.kickPlayer(plugin.util.formatMessage(banMsgVictim)); if(banMsgBroadcast != null){ if(broadcast){ plugin.getServer().broadcastMessage(plugin.util.formatMessage(banMsgBroadcast)); }else{ sender.sendMessage(ChatColor.ITALIC + "Silent: " + plugin.util.formatMessage(banMsgBroadcast)); } } log.log(Level.INFO, "[UltraBan] " + admin + " banned player " + p.toLowerCase() + "."); return true; }
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { YamlConfiguration config = (YamlConfiguration) plugin.getConfig(); boolean auth = false; boolean broadcast = true; Player player = null; String admin = config.getString("defAdminName", "server"); String reason = config.getString("defReason", "not sure"); if (sender instanceof Player){ player = (Player)sender; if(player.hasPermission(permission) || player.isOp()) auth = true; admin = player.getName(); }else{ auth = true; } if (!auth){ sender.sendMessage(ChatColor.RED + "You do not have the required permissions."); return true; } if (args.length < 1) return false; String p = args[0]; //Enhanced Variables if(args.length > 1){ if(args[1].equalsIgnoreCase("-s")){ broadcast = false; reason = plugin.util.combineSplit(2, args, " "); }else{ if(args[1].equalsIgnoreCase("-a")){ admin = config.getString("defAdminName", "server"); reason = plugin.util.combineSplit(2, args, " "); }else{ reason = plugin.util.combineSplit(1, args, " "); } } } //Validate IP format if(plugin.util.validIP(p)){ plugin.bannedIPs.add(p); String pname = plugin.db.getName(p); if (pname != null){ plugin.db.addPlayer(pname, reason, admin, 0, 1); plugin.bannedPlayers.add(pname); }else{ plugin.db.setAddress(p, p); plugin.db.addPlayer(p, reason, admin, 0, 1); } String banMsgBroadcast = config.getString("messages.banMsgBroadcast", "%victim% was banned by %admin%. Reason: %reason%"); if(banMsgBroadcast.contains(plugin.regexAdmin)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexAdmin, admin); if(banMsgBroadcast.contains(plugin.regexReason)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexReason, reason); if(banMsgBroadcast.contains(plugin.regexVictim)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexVictim, p.toLowerCase()); if(banMsgBroadcast != null){ if(broadcast){ plugin.getServer().broadcastMessage(plugin.util.formatMessage(banMsgBroadcast)); }else{ sender.sendMessage(ChatColor.ITALIC + "Silent: " + plugin.util.formatMessage(banMsgBroadcast)); } } log.log(Level.INFO, "[UltraBan] " + admin + " banned ip " + p + "."); return true; } if(plugin.autoComplete) p = plugin.util.expandName(p); //Player Checks Player victim = plugin.getServer().getPlayer(p); String victimip = null; if(victim == null){ victim = plugin.getServer().getOfflinePlayer(p).getPlayer(); if(victim != null){ if(victim.hasPermission( "ultraban.override.ipban")){ sender.sendMessage(ChatColor.RED + "Your ipban has been denied!"); return true; } }else{ victimip = plugin.db.getAddress(p); if(victimip == null){ sender.sendMessage(ChatColor.GRAY + "IP address not found by Ultrabans for " + p); sender.sendMessage(ChatColor.GRAY + "Processed as a normal ban for " + p); plugin.db.addPlayer(p.toLowerCase(), reason, admin, 0, 0); plugin.bannedPlayers.add(p.toLowerCase()); log.log(Level.INFO, "[UltraBan] " + admin + " banned player " + p + "."); return true; } } }else{ if(victim.getName() == admin){ sender.sendMessage(ChatColor.RED + "You cannot ipban yourself!"); return true; } if(victim.hasPermission( "ultraban.override.ipban")){ sender.sendMessage(ChatColor.RED + "Your ipban has been denied! Player Notified!"); victim.sendMessage(ChatColor.RED + "Player: " + admin + " Attempted to ipban you!"); return true; } victimip = plugin.db.getAddress(victim.getName().toLowerCase()); } if(plugin.bannedIPs.contains(victimip)){ sender.sendMessage(ChatColor.BLUE + victim.getName() + ChatColor.GRAY + " is already banned for " + plugin.db.getBanReason(p.toLowerCase())); return true; } if(victimip == null){ sender.sendMessage(ChatColor.GRAY + "IP address not found by Ultrabans for " + p.toLowerCase()); sender.sendMessage(ChatColor.GRAY + "Processed as a normal ban for " + p.toLowerCase()); plugin.db.addPlayer(victim.getName(), reason, admin, 0, 0); log.log(Level.INFO, "[UltraBan] " + admin + " banned player " + p.toLowerCase() + "."); String banMsgVictim = config.getString("messages.banMsgVictim", "You have been banned by %admin%. Reason: %reason%"); if(banMsgVictim.contains(plugin.regexAdmin)) banMsgVictim = banMsgVictim.replaceAll(plugin.regexAdmin, admin); if(banMsgVictim.contains(plugin.regexReason)) banMsgVictim = banMsgVictim.replaceAll(plugin.regexReason, reason); victim.kickPlayer(plugin.util.formatMessage(banMsgVictim)); return true; } String banMsgVictim = config.getString("messages.banMsgVictim", "You have been banned by %admin%. Reason: %reason%"); if(banMsgVictim.contains(plugin.regexAdmin)) banMsgVictim = banMsgVictim.replaceAll(plugin.regexAdmin, admin); if(banMsgVictim.contains(plugin.regexReason)) banMsgVictim = banMsgVictim.replaceAll(plugin.regexReason, reason); String banMsgBroadcast = config.getString("messages.banMsgBroadcast", "%victim% was banned by %admin%. Reason: %reason%"); if(banMsgBroadcast.contains(plugin.regexAdmin)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexAdmin, admin); if(banMsgBroadcast.contains(plugin.regexReason)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexReason, reason); if(banMsgBroadcast.contains(plugin.regexVictim)) banMsgBroadcast = banMsgBroadcast.replaceAll(plugin.regexVictim, p.toLowerCase()); plugin.bannedPlayers.add(p.toLowerCase()); plugin.bannedIPs.add(victimip); plugin.db.addPlayer(p.toLowerCase(), reason, admin, 0, 1); if(victim != null && victim.isOnline()) victim.kickPlayer(plugin.util.formatMessage(banMsgVictim)); if(banMsgBroadcast != null){ if(broadcast){ plugin.getServer().broadcastMessage(plugin.util.formatMessage(banMsgBroadcast)); }else{ sender.sendMessage(ChatColor.ITALIC + "Silent: " + plugin.util.formatMessage(banMsgBroadcast)); } } log.log(Level.INFO, "[UltraBan] " + admin + " banned player " + p.toLowerCase() + "."); return true; }
diff --git a/projectubernahme/ProjectUbernahme.java b/projectubernahme/ProjectUbernahme.java index 71d0dc0..74c54c8 100644 --- a/projectubernahme/ProjectUbernahme.java +++ b/projectubernahme/ProjectUbernahme.java @@ -1,110 +1,117 @@ package projectubernahme; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import javax.imageio.ImageIO; import projectubernahme.interface2D.Interface2D; import projectubernahme.simulator.MainSimulator; /* * Copyright 2010 Project Ubernahme Team * Copyright 2010 Martin Ueding <[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/>. */ /** the main game class */ public class ProjectUbernahme { /** main player */ static Player player; static MainSimulator sim; public static void main (String[] args) { loadImagesIntoMap(); sim = new MainSimulator(); player = new Player(sim); sim.addPlayer(player); @SuppressWarnings("unused") Interface2D interface2d = new Interface2D(sim, player); } private static HashMap<String,BufferedImage> images = new HashMap<String,BufferedImage>(); public static BufferedImage getImage(String name, int resolution) { //System.out.println("Query for "+name+resolution); int res = 1; while (resolution > res) res *= 2; res = Math.min(res, 256); //System.out.println("Query for "+name+res); String key = name+res; if (images.containsKey(key)) { return images.get(key); } else { return null; } } private static void loadImagesIntoMap () { /* load the gfx directory */ File gfxDirectory = new File(ClassLoader.getSystemResource("projectubernahme/gfx").getFile()); /* if this worked quite well ... */ if (gfxDirectory != null) { /* get all the files within the gfx directory */ File[] files = gfxDirectory.listFiles(); + System.out.println("Absolute Path of gfxDir: "+gfxDirectory.getAbsolutePath()); + System.out.println("does the dir exist? "+gfxDirectory.exists()); + System.out.println("is it a directory? "+gfxDirectory.isDirectory()); + System.out.println("Files inside it: "+gfxDirectory.listFiles()); if (files != null){ for (File file : files) { /* get all the files which hopefully are a picture */ if (file.getName().endsWith(".png")) { System.out.println("Loading file: "+file.getName()); try { InputStream is = ClassLoader.getSystemResourceAsStream("projectubernahme/gfx/"+file.getName()); /* place the picture in the hashmap */ if (is != null) { images.put(file.getName().replace(".png", ""), ImageIO.read(is)); } + else { + System.out.println("is is null"); + } } catch (IOException e) { e.printStackTrace(); } } } } else{ System.out.println(Localizer.get("ERROR: Could not access the files within the gfx-directory somehow. Sorry, quitting now")); System.exit(1); } } else { System.out.println(Localizer.get("ERROR: Could not access the gfx-directory somehow. Sorry, quitting now")); System.exit(1); } } }
false
true
private static void loadImagesIntoMap () { /* load the gfx directory */ File gfxDirectory = new File(ClassLoader.getSystemResource("projectubernahme/gfx").getFile()); /* if this worked quite well ... */ if (gfxDirectory != null) { /* get all the files within the gfx directory */ File[] files = gfxDirectory.listFiles(); if (files != null){ for (File file : files) { /* get all the files which hopefully are a picture */ if (file.getName().endsWith(".png")) { System.out.println("Loading file: "+file.getName()); try { InputStream is = ClassLoader.getSystemResourceAsStream("projectubernahme/gfx/"+file.getName()); /* place the picture in the hashmap */ if (is != null) { images.put(file.getName().replace(".png", ""), ImageIO.read(is)); } } catch (IOException e) { e.printStackTrace(); } } } } else{ System.out.println(Localizer.get("ERROR: Could not access the files within the gfx-directory somehow. Sorry, quitting now")); System.exit(1); } } else { System.out.println(Localizer.get("ERROR: Could not access the gfx-directory somehow. Sorry, quitting now")); System.exit(1); } }
private static void loadImagesIntoMap () { /* load the gfx directory */ File gfxDirectory = new File(ClassLoader.getSystemResource("projectubernahme/gfx").getFile()); /* if this worked quite well ... */ if (gfxDirectory != null) { /* get all the files within the gfx directory */ File[] files = gfxDirectory.listFiles(); System.out.println("Absolute Path of gfxDir: "+gfxDirectory.getAbsolutePath()); System.out.println("does the dir exist? "+gfxDirectory.exists()); System.out.println("is it a directory? "+gfxDirectory.isDirectory()); System.out.println("Files inside it: "+gfxDirectory.listFiles()); if (files != null){ for (File file : files) { /* get all the files which hopefully are a picture */ if (file.getName().endsWith(".png")) { System.out.println("Loading file: "+file.getName()); try { InputStream is = ClassLoader.getSystemResourceAsStream("projectubernahme/gfx/"+file.getName()); /* place the picture in the hashmap */ if (is != null) { images.put(file.getName().replace(".png", ""), ImageIO.read(is)); } else { System.out.println("is is null"); } } catch (IOException e) { e.printStackTrace(); } } } } else{ System.out.println(Localizer.get("ERROR: Could not access the files within the gfx-directory somehow. Sorry, quitting now")); System.exit(1); } } else { System.out.println(Localizer.get("ERROR: Could not access the gfx-directory somehow. Sorry, quitting now")); System.exit(1); } }
diff --git a/javafx.fxd/src/org/netbeans/modules/javafx/fxd/composer/source/FXDDocumentModelProvider.java b/javafx.fxd/src/org/netbeans/modules/javafx/fxd/composer/source/FXDDocumentModelProvider.java index 531ee57f..c427034d 100644 --- a/javafx.fxd/src/org/netbeans/modules/javafx/fxd/composer/source/FXDDocumentModelProvider.java +++ b/javafx.fxd/src/org/netbeans/modules/javafx/fxd/composer/source/FXDDocumentModelProvider.java @@ -1,367 +1,369 @@ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package org.netbeans.modules.javafx.fxd.composer.source; import com.sun.javafx.tools.fxd.FXDReference; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.swing.JEditorPane; import javax.swing.SwingUtilities; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import org.netbeans.editor.BaseDocument; import org.netbeans.editor.EditorUI; import org.netbeans.editor.StatusBar; import org.netbeans.editor.Utilities; import org.netbeans.modules.editor.NbEditorUtilities; import org.netbeans.modules.editor.structure.api.DocumentElement; import org.netbeans.modules.editor.structure.api.DocumentModel; import org.netbeans.modules.editor.structure.api.DocumentModel.DocumentChange; import org.netbeans.modules.editor.structure.api.DocumentModel.DocumentModelModificationTransaction; import org.netbeans.modules.editor.structure.api.DocumentModel.DocumentModelTransactionCancelledException; import org.netbeans.modules.editor.structure.api.DocumentModelException; import org.netbeans.modules.editor.structure.spi.DocumentModelProvider; import org.netbeans.modules.javafx.fxd.composer.misc.CharSeqReader; import org.netbeans.modules.javafx.fxd.composer.model.FXDFileModel; import org.openide.cookies.EditorCookie; import org.openide.loaders.DataObject; import org.openide.util.Exceptions; import com.sun.javafx.tools.fxd.container.scene.fxd.*; import java.util.ArrayList; import java.util.List; /** * * @author Pavel Benes */ public final class FXDDocumentModelProvider implements DocumentModelProvider { private static final Map<String,String> NO_ATTRS = new HashMap<String,String>(1); private static final class NodeBuilder { private final String m_typeName; private final int m_startOffset; /** map with node's attributes */ private final Map<String,String> m_attributes = new HashMap<String, String>(); /** map with child attributes that have Node or List with Nodes as value. * Is used to check if child nodes should be removed from the model. * The only possible way because ContentHandler doesn't give relations between nodes. */ private final Map<String, Object> m_childNodes = new HashMap<String, Object>(); private NodeBuilder( String typeName, int startOff) { m_typeName = typeName; m_startOffset = startOff; } public Map<String,String> getAttributeMap() { return m_attributes; } protected void addAttribute( String name, String value, int startOff, int endOff) { if ( !m_attributes.containsKey(name)) { m_attributes.put(name, value); } } protected void build(DocumentModelModificationTransaction trans, int endOffset) throws BadLocationException, DocumentModelTransactionCancelledException { trans.addDocumentElement( m_typeName, FXDFileModel.FXD_NODE, m_attributes, m_startOffset, endOffset); } /** * checks if DocumentElement type and name are equal to current node * @param de * @return */ public boolean isEqual(final DocumentElement de) { assert de != null; return FXDFileModel.FXD_NODE.equals(de.getType()) && m_typeName.equals(de.getName()); } /** * Checks if given AttributeSet describes the same list of attributes as * current node contain. * @param attrs * @return */ public boolean areAttributesEqual(final AttributeSet attrs) { assert attrs != null; if ( attrs.getAttributeCount() == m_attributes.size()) { for (Entry<String, String> entry : m_attributes.entrySet()) { String value1 = entry.getValue(); Object value2 = attrs.getAttribute(entry.getKey()); if ( value1 != value2) { if ( value1 == null || !value1.equals(value2)) { return false; } } } return true; } return false; } @Override public String toString() { return "NodeBuilder [name="+m_typeName+" startOff="+m_startOffset+"]"; } /** * returns map with attributes that contain Node or List of Nodes as value. * @return Map with pairs (name,value). */ protected Map<String, Object> getChildNodesMap(){ return m_childNodes; } /** * adds Node or List with nodes to the map with child Nodes. * Do not add attributes that has primitive value or array of primitives as value. * @param name - name of the attribute that has given Node or * List of Nodes as value. * @param value Node or List of Nodes */ protected void addNodeToChildrenMap(String name, Object value) { if (!m_childNodes.containsKey(name)) { m_childNodes.put(name, value); } } protected boolean hasNodeInAttrValue(String nodeName) { Object attrNodeName = getChildNodesMap().get(nodeName); // attr is not present in updated node or it's type is changed to array. if ((attrNodeName == null || !(attrNodeName instanceof String))) { return false; } return true; } protected List<String> getNodesNamesFromAttrValue(String nodeName) { Object nodesList = getChildNodesMap().get(nodeName); if (nodesList != null && nodesList instanceof List) { return (List<String>) nodesList; } else { return new ArrayList<String>(); } } } public static final String PROP_PARSE_ERROR = "parse-error"; // NOI18N /* private static FXDNode s_root = null; public static synchronized FXDNode getRoot() { return s_root; }*/ public synchronized void updateModel(final DocumentModelModificationTransaction trans, final DocumentModel model, final DocumentChange[] changes) throws DocumentModelException, DocumentModelTransactionCancelledException { //DocumentModelUtils.dumpElementStructure( model.getRootElement()); BaseDocument doc = (BaseDocument) model.getDocument(); final DataObject dObj = NbEditorUtilities.getDataObject(doc); DocumentElement rootDE = model.getRootElement(); if ( rootDE.getElementCount() == 1) { DocumentElement childDE = rootDE.getElement(0); if ( FXDFileModel.isError(childDE)) { trans.removeDocumentElement(rootDE.getElement(0), true); } } Reader docReader = new CharSeqReader(doc.getText()); final StringBuilder statMsg = new StringBuilder(" "); // NOI18N try { FXDParser fxdParser = new FXDParser(docReader, new ContentHandler() { /** is last processed element was node or not (then array) */ private boolean m_isLastNode = true; /** last processed element - String (Node name) * or List<String> ( array attribute with nodes == list of node names) */ private Object m_lastElem = null; public Object startNode(String typeName, int startOff, boolean isExtension) { return new NodeBuilder(typeName, startOff); } public void attribute(Object node, String name, String value, int startOff, int endOff, boolean isMeta) throws FXDException { NodeBuilder deb = (NodeBuilder) node; if ( value == null) { try { if ( m_isLastNode) { //System.err.println(String.format("Adding attribute %s <%d, %d>", name, startOff, endOff)); trans.addDocumentElement(name, FXDFileModel.FXD_ATTRIBUTE, NO_ATTRS, startOff, endOff); } else { //System.err.println(String.format("Adding array attribute %s <%d, %d>", name, startOff, endOff)); trans.addDocumentElement(name, FXDFileModel.FXD_ATTRIBUTE_ARRAY, NO_ATTRS, startOff, endOff); } deb.addNodeToChildrenMap(name, m_lastElem); m_lastElem = null; } catch( Exception e) { throw new FXDException(e); } } // TODO parse value. This will allow to handle functions and references // TODO handle meta separately deb.addAttribute( name, value, startOff, endOff); } public void endNode(Object node, int endOff) throws FXDException { //System.err.println("Node ended"); NodeBuilder deb = (NodeBuilder) node; DocumentElement de = model.getLeafElementForOffset(deb.m_startOffset); try { if ( de != model.getRootElement() && deb.isEqual(de)) { if ( !deb.areAttributesEqual(de.getAttributes())) { //System.err.println("Attributes changes for " + deb.m_typeName); trans.updateDocumentElementAttribs(de, deb.getAttributeMap()); } synchRemovedChildNodes(deb, de); } else { deb.build(trans, endOff); } } catch( Exception e) { throw new FXDException(e); } m_isLastNode = true; m_lastElem = deb.m_typeName; } private void synchRemovedChildNodes(NodeBuilder deb, DocumentElement de) throws DocumentModelTransactionCancelledException { List<DocumentElement> deChildren = de.getChildren(); for (DocumentElement deChild : deChildren) { if (FXDFileModel.FXD_ATTRIBUTE_ARRAY.equals(deChild.getType())) { - synchArrayOfChildNodes(deb, de); + synchArrayOfChildNodes(deb, deChild); } else if (FXDFileModel.FXD_ATTRIBUTE.equals(deChild.getType())) { if (!deb.hasNodeInAttrValue(deChild.getName())) { trans.removeDocumentElement(deChild, true); } } } } private void synchArrayOfChildNodes(NodeBuilder deb, DocumentElement de) throws DocumentModelTransactionCancelledException { List<String> nodeNamesList = deb.getNodesNamesFromAttrValue(de.getName()); for (DocumentElement child : de.getChildren()) { if (FXDFileModel.FXD_NODE.equals(child.getType())) { + // TODO: fix the case when one of children with same names was removed. + // e.g. content with several polygons. if (!nodeNamesList.contains(child.getName())) { trans.removeDocumentElement(child, true); } } } } public Object startNodeArray(int startOff) { //System.err.println("Array started"); return new ArrayList<String>(); } public void arrayElement(Object array, String value, int startOff, int endOff) throws FXDException { if ( value != null) { try { trans.addDocumentElement(value, FXDFileModel.FXD_ARRAY_ELEM, NO_ATTRS, startOff, endOff); } catch (Exception ex) { throw new FXDException( ex); } } else { ((List)array).add(m_lastElem); m_lastElem = null; } } public void endNodeArray(Object array, int endOff) { m_lastElem = array; m_isLastNode = false; } public void parsingStarted(FXDParser parser) { // do nothing. we do not need parser onstance } public FXDReference createReference(String str) throws FXDException { // TODO: should implement? // implementation is necessary if we parse attribute or array element value. // But we use them as they come. return null; } }); showStatusText(dObj, " Parsing text..."); // NOI18N fxdParser.parseObject(); reportDeletedElements(trans, model.getRootElement()); doc.putProperty( PROP_PARSE_ERROR, null); } catch( DocumentModelTransactionCancelledException e) { //s_root = null; throw e; } catch (Exception ex) { if ( ex instanceof FXDSyntaxErrorException) { statMsg.append( "Syntax error: "); //NOI18N } else { statMsg.append( "Unknown error: "); //NOI18N } String msg = ex.getLocalizedMessage(); statMsg.append(msg); doc.putProperty( PROP_PARSE_ERROR, msg); cleanModel(trans, model); try { trans.addDocumentElement("Invalid FXD syntax", FXDFileModel.FXD_ERROR, NO_ATTRS, 0, doc.getLength()); // NOI18N } catch (BadLocationException ex1) { Exceptions.printStackTrace(ex1); } } finally { showStatusText(dObj, statMsg.toString()); } } protected static void showStatusText( DataObject dObj, final String msg) { final EditorCookie ec = dObj.getCookie( EditorCookie.class); if ( ec != null) { SwingUtilities.invokeLater( new Runnable() { public void run() { final JEditorPane [] panes = ec.getOpenedPanes(); if ( panes != null && panes.length > 0 && panes[0] != null) { EditorUI eui = Utilities.getEditorUI(panes[0]); StatusBar sb = eui == null ? null : eui.getStatusBar(); if (sb != null) { sb.setText(SourceEditorWrapper.CELL_ERROR, msg); } } } }); } } protected void cleanModel( final DocumentModelModificationTransaction trans, DocumentModel model) throws DocumentModelTransactionCancelledException { DocumentElement root = model.getRootElement(); for ( int i = root.getElementCount() - 1; i >= 0; i--) { trans.removeDocumentElement( root.getElement(i), true); } } protected void reportDeletedElements(final DocumentModelModificationTransaction trans, DocumentElement de) throws DocumentModelTransactionCancelledException { assert de != null; if ( de.getStartOffset() == de.getEndOffset()) { trans.removeDocumentElement(de, true); } else { for (int i = de.getElementCount()-1; i >= 0; i--) { reportDeletedElements(trans, de.getElement(i)); } } } }
false
true
public synchronized void updateModel(final DocumentModelModificationTransaction trans, final DocumentModel model, final DocumentChange[] changes) throws DocumentModelException, DocumentModelTransactionCancelledException { //DocumentModelUtils.dumpElementStructure( model.getRootElement()); BaseDocument doc = (BaseDocument) model.getDocument(); final DataObject dObj = NbEditorUtilities.getDataObject(doc); DocumentElement rootDE = model.getRootElement(); if ( rootDE.getElementCount() == 1) { DocumentElement childDE = rootDE.getElement(0); if ( FXDFileModel.isError(childDE)) { trans.removeDocumentElement(rootDE.getElement(0), true); } } Reader docReader = new CharSeqReader(doc.getText()); final StringBuilder statMsg = new StringBuilder(" "); // NOI18N try { FXDParser fxdParser = new FXDParser(docReader, new ContentHandler() { /** is last processed element was node or not (then array) */ private boolean m_isLastNode = true; /** last processed element - String (Node name) * or List<String> ( array attribute with nodes == list of node names) */ private Object m_lastElem = null; public Object startNode(String typeName, int startOff, boolean isExtension) { return new NodeBuilder(typeName, startOff); } public void attribute(Object node, String name, String value, int startOff, int endOff, boolean isMeta) throws FXDException { NodeBuilder deb = (NodeBuilder) node; if ( value == null) { try { if ( m_isLastNode) { //System.err.println(String.format("Adding attribute %s <%d, %d>", name, startOff, endOff)); trans.addDocumentElement(name, FXDFileModel.FXD_ATTRIBUTE, NO_ATTRS, startOff, endOff); } else { //System.err.println(String.format("Adding array attribute %s <%d, %d>", name, startOff, endOff)); trans.addDocumentElement(name, FXDFileModel.FXD_ATTRIBUTE_ARRAY, NO_ATTRS, startOff, endOff); } deb.addNodeToChildrenMap(name, m_lastElem); m_lastElem = null; } catch( Exception e) { throw new FXDException(e); } } // TODO parse value. This will allow to handle functions and references // TODO handle meta separately deb.addAttribute( name, value, startOff, endOff); } public void endNode(Object node, int endOff) throws FXDException { //System.err.println("Node ended"); NodeBuilder deb = (NodeBuilder) node; DocumentElement de = model.getLeafElementForOffset(deb.m_startOffset); try { if ( de != model.getRootElement() && deb.isEqual(de)) { if ( !deb.areAttributesEqual(de.getAttributes())) { //System.err.println("Attributes changes for " + deb.m_typeName); trans.updateDocumentElementAttribs(de, deb.getAttributeMap()); } synchRemovedChildNodes(deb, de); } else { deb.build(trans, endOff); } } catch( Exception e) { throw new FXDException(e); } m_isLastNode = true; m_lastElem = deb.m_typeName; } private void synchRemovedChildNodes(NodeBuilder deb, DocumentElement de) throws DocumentModelTransactionCancelledException { List<DocumentElement> deChildren = de.getChildren(); for (DocumentElement deChild : deChildren) { if (FXDFileModel.FXD_ATTRIBUTE_ARRAY.equals(deChild.getType())) { synchArrayOfChildNodes(deb, de); } else if (FXDFileModel.FXD_ATTRIBUTE.equals(deChild.getType())) { if (!deb.hasNodeInAttrValue(deChild.getName())) { trans.removeDocumentElement(deChild, true); } } } } private void synchArrayOfChildNodes(NodeBuilder deb, DocumentElement de) throws DocumentModelTransactionCancelledException { List<String> nodeNamesList = deb.getNodesNamesFromAttrValue(de.getName()); for (DocumentElement child : de.getChildren()) { if (FXDFileModel.FXD_NODE.equals(child.getType())) { if (!nodeNamesList.contains(child.getName())) { trans.removeDocumentElement(child, true); } } } } public Object startNodeArray(int startOff) { //System.err.println("Array started"); return new ArrayList<String>(); } public void arrayElement(Object array, String value, int startOff, int endOff) throws FXDException { if ( value != null) { try { trans.addDocumentElement(value, FXDFileModel.FXD_ARRAY_ELEM, NO_ATTRS, startOff, endOff); } catch (Exception ex) { throw new FXDException( ex); } } else { ((List)array).add(m_lastElem); m_lastElem = null; } } public void endNodeArray(Object array, int endOff) { m_lastElem = array; m_isLastNode = false; } public void parsingStarted(FXDParser parser) { // do nothing. we do not need parser onstance } public FXDReference createReference(String str) throws FXDException { // TODO: should implement? // implementation is necessary if we parse attribute or array element value. // But we use them as they come. return null; } }); showStatusText(dObj, " Parsing text..."); // NOI18N fxdParser.parseObject(); reportDeletedElements(trans, model.getRootElement()); doc.putProperty( PROP_PARSE_ERROR, null); } catch( DocumentModelTransactionCancelledException e) { //s_root = null; throw e; } catch (Exception ex) { if ( ex instanceof FXDSyntaxErrorException) { statMsg.append( "Syntax error: "); //NOI18N } else { statMsg.append( "Unknown error: "); //NOI18N } String msg = ex.getLocalizedMessage(); statMsg.append(msg); doc.putProperty( PROP_PARSE_ERROR, msg); cleanModel(trans, model); try { trans.addDocumentElement("Invalid FXD syntax", FXDFileModel.FXD_ERROR, NO_ATTRS, 0, doc.getLength()); // NOI18N } catch (BadLocationException ex1) { Exceptions.printStackTrace(ex1); } } finally { showStatusText(dObj, statMsg.toString()); } }
public synchronized void updateModel(final DocumentModelModificationTransaction trans, final DocumentModel model, final DocumentChange[] changes) throws DocumentModelException, DocumentModelTransactionCancelledException { //DocumentModelUtils.dumpElementStructure( model.getRootElement()); BaseDocument doc = (BaseDocument) model.getDocument(); final DataObject dObj = NbEditorUtilities.getDataObject(doc); DocumentElement rootDE = model.getRootElement(); if ( rootDE.getElementCount() == 1) { DocumentElement childDE = rootDE.getElement(0); if ( FXDFileModel.isError(childDE)) { trans.removeDocumentElement(rootDE.getElement(0), true); } } Reader docReader = new CharSeqReader(doc.getText()); final StringBuilder statMsg = new StringBuilder(" "); // NOI18N try { FXDParser fxdParser = new FXDParser(docReader, new ContentHandler() { /** is last processed element was node or not (then array) */ private boolean m_isLastNode = true; /** last processed element - String (Node name) * or List<String> ( array attribute with nodes == list of node names) */ private Object m_lastElem = null; public Object startNode(String typeName, int startOff, boolean isExtension) { return new NodeBuilder(typeName, startOff); } public void attribute(Object node, String name, String value, int startOff, int endOff, boolean isMeta) throws FXDException { NodeBuilder deb = (NodeBuilder) node; if ( value == null) { try { if ( m_isLastNode) { //System.err.println(String.format("Adding attribute %s <%d, %d>", name, startOff, endOff)); trans.addDocumentElement(name, FXDFileModel.FXD_ATTRIBUTE, NO_ATTRS, startOff, endOff); } else { //System.err.println(String.format("Adding array attribute %s <%d, %d>", name, startOff, endOff)); trans.addDocumentElement(name, FXDFileModel.FXD_ATTRIBUTE_ARRAY, NO_ATTRS, startOff, endOff); } deb.addNodeToChildrenMap(name, m_lastElem); m_lastElem = null; } catch( Exception e) { throw new FXDException(e); } } // TODO parse value. This will allow to handle functions and references // TODO handle meta separately deb.addAttribute( name, value, startOff, endOff); } public void endNode(Object node, int endOff) throws FXDException { //System.err.println("Node ended"); NodeBuilder deb = (NodeBuilder) node; DocumentElement de = model.getLeafElementForOffset(deb.m_startOffset); try { if ( de != model.getRootElement() && deb.isEqual(de)) { if ( !deb.areAttributesEqual(de.getAttributes())) { //System.err.println("Attributes changes for " + deb.m_typeName); trans.updateDocumentElementAttribs(de, deb.getAttributeMap()); } synchRemovedChildNodes(deb, de); } else { deb.build(trans, endOff); } } catch( Exception e) { throw new FXDException(e); } m_isLastNode = true; m_lastElem = deb.m_typeName; } private void synchRemovedChildNodes(NodeBuilder deb, DocumentElement de) throws DocumentModelTransactionCancelledException { List<DocumentElement> deChildren = de.getChildren(); for (DocumentElement deChild : deChildren) { if (FXDFileModel.FXD_ATTRIBUTE_ARRAY.equals(deChild.getType())) { synchArrayOfChildNodes(deb, deChild); } else if (FXDFileModel.FXD_ATTRIBUTE.equals(deChild.getType())) { if (!deb.hasNodeInAttrValue(deChild.getName())) { trans.removeDocumentElement(deChild, true); } } } } private void synchArrayOfChildNodes(NodeBuilder deb, DocumentElement de) throws DocumentModelTransactionCancelledException { List<String> nodeNamesList = deb.getNodesNamesFromAttrValue(de.getName()); for (DocumentElement child : de.getChildren()) { if (FXDFileModel.FXD_NODE.equals(child.getType())) { // TODO: fix the case when one of children with same names was removed. // e.g. content with several polygons. if (!nodeNamesList.contains(child.getName())) { trans.removeDocumentElement(child, true); } } } } public Object startNodeArray(int startOff) { //System.err.println("Array started"); return new ArrayList<String>(); } public void arrayElement(Object array, String value, int startOff, int endOff) throws FXDException { if ( value != null) { try { trans.addDocumentElement(value, FXDFileModel.FXD_ARRAY_ELEM, NO_ATTRS, startOff, endOff); } catch (Exception ex) { throw new FXDException( ex); } } else { ((List)array).add(m_lastElem); m_lastElem = null; } } public void endNodeArray(Object array, int endOff) { m_lastElem = array; m_isLastNode = false; } public void parsingStarted(FXDParser parser) { // do nothing. we do not need parser onstance } public FXDReference createReference(String str) throws FXDException { // TODO: should implement? // implementation is necessary if we parse attribute or array element value. // But we use them as they come. return null; } }); showStatusText(dObj, " Parsing text..."); // NOI18N fxdParser.parseObject(); reportDeletedElements(trans, model.getRootElement()); doc.putProperty( PROP_PARSE_ERROR, null); } catch( DocumentModelTransactionCancelledException e) { //s_root = null; throw e; } catch (Exception ex) { if ( ex instanceof FXDSyntaxErrorException) { statMsg.append( "Syntax error: "); //NOI18N } else { statMsg.append( "Unknown error: "); //NOI18N } String msg = ex.getLocalizedMessage(); statMsg.append(msg); doc.putProperty( PROP_PARSE_ERROR, msg); cleanModel(trans, model); try { trans.addDocumentElement("Invalid FXD syntax", FXDFileModel.FXD_ERROR, NO_ATTRS, 0, doc.getLength()); // NOI18N } catch (BadLocationException ex1) { Exceptions.printStackTrace(ex1); } } finally { showStatusText(dObj, statMsg.toString()); } }
diff --git a/GAE/src/com/gallatinsystems/framework/dataexport/applet/DataExportAppletImpl.java b/GAE/src/com/gallatinsystems/framework/dataexport/applet/DataExportAppletImpl.java index 99fc27490..45e7eec74 100644 --- a/GAE/src/com/gallatinsystems/framework/dataexport/applet/DataExportAppletImpl.java +++ b/GAE/src/com/gallatinsystems/framework/dataexport/applet/DataExportAppletImpl.java @@ -1,97 +1,102 @@ /* * Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo FLOW. * * Akvo FLOW is free software: you can redistribute it and modify it under the terms of * the GNU Affero General Public License (AGPL) as published by the Free Software Foundation, * either version 3 of the License or any later version. * * Akvo FLOW 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 included below for more details. * * The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>. */ package com.gallatinsystems.framework.dataexport.applet; import java.io.File; import java.util.Map; import javax.swing.JFileChooser; import javax.swing.JLabel; import org.waterforpeople.mapping.dataexport.RawDataExporter; /** * simple applet to allow us to export data from google app engine * * @author Christopher Fagiani * */ public class DataExportAppletImpl extends AbstractDataImportExportApplet { private static final long serialVersionUID = 944163825066341210L; private static final String EXPORT_TYPE_PARAM = "exportType"; private static final String OPTIONS_PARAM = "options"; private JLabel statusLabel; private DataImportExportFactory dataExporterFactory; private Boolean useTabFlag = false; /** * initializes the UI, constructs the exporter factory then invokes the * export method. */ public void init() { statusLabel = new JLabel(); getContentPane().add(statusLabel); String type = getParameter(EXPORT_TYPE_PARAM); dataExporterFactory = getDataImportExportFactory(); doExport(type, getConfigCriteria(), getServerBase(), parseCriteria(getParameter(OPTIONS_PARAM))); } /** * launches a JFileChooser to prompt the user to specify an output file. If * the file is supplied, will then invoke the export method on the exporter * returned from the factory.. * * @param type * @param criteriaMap * @param serverBase * @param options */ public void doExport(String type, Map<String, String> criteriaMap, String serverBase, Map<String, String> options) { final JFileChooser chooser = new JFileChooser(); final String surveyId = criteriaMap.containsKey("surveyId") ? criteriaMap .get("surveyId") : null; + String exportType = criteriaMap.get("exportType"); + String ext = ".xlsx"; + if (exportType != null && exportType.equalsIgnoreCase("SURVEY_FORM")) { + ext = ".xls"; + } final String fileName = type + (surveyId != null ? "-" + surveyId : "") - + ".xls"; + + ext; chooser.setSelectedFile(new File(fileName)); chooser.showSaveDialog(this); if (chooser.getSelectedFile() != null) { DataExporter exporter = dataExporterFactory.getExporter(type); statusLabel.setText("Exporting..."); if (serverBase.trim().endsWith("/")) { serverBase = serverBase.trim().substring(0, serverBase.lastIndexOf("/")); } if(options.containsKey("generateTabFormat")){ if(options.get("generateTabFormat").trim()!=null && !options.get("generateTabFormat").trim().equalsIgnoreCase("")) useTabFlag = Boolean.parseBoolean(options.get("generateTabFormat")); } if (type.equalsIgnoreCase("RAW_DATA")&&useTabFlag) { RawDataExporter rde = new RawDataExporter(); rde.export(criteriaMap , chooser.getSelectedFile(), serverBase, options); } else { exporter.export(criteriaMap, chooser.getSelectedFile(), serverBase, options); } statusLabel.setText("Export Complete"); } } }
false
true
public void doExport(String type, Map<String, String> criteriaMap, String serverBase, Map<String, String> options) { final JFileChooser chooser = new JFileChooser(); final String surveyId = criteriaMap.containsKey("surveyId") ? criteriaMap .get("surveyId") : null; final String fileName = type + (surveyId != null ? "-" + surveyId : "") + ".xls"; chooser.setSelectedFile(new File(fileName)); chooser.showSaveDialog(this); if (chooser.getSelectedFile() != null) { DataExporter exporter = dataExporterFactory.getExporter(type); statusLabel.setText("Exporting..."); if (serverBase.trim().endsWith("/")) { serverBase = serverBase.trim().substring(0, serverBase.lastIndexOf("/")); } if(options.containsKey("generateTabFormat")){ if(options.get("generateTabFormat").trim()!=null && !options.get("generateTabFormat").trim().equalsIgnoreCase("")) useTabFlag = Boolean.parseBoolean(options.get("generateTabFormat")); } if (type.equalsIgnoreCase("RAW_DATA")&&useTabFlag) { RawDataExporter rde = new RawDataExporter(); rde.export(criteriaMap , chooser.getSelectedFile(), serverBase, options); } else { exporter.export(criteriaMap, chooser.getSelectedFile(), serverBase, options); } statusLabel.setText("Export Complete"); } }
public void doExport(String type, Map<String, String> criteriaMap, String serverBase, Map<String, String> options) { final JFileChooser chooser = new JFileChooser(); final String surveyId = criteriaMap.containsKey("surveyId") ? criteriaMap .get("surveyId") : null; String exportType = criteriaMap.get("exportType"); String ext = ".xlsx"; if (exportType != null && exportType.equalsIgnoreCase("SURVEY_FORM")) { ext = ".xls"; } final String fileName = type + (surveyId != null ? "-" + surveyId : "") + ext; chooser.setSelectedFile(new File(fileName)); chooser.showSaveDialog(this); if (chooser.getSelectedFile() != null) { DataExporter exporter = dataExporterFactory.getExporter(type); statusLabel.setText("Exporting..."); if (serverBase.trim().endsWith("/")) { serverBase = serverBase.trim().substring(0, serverBase.lastIndexOf("/")); } if(options.containsKey("generateTabFormat")){ if(options.get("generateTabFormat").trim()!=null && !options.get("generateTabFormat").trim().equalsIgnoreCase("")) useTabFlag = Boolean.parseBoolean(options.get("generateTabFormat")); } if (type.equalsIgnoreCase("RAW_DATA")&&useTabFlag) { RawDataExporter rde = new RawDataExporter(); rde.export(criteriaMap , chooser.getSelectedFile(), serverBase, options); } else { exporter.export(criteriaMap, chooser.getSelectedFile(), serverBase, options); } statusLabel.setText("Export Complete"); } }
diff --git a/src/main/java/org/neo4j/admin/tool/pruneloop/Main.java b/src/main/java/org/neo4j/admin/tool/pruneloop/Main.java index 3222aea..c2dbd28 100644 --- a/src/main/java/org/neo4j/admin/tool/pruneloop/Main.java +++ b/src/main/java/org/neo4j/admin/tool/pruneloop/Main.java @@ -1,170 +1,168 @@ /** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.admin.tool.pruneloop; import java.util.HashSet; import java.util.Set; import org.neo4j.admin.tool.RecordProcessor; import org.neo4j.admin.tool.SimpleStoreTool; import org.neo4j.kernel.impl.nioneo.store.Filter; import org.neo4j.kernel.impl.nioneo.store.NodeRecord; import org.neo4j.kernel.impl.nioneo.store.NodeStoreAccess; import org.neo4j.kernel.impl.nioneo.store.RelationshipRecord; import org.neo4j.kernel.impl.nioneo.store.RelationshipStoreAccess; public class Main extends SimpleStoreTool implements RecordProcessor<NodeRecord> { private final RelationshipStoreAccess rels = store.getRelStore(); private final NodeStoreAccess nodes = store.getNodeStore(); private final long[] rootNodes; Main( String[] args ) { super( args ); rootNodes = new long[args.length - 1]; for ( int i = 0; i < rootNodes.length; i++ ) { rootNodes[i] = Long.parseLong( args[i + 1] ); } } public static void main( String[] args ) throws Throwable { main( Main.class, args ); } @Override @SuppressWarnings( "unchecked" ) protected void run() throws Throwable { if ( rootNodes.length > 0 ) for ( long startNode : rootNodes ) { fixChainOf( startNode, nodes.forceGetRecord( startNode ) ); } else process( this, nodes, Filter.IN_USE ); } @Override public void process( NodeRecord record ) { fixChainOf( record.getId(), record ); } private void fixChainOf( final long nodeId, final NodeRecord node ) { Set<Long> seen = new HashSet<Long>(); RelationshipRecord rel = null; - for ( long curId = node.getNextRel(), prevId = RelationshipStoreAccess.NO_NEXT_RECORD, nextId; curId != RelationshipStoreAccess.NO_NEXT_RECORD; prevId = curId, curId = nextId ) + for ( long curId = node.getNextRel(), prevId = RelationshipStoreAccess.NO_NEXT_RECORD, nextId = prevId; curId != RelationshipStoreAccess.NO_NEXT_RECORD; prevId = curId, curId = nextId ) { RelationshipRecord prev = rel; rel = rels.forceGetRecord( curId ); boolean linked = false; if ( rel.inUse() ) { if ( rel.getFirstNode() == nodeId ) { nextId = rel.getFirstNextRel(); boolean fixed = false; try { if ( rel.getFirstPrevRel() != prevId ) { rel.setFirstPrevRel( prevId ); fixed = true; } if ( !seen.add( Long.valueOf( nextId ) ) ) { rel.setFirstNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); fixed = true; return; } } finally { if ( fixed ) { System.out.println( rel ); rels.forceUpdateRecord( rel ); } linked = true; } } if ( rel.getSecondNode() == nodeId ) { nextId = rel.getSecondNextRel(); boolean fixed = false; try { if ( rel.getSecondPrevRel() != prevId ) { rel.setSecondPrevRel( prevId ); fixed = true; } if ( !seen.add( Long.valueOf( nextId ) ) ) { rel.setSecondNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); fixed = true; return; } } finally { if ( fixed ) { System.out.println( rel ); rels.forceUpdateRecord( rel ); } linked = true; } } } if ( !linked ) { // the relationship did not reference the node - break the chain if ( prev != null ) { // in the middle of the chain if ( prev.getFirstNode() == nodeId ) { prev.setFirstNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); } if ( prev.getSecondNode() == nodeId ) { prev.setSecondNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); } System.out.println( prev ); rels.forceUpdateRecord( prev ); return; // chain broken } else { // in the start of the chain node.setNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); System.out.println( node ); nodes.forceUpdateRecord( node ); return; // chain broken } } - else - return; // should never happen } } }
false
true
private void fixChainOf( final long nodeId, final NodeRecord node ) { Set<Long> seen = new HashSet<Long>(); RelationshipRecord rel = null; for ( long curId = node.getNextRel(), prevId = RelationshipStoreAccess.NO_NEXT_RECORD, nextId; curId != RelationshipStoreAccess.NO_NEXT_RECORD; prevId = curId, curId = nextId ) { RelationshipRecord prev = rel; rel = rels.forceGetRecord( curId ); boolean linked = false; if ( rel.inUse() ) { if ( rel.getFirstNode() == nodeId ) { nextId = rel.getFirstNextRel(); boolean fixed = false; try { if ( rel.getFirstPrevRel() != prevId ) { rel.setFirstPrevRel( prevId ); fixed = true; } if ( !seen.add( Long.valueOf( nextId ) ) ) { rel.setFirstNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); fixed = true; return; } } finally { if ( fixed ) { System.out.println( rel ); rels.forceUpdateRecord( rel ); } linked = true; } } if ( rel.getSecondNode() == nodeId ) { nextId = rel.getSecondNextRel(); boolean fixed = false; try { if ( rel.getSecondPrevRel() != prevId ) { rel.setSecondPrevRel( prevId ); fixed = true; } if ( !seen.add( Long.valueOf( nextId ) ) ) { rel.setSecondNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); fixed = true; return; } } finally { if ( fixed ) { System.out.println( rel ); rels.forceUpdateRecord( rel ); } linked = true; } } } if ( !linked ) { // the relationship did not reference the node - break the chain if ( prev != null ) { // in the middle of the chain if ( prev.getFirstNode() == nodeId ) { prev.setFirstNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); } if ( prev.getSecondNode() == nodeId ) { prev.setSecondNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); } System.out.println( prev ); rels.forceUpdateRecord( prev ); return; // chain broken } else { // in the start of the chain node.setNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); System.out.println( node ); nodes.forceUpdateRecord( node ); return; // chain broken } } else return; // should never happen } }
private void fixChainOf( final long nodeId, final NodeRecord node ) { Set<Long> seen = new HashSet<Long>(); RelationshipRecord rel = null; for ( long curId = node.getNextRel(), prevId = RelationshipStoreAccess.NO_NEXT_RECORD, nextId = prevId; curId != RelationshipStoreAccess.NO_NEXT_RECORD; prevId = curId, curId = nextId ) { RelationshipRecord prev = rel; rel = rels.forceGetRecord( curId ); boolean linked = false; if ( rel.inUse() ) { if ( rel.getFirstNode() == nodeId ) { nextId = rel.getFirstNextRel(); boolean fixed = false; try { if ( rel.getFirstPrevRel() != prevId ) { rel.setFirstPrevRel( prevId ); fixed = true; } if ( !seen.add( Long.valueOf( nextId ) ) ) { rel.setFirstNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); fixed = true; return; } } finally { if ( fixed ) { System.out.println( rel ); rels.forceUpdateRecord( rel ); } linked = true; } } if ( rel.getSecondNode() == nodeId ) { nextId = rel.getSecondNextRel(); boolean fixed = false; try { if ( rel.getSecondPrevRel() != prevId ) { rel.setSecondPrevRel( prevId ); fixed = true; } if ( !seen.add( Long.valueOf( nextId ) ) ) { rel.setSecondNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); fixed = true; return; } } finally { if ( fixed ) { System.out.println( rel ); rels.forceUpdateRecord( rel ); } linked = true; } } } if ( !linked ) { // the relationship did not reference the node - break the chain if ( prev != null ) { // in the middle of the chain if ( prev.getFirstNode() == nodeId ) { prev.setFirstNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); } if ( prev.getSecondNode() == nodeId ) { prev.setSecondNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); } System.out.println( prev ); rels.forceUpdateRecord( prev ); return; // chain broken } else { // in the start of the chain node.setNextRel( RelationshipStoreAccess.NO_NEXT_RECORD ); System.out.println( node ); nodes.forceUpdateRecord( node ); return; // chain broken } } } }
diff --git a/src/aiml/classifier/ContextNode.java b/src/aiml/classifier/ContextNode.java index f435e0a..631b7d6 100644 --- a/src/aiml/classifier/ContextNode.java +++ b/src/aiml/classifier/ContextNode.java @@ -1,169 +1,166 @@ /* jaiml - java AIML library Copyright (C) 2004, 2009 Kim Sullivan This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package aiml.classifier; import graphviz.Graphviz; import graphviz.GraphvizNode; import aiml.classifier.PaternSequence.PatternIterator; import aiml.classifier.node.PatternNode; import aiml.context.Context; /** * <p> * This class represents a node in the tree of contexts. Each context imposes * another constraint on the state of the matching system. * </p> * * @author Kim Sullivan * @version 1.0 */ public abstract class ContextNode implements GraphvizNode { /** The context this tree applies to */ Context<? extends Object> context; /** The classifier this context node is a part of */ Classifier classifier; /** * the next lower context (subcontext), used when we fail matching to this * context's pattern tree or if there wasn't any pattern tree in the first * place (the latter shouldn't happen - if there are no patterns, there should * not be a context tree for them) */ ContextNode next; protected ContextNode(Classifier classifier, Context<? extends Object> context) { this.classifier = classifier; this.context = context; } /** * Adds the remaining patterns in a sequence to this node. Creates all * necessary pattern subtrees and subcontexts, ensures that the proper order * of contexts is maintained. * * @param patterns * remaining patterns in the sequence * @param o * the object to be added to the tree * @throws DuplicatePathException * @return the resulting context tree, with all modifications applied and the * correct ordering. */ public ContextNode add(PatternIterator patterns, Object o) throws DuplicatePathException { /*check the context order, if it's OK to add the current pattern to this context *or if we need to add a new context somewhere. *if we're adding it here, run the rootnode's add() method and * recursively construct the pattern tree for this context. */ if (patterns.hasNext()) { //We're in the middle of the sequence PaternSequence.Pattern pattern = patterns.peek(); if (context.compareTo(pattern.getContext()) < 0) { //add as next if (next == null) { next = pattern.getContext().createClassifierNode(classifier, patterns, null, o); } else { next = next.add(patterns, o); } return this; } else if (context.compareTo(pattern.getContext()) > 0) { //add instead of self - // return pattern.getContext().createClassifierNode(classifier, - // patterns, this, o); - ContextNode cn = pattern.getContext().createClassifierNode(classifier, - patterns, this, o); - return cn.add(patterns, o); //actually, just cn should be sufficient, but let's not make any assumptions + return pattern.getContext().createClassifierNode(classifier, patterns, + this, o); } else { //add the pattern into the current tree. PatternNode leaf = addPattern(pattern); patterns.next(); leaf.addContext(patterns, o); return this; } } else { //we're at the end of the sequence, so we can add a Leaf node if (next == null) { next = new LeafContextNode(classifier, o); } else { next = next.add(patterns, o); } return this; } } /** * Adds a pattern to this context. * * <i>Note:</i> This method will be reworked once generalized context types * are implemented (i.e. it will be replaced by an addGeneralContextType() * method. * * @param pattern * Pattern */ public abstract PatternNode addPattern(PaternSequence.Pattern pattern); public Classifier getClassifier() { return classifier; } /** * Try to match the current match state. * * @param match * MatchState * @return <code>true</code> if a match was found; <code>false</code> if the * match failed */ public abstract boolean match(MatchState match); /** Returns a string representation of this context node */ public String toString() { return "<" + context + ">" + "\n" + "[" + context + ".NEXT]: " + next; } public String gvNodeID() { return "ContextNode_" + context + "_" + hashCode(); } public String gvNodeLabel() { return "<" + context + ">"; } public void gvGraph(Graphviz graph) { gvNodes(graph); gvInternalGraph(graph); gvExternalGraph(graph); } public void gvNodes(Graphviz graph) { graph.node(gvNodeID(), "label", gvNodeLabel()); } public void gvInternalGraph(Graphviz graph) { } public void gvExternalGraph(Graphviz graph) { if (next != null) { graph.edge(gvNodeID(), next.gvNodeID()); next.gvGraph(graph); } } }
true
true
public ContextNode add(PatternIterator patterns, Object o) throws DuplicatePathException { /*check the context order, if it's OK to add the current pattern to this context *or if we need to add a new context somewhere. *if we're adding it here, run the rootnode's add() method and * recursively construct the pattern tree for this context. */ if (patterns.hasNext()) { //We're in the middle of the sequence PaternSequence.Pattern pattern = patterns.peek(); if (context.compareTo(pattern.getContext()) < 0) { //add as next if (next == null) { next = pattern.getContext().createClassifierNode(classifier, patterns, null, o); } else { next = next.add(patterns, o); } return this; } else if (context.compareTo(pattern.getContext()) > 0) { //add instead of self // return pattern.getContext().createClassifierNode(classifier, // patterns, this, o); ContextNode cn = pattern.getContext().createClassifierNode(classifier, patterns, this, o); return cn.add(patterns, o); //actually, just cn should be sufficient, but let's not make any assumptions } else { //add the pattern into the current tree. PatternNode leaf = addPattern(pattern); patterns.next(); leaf.addContext(patterns, o); return this; } } else { //we're at the end of the sequence, so we can add a Leaf node if (next == null) { next = new LeafContextNode(classifier, o); } else { next = next.add(patterns, o); } return this; } }
public ContextNode add(PatternIterator patterns, Object o) throws DuplicatePathException { /*check the context order, if it's OK to add the current pattern to this context *or if we need to add a new context somewhere. *if we're adding it here, run the rootnode's add() method and * recursively construct the pattern tree for this context. */ if (patterns.hasNext()) { //We're in the middle of the sequence PaternSequence.Pattern pattern = patterns.peek(); if (context.compareTo(pattern.getContext()) < 0) { //add as next if (next == null) { next = pattern.getContext().createClassifierNode(classifier, patterns, null, o); } else { next = next.add(patterns, o); } return this; } else if (context.compareTo(pattern.getContext()) > 0) { //add instead of self return pattern.getContext().createClassifierNode(classifier, patterns, this, o); } else { //add the pattern into the current tree. PatternNode leaf = addPattern(pattern); patterns.next(); leaf.addContext(patterns, o); return this; } } else { //we're at the end of the sequence, so we can add a Leaf node if (next == null) { next = new LeafContextNode(classifier, o); } else { next = next.add(patterns, o); } return this; } }
diff --git a/src/classes/com/sun/opengl/impl/macosx/MacOSXOnscreenGLContext.java b/src/classes/com/sun/opengl/impl/macosx/MacOSXOnscreenGLContext.java index f09f24e9d..1e6a263de 100644 --- a/src/classes/com/sun/opengl/impl/macosx/MacOSXOnscreenGLContext.java +++ b/src/classes/com/sun/opengl/impl/macosx/MacOSXOnscreenGLContext.java @@ -1,113 +1,119 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution 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 Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ package com.sun.opengl.impl.macosx; import java.util.*; import javax.media.opengl.*; import com.sun.opengl.impl.*; public class MacOSXOnscreenGLContext extends MacOSXGLContext { protected MacOSXOnscreenGLDrawable drawable; public MacOSXOnscreenGLContext(MacOSXOnscreenGLDrawable drawable, GLContext shareWith) { super(drawable, shareWith); this.drawable = drawable; } protected int makeCurrentImpl() throws GLException { int lockRes = drawable.lockSurface(); try { if (lockRes == MacOSXOnscreenGLDrawable.LOCK_SURFACE_NOT_READY) { return CONTEXT_NOT_CURRENT; } if (lockRes == MacOSXOnscreenGLDrawable.LOCK_SURFACE_CHANGED) { destroyImpl(); } int ret = super.makeCurrentImpl(); if ((ret == CONTEXT_CURRENT) || (ret == CONTEXT_CURRENT_NEW)) { // Assume the canvas might have been resized or moved and tell the OpenGL // context to update itself. This used to be done only upon receiving a // reshape event but that doesn't appear to be sufficient. An experiment // was also done to add a HierarchyBoundsListener to the GLCanvas and // do this updating only upon reshape of this component or reshape or movement // of an ancestor, but this also wasn't sufficient and left garbage on the // screen in some situations. CGL.updateContext(nsContext); + } else { + if (!isOptimizable()) { + // This can happen if the window currently is zero-sized, for example. + // Make sure we don't leave the surface locked in this case. + drawable.unlockSurface(); + } } return ret; } finally { if (isOptimizable()) { if (lockRes != MacOSXOnscreenGLDrawable.LOCK_SURFACE_NOT_READY) { drawable.unlockSurface(); } } } } protected void releaseImpl() throws GLException { try { super.releaseImpl(); } finally { if (!isOptimizable()) { drawable.unlockSurface(); } } } public void swapBuffers() throws GLException { if (!CGL.flushBuffer(nsContext)) { throw new GLException("Error swapping buffers"); } } protected void update() throws GLException { if (nsContext == 0) { throw new GLException("Context not created"); } CGL.updateContext(nsContext); } protected boolean create() { return create(false, false); } }
true
true
protected int makeCurrentImpl() throws GLException { int lockRes = drawable.lockSurface(); try { if (lockRes == MacOSXOnscreenGLDrawable.LOCK_SURFACE_NOT_READY) { return CONTEXT_NOT_CURRENT; } if (lockRes == MacOSXOnscreenGLDrawable.LOCK_SURFACE_CHANGED) { destroyImpl(); } int ret = super.makeCurrentImpl(); if ((ret == CONTEXT_CURRENT) || (ret == CONTEXT_CURRENT_NEW)) { // Assume the canvas might have been resized or moved and tell the OpenGL // context to update itself. This used to be done only upon receiving a // reshape event but that doesn't appear to be sufficient. An experiment // was also done to add a HierarchyBoundsListener to the GLCanvas and // do this updating only upon reshape of this component or reshape or movement // of an ancestor, but this also wasn't sufficient and left garbage on the // screen in some situations. CGL.updateContext(nsContext); } return ret; } finally { if (isOptimizable()) { if (lockRes != MacOSXOnscreenGLDrawable.LOCK_SURFACE_NOT_READY) { drawable.unlockSurface(); } } } }
protected int makeCurrentImpl() throws GLException { int lockRes = drawable.lockSurface(); try { if (lockRes == MacOSXOnscreenGLDrawable.LOCK_SURFACE_NOT_READY) { return CONTEXT_NOT_CURRENT; } if (lockRes == MacOSXOnscreenGLDrawable.LOCK_SURFACE_CHANGED) { destroyImpl(); } int ret = super.makeCurrentImpl(); if ((ret == CONTEXT_CURRENT) || (ret == CONTEXT_CURRENT_NEW)) { // Assume the canvas might have been resized or moved and tell the OpenGL // context to update itself. This used to be done only upon receiving a // reshape event but that doesn't appear to be sufficient. An experiment // was also done to add a HierarchyBoundsListener to the GLCanvas and // do this updating only upon reshape of this component or reshape or movement // of an ancestor, but this also wasn't sufficient and left garbage on the // screen in some situations. CGL.updateContext(nsContext); } else { if (!isOptimizable()) { // This can happen if the window currently is zero-sized, for example. // Make sure we don't leave the surface locked in this case. drawable.unlockSurface(); } } return ret; } finally { if (isOptimizable()) { if (lockRes != MacOSXOnscreenGLDrawable.LOCK_SURFACE_NOT_READY) { drawable.unlockSurface(); } } } }
diff --git a/bodymodel/jnect-modified/org.jnect.demo.gef/src/org/jnect/demo/gef/handler/StartGefHandler.java b/bodymodel/jnect-modified/org.jnect.demo.gef/src/org/jnect/demo/gef/handler/StartGefHandler.java index 70a35671..875f9db2 100644 --- a/bodymodel/jnect-modified/org.jnect.demo.gef/src/org/jnect/demo/gef/handler/StartGefHandler.java +++ b/bodymodel/jnect-modified/org.jnect.demo.gef/src/org/jnect/demo/gef/handler/StartGefHandler.java @@ -1,34 +1,39 @@ /******************************************************************************* * Copyright (c) 2012 jnect.org. * 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: * Eugen Neufeld - initial API and implementation *******************************************************************************/ package org.jnect.demo.gef.handler; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.PlatformUI; import org.jnect.core.KinectManager; import org.jnect.demo.gef.HumanDiagramGraphicalEditor; public class StartGefHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { - KinectManager.INSTANCE.startSkeletonTracking(); + if (!KinectManager.INSTANCE.isStarted()) { + KinectManager.INSTANCE.startKinect(); + } + if (!KinectManager.INSTANCE.isSkeletonTrackingStarted()) { + KinectManager.INSTANCE.startSkeletonTracking(); + } HumanDiagramGraphicalEditor editor = ((HumanDiagramGraphicalEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor()); if (editor!=null) { editor.setContent(KinectManager.INSTANCE.getSkeletonModel()); } return null; } }
true
true
public Object execute(ExecutionEvent event) throws ExecutionException { KinectManager.INSTANCE.startSkeletonTracking(); HumanDiagramGraphicalEditor editor = ((HumanDiagramGraphicalEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor()); if (editor!=null) { editor.setContent(KinectManager.INSTANCE.getSkeletonModel()); } return null; }
public Object execute(ExecutionEvent event) throws ExecutionException { if (!KinectManager.INSTANCE.isStarted()) { KinectManager.INSTANCE.startKinect(); } if (!KinectManager.INSTANCE.isSkeletonTrackingStarted()) { KinectManager.INSTANCE.startSkeletonTracking(); } HumanDiagramGraphicalEditor editor = ((HumanDiagramGraphicalEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor()); if (editor!=null) { editor.setContent(KinectManager.INSTANCE.getSkeletonModel()); } return null; }
diff --git a/src/com/undeadscythes/udsplugin/commands/DemoteCmd.java b/src/com/undeadscythes/udsplugin/commands/DemoteCmd.java index 977c78d..4cdba9a 100644 --- a/src/com/undeadscythes/udsplugin/commands/DemoteCmd.java +++ b/src/com/undeadscythes/udsplugin/commands/DemoteCmd.java @@ -1,27 +1,27 @@ package com.undeadscythes.udsplugin.commands; import com.undeadscythes.udsplugin.*; import com.undeadscythes.udsplugin.SaveablePlayer.PlayerRank; /** * Demote a player by a single rank. * @author UndeadScythes */ public class DemoteCmd extends PlayerCommandExecutor { /** * @inheritDocs */ @Override public void playerExecute(SaveablePlayer player, String[] args) { SaveablePlayer target; if(numArgsHelp(1) && (target = getMatchingPlayer(args[0])) != null && notSelf(target)) { PlayerRank rank; - if((rank = target.demote()) != null) { + if(player.getRank().compareTo(target.getRank()) >= 0 && (rank = target.demote()) != null) { player.sendMessage(Color.MESSAGE + target.getDisplayName() + " has been demoted to " + rank.toString() + "."); target.sendMessage(Color.MESSAGE + "You have been demoted to " + rank.toString() + "."); } else { player.sendMessage(Color.ERROR + "You can't demote this player any further."); } } } }
true
true
public void playerExecute(SaveablePlayer player, String[] args) { SaveablePlayer target; if(numArgsHelp(1) && (target = getMatchingPlayer(args[0])) != null && notSelf(target)) { PlayerRank rank; if((rank = target.demote()) != null) { player.sendMessage(Color.MESSAGE + target.getDisplayName() + " has been demoted to " + rank.toString() + "."); target.sendMessage(Color.MESSAGE + "You have been demoted to " + rank.toString() + "."); } else { player.sendMessage(Color.ERROR + "You can't demote this player any further."); } } }
public void playerExecute(SaveablePlayer player, String[] args) { SaveablePlayer target; if(numArgsHelp(1) && (target = getMatchingPlayer(args[0])) != null && notSelf(target)) { PlayerRank rank; if(player.getRank().compareTo(target.getRank()) >= 0 && (rank = target.demote()) != null) { player.sendMessage(Color.MESSAGE + target.getDisplayName() + " has been demoted to " + rank.toString() + "."); target.sendMessage(Color.MESSAGE + "You have been demoted to " + rank.toString() + "."); } else { player.sendMessage(Color.ERROR + "You can't demote this player any further."); } } }
diff --git a/common/cpw/mods/fml/common/registry/GameRegistry.java b/common/cpw/mods/fml/common/registry/GameRegistry.java index 3e8f5b4f..c504fac2 100644 --- a/common/cpw/mods/fml/common/registry/GameRegistry.java +++ b/common/cpw/mods/fml/common/registry/GameRegistry.java @@ -1,395 +1,397 @@ /* * Forge Mod Loader * Copyright (c) 2012-2013 cpw. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * cpw - implementation */ package cpw.mods.fml.common.registry; import java.lang.reflect.Constructor; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.logging.Level; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraft.item.crafting.IRecipe; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraft.world.WorldType; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.chunk.IChunkProvider; import com.google.common.base.Function; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Sets; import com.google.common.collect.Sets.SetView; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.ICraftingHandler; import cpw.mods.fml.common.IFuelHandler; import cpw.mods.fml.common.IPickupNotifier; import cpw.mods.fml.common.IPlayerTracker; import cpw.mods.fml.common.IWorldGenerator; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.LoaderException; import cpw.mods.fml.common.LoaderState; import cpw.mods.fml.common.ObfuscationReflectionHelper; import cpw.mods.fml.common.Mod.Block; import cpw.mods.fml.common.ModContainer; public class GameRegistry { private static Multimap<ModContainer, BlockProxy> blockRegistry = ArrayListMultimap.create(); private static Set<IWorldGenerator> worldGenerators = Sets.newHashSet(); private static List<IFuelHandler> fuelHandlers = Lists.newArrayList(); private static List<ICraftingHandler> craftingHandlers = Lists.newArrayList(); private static List<IPickupNotifier> pickupHandlers = Lists.newArrayList(); private static List<IPlayerTracker> playerTrackers = Lists.newArrayList(); /** * Register a world generator - something that inserts new block types into the world * * @param generator */ public static void registerWorldGenerator(IWorldGenerator generator) { worldGenerators.add(generator); } /** * Callback hook for world gen - if your mod wishes to add extra mod related generation to the world * call this * * @param chunkX * @param chunkZ * @param world * @param chunkGenerator * @param chunkProvider */ public static void generateWorld(int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { long worldSeed = world.func_72905_C(); Random fmlRandom = new Random(worldSeed); long xSeed = fmlRandom.nextLong() >> 2 + 1L; long zSeed = fmlRandom.nextLong() >> 2 + 1L; fmlRandom.setSeed((xSeed * chunkX + zSeed * chunkZ) ^ worldSeed); for (IWorldGenerator generator : worldGenerators) { generator.generate(fmlRandom, chunkX, chunkZ, world, chunkGenerator, chunkProvider); } } /** * Internal method for creating an @Block instance * @param container * @param type * @param annotation * @throws Exception */ public static Object buildBlock(ModContainer container, Class<?> type, Block annotation) throws Exception { Object o = type.getConstructor(int.class).newInstance(findSpareBlockId()); registerBlock((net.minecraft.block.Block) o); return o; } /** * Private and not yet working properly * * @return a block id */ private static int findSpareBlockId() { return BlockTracker.nextBlockId(); } /** * Register an item with the item registry with a custom name : this allows for easier server->client resolution * * @param item The item to register * @param name The mod-unique name of the item */ public static void registerItem(net.minecraft.item.Item item, String name) { registerItem(item, name, null); } /** * Register the specified Item with a mod specific name : overrides the standard type based name * @param item The item to register * @param name The mod-unique name to register it as - null will remove a custom name * @param modId An optional modId that will "own" this block - generally used by multi-mod systems * where one mod should "own" all the blocks of all the mods, null defaults to the active mod */ public static void registerItem(net.minecraft.item.Item item, String name, String modId) { GameData.setName(item, name, modId); } /** * Register a block with the world * */ @Deprecated public static void registerBlock(net.minecraft.block.Block block) { registerBlock(block, ItemBlock.class); } /** * Register a block with the specified mod specific name : overrides the standard type based name * @param block The block to register * @param name The mod-unique name to register it as */ public static void registerBlock(net.minecraft.block.Block block, String name) { registerBlock(block, ItemBlock.class, name); } /** * Register a block with the world, with the specified item class * * Deprecated in favour of named versions * * @param block The block to register * @param itemclass The item type to register with it */ @Deprecated public static void registerBlock(net.minecraft.block.Block block, Class<? extends ItemBlock> itemclass) { registerBlock(block, itemclass, null); } /** * Register a block with the world, with the specified item class and block name * @param block The block to register * @param itemclass The item type to register with it * @param name The mod-unique name to register it with */ public static void registerBlock(net.minecraft.block.Block block, Class<? extends ItemBlock> itemclass, String name) { registerBlock(block, itemclass, name, null); } /** * Register a block with the world, with the specified item class, block name and owning modId * @param block The block to register * @param itemclass The iterm type to register with it * @param name The mod-unique name to register it with * @param modId The modId that will own the block name. null defaults to the active modId */ public static void registerBlock(net.minecraft.block.Block block, Class<? extends ItemBlock> itemclass, String name, String modId) { if (Loader.instance().isInState(LoaderState.CONSTRUCTING)) { FMLLog.warning("The mod %s is attempting to register a block whilst it it being constructed. This is bad modding practice - please use a proper mod lifecycle event.", Loader.instance().activeModContainer()); } try { assert block != null : "registerBlock: block cannot be null"; assert itemclass != null : "registerBlock: itemclass cannot be null"; int blockItemId = block.field_71990_ca - 256; Constructor<? extends ItemBlock> itemCtor; + Item i; try { itemCtor = itemclass.getConstructor(int.class); + i = itemCtor.newInstance(blockItemId); } catch (NoSuchMethodException e) { itemCtor = itemclass.getConstructor(int.class, Block.class); + i = itemCtor.newInstance(blockItemId, block); } - Item i = itemCtor.newInstance(blockItemId, block); GameRegistry.registerItem(i,name, modId); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Caught an exception during block registration"); throw new LoaderException(e); } blockRegistry.put(Loader.instance().activeModContainer(), (BlockProxy) block); } public static void addRecipe(ItemStack output, Object... params) { addShapedRecipe(output, params); } public static IRecipe addShapedRecipe(ItemStack output, Object... params) { return CraftingManager.func_77594_a().func_92103_a(output, params); } public static void addShapelessRecipe(ItemStack output, Object... params) { CraftingManager.func_77594_a().func_77596_b(output, params); } public static void addRecipe(IRecipe recipe) { CraftingManager.func_77594_a().func_77592_b().add(recipe); } public static void addSmelting(int input, ItemStack output, float xp) { FurnaceRecipes.func_77602_a().func_77600_a(input, output, xp); } public static void registerTileEntity(Class<? extends TileEntity> tileEntityClass, String id) { TileEntity.func_70306_a(tileEntityClass, id); } /** * Register a tile entity, with alternative TileEntity identifiers. Use with caution! * This method allows for you to "rename" the 'id' of the tile entity. * * @param tileEntityClass The tileEntity class to register * @param id The primary ID, this will be the ID that the tileentity saves as * @param alternatives A list of alternative IDs that will also map to this class. These will never save, but they will load */ public static void registerTileEntityWithAlternatives(Class<? extends TileEntity> tileEntityClass, String id, String... alternatives) { TileEntity.func_70306_a(tileEntityClass, id); Map<String,Class> teMappings = ObfuscationReflectionHelper.getPrivateValue(TileEntity.class, null, "field_70326_a", "a"); for (String s: alternatives) { if (!teMappings.containsKey(s)) { teMappings.put(s, tileEntityClass); } } } public static void addBiome(BiomeGenBase biome) { WorldType.field_77137_b.addNewBiome(biome); } public static void removeBiome(BiomeGenBase biome) { WorldType.field_77137_b.removeBiome(biome); } public static void registerFuelHandler(IFuelHandler handler) { fuelHandlers.add(handler); } public static int getFuelValue(ItemStack itemStack) { int fuelValue = 0; for (IFuelHandler handler : fuelHandlers) { fuelValue = Math.max(fuelValue, handler.getBurnTime(itemStack)); } return fuelValue; } public static void registerCraftingHandler(ICraftingHandler handler) { craftingHandlers.add(handler); } public static void onItemCrafted(EntityPlayer player, ItemStack item, IInventory craftMatrix) { for (ICraftingHandler handler : craftingHandlers) { handler.onCrafting(player, item, craftMatrix); } } public static void onItemSmelted(EntityPlayer player, ItemStack item) { for (ICraftingHandler handler : craftingHandlers) { handler.onSmelting(player, item); } } public static void registerPickupHandler(IPickupNotifier handler) { pickupHandlers.add(handler); } public static void onPickupNotification(EntityPlayer player, EntityItem item) { for (IPickupNotifier notify : pickupHandlers) { notify.notifyPickup(item, player); } } public static void registerPlayerTracker(IPlayerTracker tracker) { playerTrackers.add(tracker); } public static void onPlayerLogin(EntityPlayer player) { for(IPlayerTracker tracker : playerTrackers) tracker.onPlayerLogin(player); } public static void onPlayerLogout(EntityPlayer player) { for(IPlayerTracker tracker : playerTrackers) tracker.onPlayerLogout(player); } public static void onPlayerChangedDimension(EntityPlayer player) { for(IPlayerTracker tracker : playerTrackers) tracker.onPlayerChangedDimension(player); } public static void onPlayerRespawn(EntityPlayer player) { for(IPlayerTracker tracker : playerTrackers) tracker.onPlayerRespawn(player); } /** * Look up a mod block in the global "named item list" * @param modId The modid owning the block * @param name The name of the block itself * @return The block or null if not found */ public static net.minecraft.block.Block findBlock(String modId, String name) { return GameData.findBlock(modId, name); } /** * Look up a mod item in the global "named item list" * @param modId The modid owning the item * @param name The name of the item itself * @return The item or null if not found */ public static net.minecraft.item.Item findItem(String modId, String name) { return GameData.findItem(modId, name); } }
false
true
public static void registerBlock(net.minecraft.block.Block block, Class<? extends ItemBlock> itemclass, String name, String modId) { if (Loader.instance().isInState(LoaderState.CONSTRUCTING)) { FMLLog.warning("The mod %s is attempting to register a block whilst it it being constructed. This is bad modding practice - please use a proper mod lifecycle event.", Loader.instance().activeModContainer()); } try { assert block != null : "registerBlock: block cannot be null"; assert itemclass != null : "registerBlock: itemclass cannot be null"; int blockItemId = block.field_71990_ca - 256; Constructor<? extends ItemBlock> itemCtor; try { itemCtor = itemclass.getConstructor(int.class); } catch (NoSuchMethodException e) { itemCtor = itemclass.getConstructor(int.class, Block.class); } Item i = itemCtor.newInstance(blockItemId, block); GameRegistry.registerItem(i,name, modId); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Caught an exception during block registration"); throw new LoaderException(e); } blockRegistry.put(Loader.instance().activeModContainer(), (BlockProxy) block); }
public static void registerBlock(net.minecraft.block.Block block, Class<? extends ItemBlock> itemclass, String name, String modId) { if (Loader.instance().isInState(LoaderState.CONSTRUCTING)) { FMLLog.warning("The mod %s is attempting to register a block whilst it it being constructed. This is bad modding practice - please use a proper mod lifecycle event.", Loader.instance().activeModContainer()); } try { assert block != null : "registerBlock: block cannot be null"; assert itemclass != null : "registerBlock: itemclass cannot be null"; int blockItemId = block.field_71990_ca - 256; Constructor<? extends ItemBlock> itemCtor; Item i; try { itemCtor = itemclass.getConstructor(int.class); i = itemCtor.newInstance(blockItemId); } catch (NoSuchMethodException e) { itemCtor = itemclass.getConstructor(int.class, Block.class); i = itemCtor.newInstance(blockItemId, block); } GameRegistry.registerItem(i,name, modId); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Caught an exception during block registration"); throw new LoaderException(e); } blockRegistry.put(Loader.instance().activeModContainer(), (BlockProxy) block); }
diff --git a/src/portal-collector/src/com/trendmicro/tme/portal/ExchangeMetricCollector.java b/src/portal-collector/src/com/trendmicro/tme/portal/ExchangeMetricCollector.java index 8d4ed16..6226211 100644 --- a/src/portal-collector/src/com/trendmicro/tme/portal/ExchangeMetricCollector.java +++ b/src/portal-collector/src/com/trendmicro/tme/portal/ExchangeMetricCollector.java @@ -1,138 +1,143 @@ package com.trendmicro.tme.portal; import java.io.FileInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.Properties; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.googlecode.jmxtrans.JmxTransformer; import com.googlecode.jmxtrans.model.JmxProcess; import com.googlecode.jmxtrans.model.Query; import com.googlecode.jmxtrans.model.Server; import com.googlecode.jmxtrans.util.ValidationException; import com.trendmicro.codi.ZKSessionManager; import com.trendmicro.tme.mfr.BrokerFarm; import com.trendmicro.mist.proto.ZooKeeperInfo.Broker; public class ExchangeMetricCollector { private static final String CONFIG_PATH = System.getProperty("com.trendmicro.tme.portal.collector.conf", "/opt/trend/tme/conf/portal-collector/portal-collector.properties"); private static final Logger logger = LoggerFactory.getLogger(ExchangeMetricCollector.class); private BrokerFarm brokerFarm; private ExchangeMetricWriter writer; private Query createQuery() { Query query = new Query(); query.setObj("com.sun.messaging.jms.server:type=Destination,subtype=Monitor,desttype=*,name=*"); query.addAttr("NumMsgs"); query.addAttr("NumMsgsIn"); query.addAttr("NumMsgsOut"); query.addAttr("NumMsgsPendingAcks"); query.addAttr("NumConsumers"); query.addAttr("NumProducers"); query.addAttr("MsgBytesIn"); query.addAttr("MsgBytesOut"); query.addAttr("TotalMsgBytes"); query.addOutputWriter(writer); return query; } public ExchangeMetricCollector(BrokerFarm brokerFarm, ExchangeMetricWriter writer) { this.brokerFarm = brokerFarm; this.writer = writer; } private String getJMXUrl(String broker) { Socket sock = new Socket(); try { sock.connect(new InetSocketAddress(broker, 7676)); String url = null; for(String line : IOUtils.toString(sock.getInputStream()).split("\n")) { if(line.startsWith("jmxrmi rmi JMX")) { url = line.substring(line.indexOf('=') + 1, line.length() - 1); break; } } logger.info("jmxurl of broker {} = {}", broker, url); return url; } catch(Exception e) { logger.error(e.getMessage(), e); return null; } finally { try { IOUtils.closeQuietly(sock.getInputStream()); IOUtils.closeQuietly(sock.getOutputStream()); sock.close(); } catch(IOException e) { } } } public void run() { logger.info("Exchange Metric Collector started"); while(true) { JmxProcess jmxProcess = new JmxProcess(); for(Broker broker : brokerFarm.getAllBrokers().values()) { if(broker.getStatus() == Broker.Status.ONLINE) { Server server = new Server(); server.setHost(broker.getHost()); server.setUsername("admin"); server.setPassword("admin"); - server.setUrl(getJMXUrl(broker.getHost())); + String jmxurl = getJMXUrl(broker.getHost()); + if(jmxurl == null) { + logger.error("cannot obtain JMX URL from broker {}", broker.getHost()); + continue; + } + server.setUrl(jmxurl); try { server.addQuery(createQuery()); } catch(ValidationException e) { e.printStackTrace(); } jmxProcess.addServer(server); } } JmxTransformer transformer = new JmxTransformer(); try { transformer.executeStandalone(jmxProcess); Thread.sleep(10000); } catch(Exception e) { logger.error("Error to collect metrics: ", e); } } } public static void main(String[] args) { try { Properties prop = new Properties(); prop.load(new FileInputStream(CONFIG_PATH)); // Let the system properties override the ones in the config file prop.putAll(System.getProperties()); String zkQuorum = prop.getProperty("com.trendmicro.tme.portal.collector.zookeeper.quorum"); int zkTimeout = Integer.valueOf(prop.getProperty("com.trendmicro.tme.portal.collector.zookeeper.timeout")); ZKSessionManager.initialize(zkQuorum + prop.getProperty("com.trendmicro.tme.portal.collector.zookeeper.tmeroot"), zkTimeout); if(!ZKSessionManager.instance().waitConnected(zkTimeout)) { throw new Exception("Cannot connect to ZooKeeper Quorom " + zkQuorum); } ExchangeMetricWriter writer = new ExchangeMetricWriter(); writer.addSetting("templateFile", prop.getProperty("com.trendmicro.tme.portal.collector.template")); writer.addSetting("outputPath", prop.getProperty("com.trendmicro.tme.portal.collector.outputdir")); ExchangeMetricCollector collector = new ExchangeMetricCollector(new BrokerFarm(), writer); collector.run(); } catch(Exception e) { e.printStackTrace(); logger.error("Portal Collector startup error: ", e); System.exit(-1); } } }
true
true
public void run() { logger.info("Exchange Metric Collector started"); while(true) { JmxProcess jmxProcess = new JmxProcess(); for(Broker broker : brokerFarm.getAllBrokers().values()) { if(broker.getStatus() == Broker.Status.ONLINE) { Server server = new Server(); server.setHost(broker.getHost()); server.setUsername("admin"); server.setPassword("admin"); server.setUrl(getJMXUrl(broker.getHost())); try { server.addQuery(createQuery()); } catch(ValidationException e) { e.printStackTrace(); } jmxProcess.addServer(server); } } JmxTransformer transformer = new JmxTransformer(); try { transformer.executeStandalone(jmxProcess); Thread.sleep(10000); } catch(Exception e) { logger.error("Error to collect metrics: ", e); } } }
public void run() { logger.info("Exchange Metric Collector started"); while(true) { JmxProcess jmxProcess = new JmxProcess(); for(Broker broker : brokerFarm.getAllBrokers().values()) { if(broker.getStatus() == Broker.Status.ONLINE) { Server server = new Server(); server.setHost(broker.getHost()); server.setUsername("admin"); server.setPassword("admin"); String jmxurl = getJMXUrl(broker.getHost()); if(jmxurl == null) { logger.error("cannot obtain JMX URL from broker {}", broker.getHost()); continue; } server.setUrl(jmxurl); try { server.addQuery(createQuery()); } catch(ValidationException e) { e.printStackTrace(); } jmxProcess.addServer(server); } } JmxTransformer transformer = new JmxTransformer(); try { transformer.executeStandalone(jmxProcess); Thread.sleep(10000); } catch(Exception e) { logger.error("Error to collect metrics: ", e); } } }
diff --git a/cachius/src/org/riotfamily/cachius/http/header/DynamicHeaderValue.java b/cachius/src/org/riotfamily/cachius/http/header/DynamicHeaderValue.java index eea1c94b6..f54b7014b 100644 --- a/cachius/src/org/riotfamily/cachius/http/header/DynamicHeaderValue.java +++ b/cachius/src/org/riotfamily/cachius/http/header/DynamicHeaderValue.java @@ -1,43 +1,43 @@ /* 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.riotfamily.cachius.http.header; import javax.servlet.http.HttpServletRequest; public abstract class DynamicHeaderValue implements HeaderValue { private String value; int insertAt; int skip; public DynamicHeaderValue(String value, int insertAt, int skip) { this.value = value; this.insertAt = insertAt; this.skip = skip; } public String resolve(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); sb.append(value, 0, insertAt); appendDynamicValue(sb, request); if (insertAt + skip < value.length()) { sb.append(value, insertAt + skip, value.length()); } - return value; + return sb.toString(); } protected abstract void appendDynamicValue(StringBuilder sb, HttpServletRequest request); }
true
true
public String resolve(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); sb.append(value, 0, insertAt); appendDynamicValue(sb, request); if (insertAt + skip < value.length()) { sb.append(value, insertAt + skip, value.length()); } return value; }
public String resolve(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); sb.append(value, 0, insertAt); appendDynamicValue(sb, request); if (insertAt + skip < value.length()) { sb.append(value, insertAt + skip, value.length()); } return sb.toString(); }
diff --git a/src/main/java/com/google/dexmaker/AppDataDirGuesser.java b/src/main/java/com/google/dexmaker/AppDataDirGuesser.java index e9f343c..b59670e 100644 --- a/src/main/java/com/google/dexmaker/AppDataDirGuesser.java +++ b/src/main/java/com/google/dexmaker/AppDataDirGuesser.java @@ -1,109 +1,115 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.dexmaker; import java.io.File; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; /** * Uses heuristics to guess the application's private data directory. */ class AppDataDirGuesser { public File guess() { try { ClassLoader classLoader = guessSuitableClassLoader(); // Check that we have an instance of the PathClassLoader. Class<?> clazz = Class.forName("dalvik.system.PathClassLoader"); clazz.cast(classLoader); // Use the toString() method to calculate the data directory. String pathFromThisClassLoader = getPathFromThisClassLoader(classLoader, clazz); File[] results = guessPath(pathFromThisClassLoader); if (results.length > 0) { return results[0]; } } catch (ClassCastException ignored) { } catch (ClassNotFoundException ignored) { } return null; } private ClassLoader guessSuitableClassLoader() { return AppDataDirGuesser.class.getClassLoader(); } private String getPathFromThisClassLoader(ClassLoader classLoader, Class<?> pathClassLoaderClass) { // Prior to ICS, we can simply read the "path" field of the // PathClassLoader. try { Field pathField = pathClassLoaderClass.getDeclaredField("path"); pathField.setAccessible(true); return (String) pathField.get(classLoader); } catch (NoSuchFieldException ignored) { } catch (IllegalAccessException ignored) { } catch (ClassCastException ignored) { } // Parsing toString() method: yuck. But no other way to get the path. // Strip out the bit between angle brackets, that's our path. String result = classLoader.toString(); int index = result.lastIndexOf('['); result = (index == -1) ? result : result.substring(index + 1); index = result.indexOf(']'); return (index == -1) ? result : result.substring(0, index); } File[] guessPath(String input) { List<File> results = new ArrayList<File>(); + // Post JB, the system property is set to the applications private data cache + // directory. + File tmpDir = new File(System.getProperty("java.io.tmpdir")); + if (isWriteableDirectory(tmpDir)) { + results.add(tmpDir); + } for (String potential : input.split(":")) { if (!potential.startsWith("/data/app/")) { continue; } int start = "/data/app/".length(); int end = potential.lastIndexOf(".apk"); if (end != potential.length() - 4) { continue; } int dash = potential.indexOf("-"); if (dash != -1) { end = dash; } String packageName = potential.substring(start, end); File dataDir = new File("/data/data/" + packageName); if (isWriteableDirectory(dataDir)) { File cacheDir = new File(dataDir, "cache"); // The cache directory might not exist -- create if necessary if (fileOrDirExists(cacheDir) || cacheDir.mkdir()) { if (isWriteableDirectory(cacheDir)) { results.add(cacheDir); } } } } return results.toArray(new File[results.size()]); } boolean fileOrDirExists(File file) { return file.exists(); } boolean isWriteableDirectory(File file) { return file.isDirectory() && file.canWrite(); } }
true
true
File[] guessPath(String input) { List<File> results = new ArrayList<File>(); for (String potential : input.split(":")) { if (!potential.startsWith("/data/app/")) { continue; } int start = "/data/app/".length(); int end = potential.lastIndexOf(".apk"); if (end != potential.length() - 4) { continue; } int dash = potential.indexOf("-"); if (dash != -1) { end = dash; } String packageName = potential.substring(start, end); File dataDir = new File("/data/data/" + packageName); if (isWriteableDirectory(dataDir)) { File cacheDir = new File(dataDir, "cache"); // The cache directory might not exist -- create if necessary if (fileOrDirExists(cacheDir) || cacheDir.mkdir()) { if (isWriteableDirectory(cacheDir)) { results.add(cacheDir); } } } } return results.toArray(new File[results.size()]); }
File[] guessPath(String input) { List<File> results = new ArrayList<File>(); // Post JB, the system property is set to the applications private data cache // directory. File tmpDir = new File(System.getProperty("java.io.tmpdir")); if (isWriteableDirectory(tmpDir)) { results.add(tmpDir); } for (String potential : input.split(":")) { if (!potential.startsWith("/data/app/")) { continue; } int start = "/data/app/".length(); int end = potential.lastIndexOf(".apk"); if (end != potential.length() - 4) { continue; } int dash = potential.indexOf("-"); if (dash != -1) { end = dash; } String packageName = potential.substring(start, end); File dataDir = new File("/data/data/" + packageName); if (isWriteableDirectory(dataDir)) { File cacheDir = new File(dataDir, "cache"); // The cache directory might not exist -- create if necessary if (fileOrDirExists(cacheDir) || cacheDir.mkdir()) { if (isWriteableDirectory(cacheDir)) { results.add(cacheDir); } } } } return results.toArray(new File[results.size()]); }
diff --git a/src/de/ueller/midlet/gps/GuiKeyShortcuts.java b/src/de/ueller/midlet/gps/GuiKeyShortcuts.java index 0eb08d0c..f478ddd8 100644 --- a/src/de/ueller/midlet/gps/GuiKeyShortcuts.java +++ b/src/de/ueller/midlet/gps/GuiKeyShortcuts.java @@ -1,108 +1,108 @@ /* * GpsMid - Copyright (c) 2008 Kai Krueger apm at users dot sourceforge dot net * See Copying */ package de.ueller.midlet.gps; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.List; import de.enough.polish.util.Locale; import de.ueller.gps.tools.intTree; public class GuiKeyShortcuts extends List implements CommandListener, GpsMidDisplayable { private static final Command CMD_BACK = new Command(Locale.get("guikeyshortcuts.Back")/*Back*/, Command.BACK, 3); private GuiDiscover parent; public GuiKeyShortcuts(GuiDiscover parent) { super(Locale.get("guikeyshortcuts.KeyShortcutsInMap")/*Key shortcuts in Map*/, List.IMPLICIT); addCommand(CMD_BACK); // Set up this Displayable to listen to command events setCommandListener(this); this.parent = parent; intTree keyMap = Trace.getInstance().singleKeyPressCommand; this.append(Locale.get("guikeyshortcuts.SingleKeyPresses")/*Single key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } keyMap = Trace.getInstance().repeatableKeyPressCommand; this.append(" ", null); this.append(Locale.get("guikeyshortcuts.RepeatableKeyPresses")/*Repeatable key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } keyMap = Trace.getInstance().longKeyPressCommand; this.append(" ", null); this.append(Locale.get("guikeyshortcuts.LongKeyPresses")/*Long key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } keyMap = Trace.getInstance().doubleKeyPressCommand; this.append(" ", null); this.append(Locale.get("guikeyshortcuts.DoubleKeyPresses")/*Double key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } keyMap = Trace.getInstance().gameKeyCommand; this.append(" ", null); - this.append(Locale.get("guikeyshortcuts.GameActionKeyPresses:")/*Game Action key presses:*/, null); + this.append(Locale.get("guikeyshortcuts.GameActionKeyPresses")/*Game Action key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } } public void commandAction(Command c, Displayable d) { if (c == CMD_BACK) { parent.show(); } } public void show() { GpsMid.getInstance().show(this); } }
true
true
public GuiKeyShortcuts(GuiDiscover parent) { super(Locale.get("guikeyshortcuts.KeyShortcutsInMap")/*Key shortcuts in Map*/, List.IMPLICIT); addCommand(CMD_BACK); // Set up this Displayable to listen to command events setCommandListener(this); this.parent = parent; intTree keyMap = Trace.getInstance().singleKeyPressCommand; this.append(Locale.get("guikeyshortcuts.SingleKeyPresses")/*Single key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } keyMap = Trace.getInstance().repeatableKeyPressCommand; this.append(" ", null); this.append(Locale.get("guikeyshortcuts.RepeatableKeyPresses")/*Repeatable key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } keyMap = Trace.getInstance().longKeyPressCommand; this.append(" ", null); this.append(Locale.get("guikeyshortcuts.LongKeyPresses")/*Long key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } keyMap = Trace.getInstance().doubleKeyPressCommand; this.append(" ", null); this.append(Locale.get("guikeyshortcuts.DoubleKeyPresses")/*Double key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } keyMap = Trace.getInstance().gameKeyCommand; this.append(" ", null); this.append(Locale.get("guikeyshortcuts.GameActionKeyPresses:")/*Game Action key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } }
public GuiKeyShortcuts(GuiDiscover parent) { super(Locale.get("guikeyshortcuts.KeyShortcutsInMap")/*Key shortcuts in Map*/, List.IMPLICIT); addCommand(CMD_BACK); // Set up this Displayable to listen to command events setCommandListener(this); this.parent = parent; intTree keyMap = Trace.getInstance().singleKeyPressCommand; this.append(Locale.get("guikeyshortcuts.SingleKeyPresses")/*Single key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } keyMap = Trace.getInstance().repeatableKeyPressCommand; this.append(" ", null); this.append(Locale.get("guikeyshortcuts.RepeatableKeyPresses")/*Repeatable key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } keyMap = Trace.getInstance().longKeyPressCommand; this.append(" ", null); this.append(Locale.get("guikeyshortcuts.LongKeyPresses")/*Long key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } keyMap = Trace.getInstance().doubleKeyPressCommand; this.append(" ", null); this.append(Locale.get("guikeyshortcuts.DoubleKeyPresses")/*Double key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } keyMap = Trace.getInstance().gameKeyCommand; this.append(" ", null); this.append(Locale.get("guikeyshortcuts.GameActionKeyPresses")/*Game Action key presses:*/, null); for (int i = 0; i < keyMap.size(); i++) { int key = keyMap.getKeyIdx(i); if (key > 31) { this.append((char) keyMap.getKeyIdx(i) + ": " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } else { this.append("'" + keyMap.getKeyIdx(i) + "': " + ((Command) keyMap.getValueIdx(i)).getLabel(), null); } } }
diff --git a/src/henplus/commands/AutocommitCommand.java b/src/henplus/commands/AutocommitCommand.java index d85fcd2..1493f67 100644 --- a/src/henplus/commands/AutocommitCommand.java +++ b/src/henplus/commands/AutocommitCommand.java @@ -1,68 +1,74 @@ /* * This is free software, licensed under the Gnu Public License (GPL) * get a copy from <http://www.gnu.org/licenses/gpl.html> * * author: Henner Zeller <[email protected]> */ package henplus.commands; import henplus.HenPlus; import henplus.SQLSession; import henplus.AbstractCommand; import java.util.StringTokenizer; import java.sql.SQLException; import java.io.File; import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; /** * document me. */ public class AutocommitCommand extends AbstractCommand { /** * returns the command-strings this command can handle. */ public String[] getCommandList() { return new String[] { "autocommit-on", "autocommit-off" }; } /** * execute the command given. */ public int execute(SQLSession session, String cmd, String param) { try { if ("autocommit-on".equals(cmd)) { + /* + * due to a bug in Sybase, we have to close the + * transaction first before setting autcommit. + * This is probably a save choice to do. + */ + session.getConnection().commit(); session.getConnection().setAutoCommit(true); System.err.println("set autocommit on"); } else if ("autocommit-off".equals(cmd)) { session.getConnection().setAutoCommit(false); System.err.println("set autocommit off"); } } catch (SQLException e) { System.err.println(e.getMessage()); } return SUCCESS; } /** * return a descriptive string. */ public String getShortDescription() { return "switches autocommit on/off"; } } /* * Local variables: * c-basic-offset: 4 * compile-command: "ant -emacs -find build.xml" * End: */
true
true
public int execute(SQLSession session, String cmd, String param) { try { if ("autocommit-on".equals(cmd)) { session.getConnection().setAutoCommit(true); System.err.println("set autocommit on"); } else if ("autocommit-off".equals(cmd)) { session.getConnection().setAutoCommit(false); System.err.println("set autocommit off"); } } catch (SQLException e) { System.err.println(e.getMessage()); } return SUCCESS; }
public int execute(SQLSession session, String cmd, String param) { try { if ("autocommit-on".equals(cmd)) { /* * due to a bug in Sybase, we have to close the * transaction first before setting autcommit. * This is probably a save choice to do. */ session.getConnection().commit(); session.getConnection().setAutoCommit(true); System.err.println("set autocommit on"); } else if ("autocommit-off".equals(cmd)) { session.getConnection().setAutoCommit(false); System.err.println("set autocommit off"); } } catch (SQLException e) { System.err.println(e.getMessage()); } return SUCCESS; }
diff --git a/com.ibm.wala.cast.js.rhino/source/org/mozilla/javascript/RhinoToAstTranslator.java b/com.ibm.wala.cast.js.rhino/source/org/mozilla/javascript/RhinoToAstTranslator.java old mode 100644 new mode 100755 index 543e5f8c3..16feff72b --- a/com.ibm.wala.cast.js.rhino/source/org/mozilla/javascript/RhinoToAstTranslator.java +++ b/com.ibm.wala.cast.js.rhino/source/org/mozilla/javascript/RhinoToAstTranslator.java @@ -1,1611 +1,1611 @@ /****************************************************************************** * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *****************************************************************************/ package org.mozilla.javascript; import java.io.Reader; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import org.mozilla.javascript.tools.ToolErrorReporter; import com.ibm.wala.cast.js.html.MappedSourceModule; import com.ibm.wala.cast.js.ipa.callgraph.JSSSAPropagationCallGraphBuilder; import com.ibm.wala.cast.js.loader.JavaScriptLoader; import com.ibm.wala.cast.js.types.JavaScriptTypes; import com.ibm.wala.cast.tree.CAst; import com.ibm.wala.cast.tree.CAstControlFlowMap; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstNodeTypeMap; import com.ibm.wala.cast.tree.CAstQualifier; import com.ibm.wala.cast.tree.CAstSourcePositionMap; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.cast.tree.CAstType; import com.ibm.wala.cast.tree.impl.CAstControlFlowRecorder; import com.ibm.wala.cast.tree.impl.CAstOperator; import com.ibm.wala.cast.tree.impl.CAstSourcePositionRecorder; import com.ibm.wala.cast.tree.impl.CAstSymbolImpl; import com.ibm.wala.cast.tree.impl.LineNumberPosition; import com.ibm.wala.classLoader.SourceModule; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.debug.Assertions; public class RhinoToAstTranslator { /** * a dummy name to use for standard function calls, only used to distinguish * them from constructor calls */ public static final String STANDARD_CALL_FN_NAME = "do"; /** * name used for constructor calls, used to distinguish them from standard * function calls */ public static final String CTOR_CALL_FN_NAME = "ctor"; private final boolean DEBUG = true; /** * shared interface for all objects storing contextual information during the * Rhino AST traversal * */ private interface WalkContext { /** * get the name of the enclosing script */ String script(); /** * get the enclosing Rhino {@link ScriptOrFnNode} */ ScriptOrFnNode top(); /** * Add a scoped entity to this context. The only scoped entities for * JavaScript are functions. (Why not variables? --MS) For a function * expression, construct will be the corresponding * {@link CAstNode#FUNCTION_EXPR}. For a function statement, construct is * <code>null</code>. */ void addScopedEntity(CAstNode construct, CAstEntity e); /** * get a mapping from CAstNodes to the scoped entities (functions for * JavaScript) introduced by those nodes. Also maps <code>null</code> to * those entities not corresponding to any node */ Map<CAstNode, Collection<CAstEntity>> getScopedEntities(); /** * is the current node within an expression? */ boolean expressionContext(); /** * for recording control-flow relationships among the CAst nodes */ CAstControlFlowRecorder cfg(); /** * for recording source positions */ CAstSourcePositionRecorder pos(); /** * get the current control-flow target if an exception is thrown, or * <code>null</code> if unknown */ CAstNode getCatchTarget(); /** * @see BaseCollectingContext */ String getBaseVarNameIfRelevant(Node node); /** * @see BaseCollectingContext */ boolean foundBase(Node node); /** * @see BaseCollectingContext */ void updateBase(Node from, Node to); /** * @see CatchBlockContext */ String getCatchVar(); /** * @see CatchBlockContext */ void setCatchVar(String name); /** * @see LoopContext */ String createForInVar(Node initExpr); /** * @see LoopContext */ String getForInInitVar(); /** * Add a name declaration to this context. For variables or constants, n * should be a {@link CAstNode#DECL_STMT}, and the initialization of the * variable (if any) may occur in a separate assignment. For functions, n * should be a {@link CAstNode#FUNCTION_STMT}, including the function body. */ void addNameDecl(CAstNode n); } /** * default implementation of WalkContext; methods do nothing / return null * */ private static class RootContext implements WalkContext { public String script() { return null; } public ScriptOrFnNode top() { return null; } public void addScopedEntity(CAstNode construct, CAstEntity e) { } public Map<CAstNode, Collection<CAstEntity>> getScopedEntities() { return null; } public boolean expressionContext() { return false; } public CAstControlFlowRecorder cfg() { return null; } public CAstSourcePositionRecorder pos() { return null; } public CAstNode getCatchTarget() { return null; } public String getBaseVarNameIfRelevant(Node node) { return null; } public boolean foundBase(Node node) { return false; } public void updateBase(Node from, Node to) { } public String getCatchVar() { return null; } public void setCatchVar(String name) { } public String createForInVar(Node initExpr) { return null; } public String getForInInitVar() { return null; } public void addNameDecl(CAstNode n) { } } /** * WalkContext that delegates all behavior to a parent */ private static abstract class DelegatingContext implements WalkContext { private final WalkContext parent; DelegatingContext(WalkContext parent) { this.parent = parent; } public String script() { return parent.script(); } public ScriptOrFnNode top() { return parent.top(); } public void addScopedEntity(CAstNode construct, CAstEntity e) { parent.addScopedEntity(construct, e); } public Map<CAstNode, Collection<CAstEntity>> getScopedEntities() { return parent.getScopedEntities(); } public boolean expressionContext() { return parent.expressionContext(); } public CAstControlFlowRecorder cfg() { return parent.cfg(); } public CAstSourcePositionRecorder pos() { return parent.pos(); } public CAstNode getCatchTarget() { return parent.getCatchTarget(); } public String getBaseVarNameIfRelevant(Node node) { return parent.getBaseVarNameIfRelevant(node); } public boolean foundBase(Node node) { return parent.foundBase(node); } public void updateBase(Node from, Node to) { parent.updateBase(from, to); } public String getCatchVar() { return parent.getCatchVar(); } public void setCatchVar(String name) { parent.setCatchVar(name); } public String createForInVar(Node initExpr) { return parent.createForInVar(initExpr); } public String getForInInitVar() { return parent.getForInInitVar(); } public void addNameDecl(CAstNode n) { parent.addNameDecl(n); } } /** * context used for function / script declarations */ private static class FunctionContext extends DelegatingContext { private final ScriptOrFnNode topNode; private final Map<CAstNode, Collection<CAstEntity>> scopedEntities = HashMapFactory.make(); private final List<CAstNode> nameDecls = new ArrayList<CAstNode>(); private final CAstSourcePositionRecorder pos = new CAstSourcePositionRecorder(); private final CAstControlFlowRecorder cfg = new CAstControlFlowRecorder(pos); FunctionContext(WalkContext parent, ScriptOrFnNode s) { super(parent); this.topNode = s; } public ScriptOrFnNode top() { return topNode; } public void addScopedEntity(CAstNode construct, CAstEntity e) { if (!scopedEntities.containsKey(construct)) { HashSet<CAstEntity> s = HashSetFactory.make(); scopedEntities.put(construct, s); } scopedEntities.get(construct).add(e); } public Map<CAstNode, Collection<CAstEntity>> getScopedEntities() { return scopedEntities; } public boolean expressionContext() { return false; } public CAstControlFlowRecorder cfg() { return cfg; } public CAstSourcePositionRecorder pos() { return pos; } // TODO do we really need to override this method? --MS public String createForInVar(Node initExpr) { return null; } // TODO do we really need to override this method? --MS public String getForInInitVar() { return null; } public void addNameDecl(CAstNode n) { assert n.getKind() == CAstNode.FUNCTION_STMT || n.getKind() == CAstNode.DECL_STMT; nameDecls.add(n); } public CAstNode getCatchTarget() { return CAstControlFlowMap.EXCEPTION_TO_EXIT; } } /** * context used for top-level script declarations */ private static class ScriptContext extends FunctionContext { private final String script; ScriptContext(WalkContext parent, ScriptOrFnNode s, String script) { super(parent, s); this.script = script; } public String script() { return script; } } private static class ExpressionContext extends DelegatingContext { ExpressionContext(WalkContext parent) { super(parent); } public boolean expressionContext() { return true; } } private static class CatchBlockContext extends DelegatingContext { private String catchVarName; CatchBlockContext(WalkContext parent) { super(parent); } public String getCatchVar() { return catchVarName; } public void setCatchVar(String name) { catchVarName = name; } } private static class TryBlockContext extends DelegatingContext { private final CAstNode catchNode; TryBlockContext(WalkContext parent, CAstNode catchNode) { super(parent); this.catchNode = catchNode; } public CAstNode getCatchTarget() { return catchNode; } } /** * Used to determine the value to be passed as the 'this' argument for a * function call. This is needed since in JavaScript, you can write a call * e(...) where e is some arbitrary expression, and in the case where e is a * property access like e'.f, we must discover that the value of expression e' * is passed as the 'this' parameter. * * The general strategy is to store the value of the expression passed as the * 'this' parameter in baseVar, and then to use baseVar as the actual argument * sub-node for the CAst call node */ private static class BaseCollectingContext extends DelegatingContext { /** * node for which we actually care about what the base pointer is. this * helps to handle cases like x.y.f(), where we would like to store x.y in * baseVar, but not x when we recurse. */ private Node baseFor; /** * the name of the variable to be used to store the value of the expression * passed as the 'this' parameter */ private final String baseVarName; /** * have we discovered a value to be passed as the 'this' parameter? */ private boolean foundBase = false; BaseCollectingContext(WalkContext parent, Node initialBaseFor, String baseVarName) { super(parent); baseFor = initialBaseFor; this.baseVarName = baseVarName; } /** * if node is one that we care about, return baseVar, and as a side effect * set foundBase to true. Otherwise, return <code>null</code>. */ public String getBaseVarNameIfRelevant(Node node) { if (baseFor.equals(node)) { foundBase = true; return baseVarName; } else { return null; } } public boolean foundBase(Node node) { return foundBase; } /** * if we currently care about the base pointer of from, switch to searching * for the base pointer of to. Used for cases like comma expressions: if we * have (x,y.f)(), we want to assign y to baseVar */ public void updateBase(Node from, Node to) { if (baseFor.equals(from)) baseFor = to; } } /** * Used to model for-in loops. Given a loop "for (x in e) {...}", we generate * a new variable forInVar that should hold the value of e. Then, the * navigation of e is modeled via {@link CAstNode#EACH_ELEMENT_GET} and * {@link CAstNode#EACH_ELEMENT_HAS_NEXT} nodes. */ private static class LoopContext extends DelegatingContext { /** * for generating fresh loop vars */ private static int counter = 0; /** * the variable holding the value being navigated by the loop */ private String forInVar = null; /** * the expression evaluating to the value being navigated */ private Node forInInitExpr = null; private LoopContext(WalkContext parent) { super(parent); } /** * create a fresh for-in loop variable that should be initialized to * initExpr, and return it */ public String createForInVar(Node initExpr) { assert this.forInVar == null; this.forInVar = "_forin_tmp" + counter++; this.forInInitExpr = initExpr; return forInVar; } public String getForInInitVar() { assert forInVar != null; return forInVar; } } private CAstNode translateOpcode(int nodeType) { switch (nodeType) { case Token.ADD: return CAstOperator.OP_ADD; case Token.DIV: return CAstOperator.OP_DIV; case Token.LSH: return CAstOperator.OP_LSH; case Token.MOD: return CAstOperator.OP_MOD; case Token.MUL: return CAstOperator.OP_MUL; case Token.RSH: return CAstOperator.OP_RSH; case Token.SUB: return CAstOperator.OP_SUB; case Token.URSH: return CAstOperator.OP_URSH; case Token.BITAND: return CAstOperator.OP_BIT_AND; case Token.BITOR: return CAstOperator.OP_BIT_OR; case Token.BITXOR: return CAstOperator.OP_BIT_XOR; case Token.EQ: return CAstOperator.OP_EQ; case Token.SHEQ: return CAstOperator.OP_STRICT_EQ; case Token.IFEQ: return CAstOperator.OP_EQ; case Token.GE: return CAstOperator.OP_GE; case Token.GT: return CAstOperator.OP_GT; case Token.LE: return CAstOperator.OP_LE; case Token.LT: return CAstOperator.OP_LT; case Token.NE: return CAstOperator.OP_NE; case Token.SHNE: return CAstOperator.OP_STRICT_NE; case Token.IFNE: return CAstOperator.OP_NE; case Token.BITNOT: return CAstOperator.OP_BITNOT; case Token.NOT: return CAstOperator.OP_NOT; default: Assertions.UNREACHABLE(); return null; } } private CAstNode makeBuiltinNew(String typeName) { return Ast.makeNode(CAstNode.NEW, Ast.makeConstant(typeName)); } private CAstNode handleNew(WalkContext context, String globalName, Node arguments) { return handleNew(context, readName(context, globalName), arguments); } private CAstNode handleNew(WalkContext context, CAstNode value, Node arguments) { return makeCtorCall(value, arguments, context); } private boolean isPrologueScript(WalkContext context) { return JavaScriptLoader.bootstrapFileNames.contains(context.script()); } /** * is n a call to "primitive" within our synthetic modeling code? */ private boolean isPrimitiveCall(WalkContext context, Node n) { return isPrologueScript(context) && n.getType() == Token.CALL && n.getFirstChild().getType() == Token.NAME && n.getFirstChild().getString().equals("primitive"); } private boolean isPrimitiveCreation(WalkContext context, Node n) { return isPrologueScript(context) && n.getType() == Token.NEW && n.getFirstChild().getType() == Token.NAME && n.getFirstChild().getString().equals("Primitives"); } private CAstNode makeCall(CAstNode fun, CAstNode thisptr, Node firstChild, WalkContext context) { return makeCall(fun, thisptr, firstChild, context, STANDARD_CALL_FN_NAME); } private CAstNode makeCtorCall(CAstNode thisptr, Node firstChild, WalkContext context) { return makeCall(thisptr, null, firstChild, context, CTOR_CALL_FN_NAME); } private CAstNode makeCall(CAstNode fun, CAstNode thisptr, Node firstChild, WalkContext context, String callee) { int children = countSiblingsStartingFrom(firstChild); // children of CAst CALL node are the expression that evaluates to the // function, followed by a name (either STANDARD_CALL_FN_NAME or // CTOR_CALL_FN_NAME), followed by the actual // parameters int nargs = (thisptr == null) ? children + 2 : children + 3; int i = 0; CAstNode arguments[] = new CAstNode[nargs]; arguments[i++] = fun; assert callee.equals(STANDARD_CALL_FN_NAME) || callee.equals(CTOR_CALL_FN_NAME); arguments[i++] = Ast.makeConstant(callee); if (thisptr != null) arguments[i++] = thisptr; for (Node arg = firstChild; arg != null; arg = arg.getNext()) arguments[i++] = walkNodes(arg, context); CAstNode call = Ast.makeNode(CAstNode.CALL, arguments); context.cfg().map(call, call); if (context.getCatchTarget() != null) { context.cfg().add(call, context.getCatchTarget(), null); } return call; } /** * count the number of successor siblings of n, including n */ private int countSiblingsStartingFrom(Node n) { int siblings = 0; for (Node c = n; c != null; c = c.getNext(), siblings++) ; return siblings; } /** * Used to represent a script or function in the CAst; see walkEntity(). * */ private class ScriptOrFnEntity implements CAstEntity { private final String[] arguments; private final String name; private final int kind; private final Map<CAstNode, Collection<CAstEntity>> subs; private final CAstNode ast; private final CAstControlFlowMap map; private final CAstSourcePositionMap pos; ScriptOrFnEntity(ScriptOrFnNode n, Map<CAstNode, Collection<CAstEntity>> subs, CAstNode ast, CAstControlFlowMap map, CAstSourcePositionMap pos) { if (n instanceof FunctionNode) { String x = ((FunctionNode) n).getFunctionName(); if (x == null || "".equals(x)) { name = scriptName + "_anonymous_" + anonymousCounter++; } else { name = x; } } else { name = n.getSourceName(); } if (n instanceof FunctionNode) { FunctionNode f = (FunctionNode) n; f.flattenSymbolTable(false); int i = 0; arguments = new String[f.getParamCount() + 2]; arguments[i++] = name; arguments[i++] = "this"; for (int j = 0; j < f.getParamCount(); j++) { arguments[i++] = f.getParamOrVarName(j); } } else { arguments = new String[0]; } kind = (n instanceof FunctionNode) ? CAstEntity.FUNCTION_ENTITY : CAstEntity.SCRIPT_ENTITY; this.subs = subs; this.ast = ast; this.map = map; this.pos = pos; } public String toString() { return "<JS function " + getName() + ">"; } public String getName() { return name; } public String getSignature() { Assertions.UNREACHABLE(); return null; } public int getKind() { return kind; } public String[] getArgumentNames() { return arguments; } public CAstNode[] getArgumentDefaults() { return new CAstNode[0]; } public int getArgumentCount() { return arguments.length; } public Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities() { return Collections.unmodifiableMap(subs); } public Iterator<CAstEntity> getScopedEntities(CAstNode construct) { if (subs.containsKey(construct)) return subs.get(construct).iterator(); else return EmptyIterator.instance(); } public CAstNode getAST() { return ast; } public CAstControlFlowMap getControlFlow() { return map; } public CAstSourcePositionMap getSourceMap() { return pos; } public CAstSourcePositionMap.Position getPosition() { return null; } public CAstNodeTypeMap getNodeTypeMap() { return null; } public Collection<CAstQualifier> getQualifiers() { Assertions.UNREACHABLE("JuliansUnnamedCAstEntity$2.getQualifiers()"); return null; } public CAstType getType() { Assertions.UNREACHABLE("JuliansUnnamedCAstEntity$2.getType()"); return null; } } private CAstEntity walkEntity(final ScriptOrFnNode n, WalkContext context) { final FunctionContext child = (n instanceof FunctionNode) ? new FunctionContext(context, n) : new ScriptContext(context, n, n.getSourceName()); CAstNode[] stmts = gatherChildren(n, child); // add variable / constant / function declarations, if any if (!child.nameDecls.isEmpty()) { // new first statement will be a block declaring all names. CAstNode[] newStmts = new CAstNode[stmts.length + 1]; newStmts[0] = Ast.makeNode(CAstNode.BLOCK_STMT, child.nameDecls.toArray(new CAstNode[child.nameDecls.size()])); System.arraycopy(stmts, 0, newStmts, 1, stmts.length); stmts = newStmts; } final CAstNode ast = Ast.makeNode(CAstNode.BLOCK_STMT, stmts); final CAstControlFlowMap map = child.cfg(); final CAstSourcePositionMap pos = child.pos(); // not sure if we need this copy --MS final Map<CAstNode, Collection<CAstEntity>> subs = HashMapFactory.make(child.getScopedEntities()); return new ScriptOrFnEntity(n, subs, ast, map, pos); } private CAstNode[] gatherSiblings(Node n, WalkContext context) { int cnt = countSiblingsStartingFrom(n); CAstNode[] result = new CAstNode[cnt]; for (int i = 0; i < result.length; i++, n = n.getNext()) { result[i] = walkNodes(n, context); } return result; } private CAstNode[] gatherChildren(Node n, WalkContext context, int skip) { Node c = n.getFirstChild(); while (skip-- > 0) c = c.getNext(); return gatherSiblings(c, context); } private CAstNode[] gatherChildren(Node n, WalkContext context) { return gatherSiblings(n.getFirstChild(), context); } private CAstNode walkNodes(final Node n, WalkContext context) { return noteSourcePosition(context, walkNodesInternal(n, context), n); } private Position makePosition(Node n) { URL url = sourceModule.getURL(); int line = n.getLineno(); if (sourceModule instanceof MappedSourceModule) { Position loc = ((MappedSourceModule) sourceModule).getMapping().getAssociatedFileAndLine(line); if (loc != null) { return loc; } } return new LineNumberPosition(url, url, line); } private CAstNode noteSourcePosition(WalkContext context, CAstNode n, Node p) { if (p.getLineno() != -1 && context.pos().getPosition(n) == null) { context.pos().setPosition(n, makePosition(p)); } return n; } private CAstNode readName(WalkContext context, String name) { CAstNode cn = makeVarRef(name); context.cfg().map(cn, cn); CAstNode target = context.getCatchTarget(); if (target != null) { context.cfg().add(cn, target, JavaScriptTypes.ReferenceError); } else { context.cfg().add(cn, CAstControlFlowMap.EXCEPTION_TO_EXIT, JavaScriptTypes.ReferenceError); } return cn; } private CAstNode walkNodesInternal(final Node n, WalkContext context) { final int NT = n.getType(); switch (NT) { case Token.FUNCTION: { int fnIndex = n.getExistingIntProp(Node.FUNCTION_PROP); FunctionNode fn = context.top().getFunctionNode(fnIndex); CAstEntity fne = walkEntity(fn, context); if (context.expressionContext()) { CAstNode fun = Ast.makeNode(CAstNode.FUNCTION_EXPR, Ast.makeConstant(fne)); context.addScopedEntity(fun, fne); return fun; } else { context.addNameDecl(Ast.makeNode(CAstNode.FUNCTION_STMT, Ast.makeConstant(fne))); context.addScopedEntity(null, fne); return Ast.makeNode(CAstNode.EMPTY); } } case Token.CATCH_SCOPE: { Node catchVarNode = n.getFirstChild(); String catchVarName = catchVarNode.getString(); assert catchVarName != null; context.setCatchVar(catchVarName); return Ast.makeNode(CAstNode.EMPTY); } case Token.LOCAL_BLOCK: { return Ast.makeNode(CAstNode.BLOCK_EXPR, gatherChildren(n, context)); } case Token.TRY: { Node catchNode = ((Node.Jump) n).target; Node finallyNode = ((Node.Jump) n).getFinally(); ArrayList<Node> tryList = new ArrayList<Node>(); ArrayList<Node> catchList = new ArrayList<Node>(); ArrayList<Node> finallyList = new ArrayList<Node>(); ArrayList<Node> current = tryList; Node c; for (c = n.getFirstChild(); c.getNext() != null; c = c.getNext()) { if (c == catchNode) { current = catchList; } else if (c == finallyNode) { current = finallyList; } if (c.getType() == Token.GOTO && // ((Node.Jump)c).target == lastChildNode && (c.getNext() == catchNode || c.getNext() == finallyNode)) { continue; } current.add(c); } CAstNode finallyBlock = null; if (finallyNode != null) { int i = 0; CAstNode[] finallyAsts = new CAstNode[finallyList.size()]; for (Iterator<Node> fns = finallyList.iterator(); fns.hasNext();) { finallyAsts[i++] = walkNodes(fns.next(), context); } finallyBlock = Ast.makeNode(CAstNode.BLOCK_STMT, finallyAsts); } if (catchNode != null) { int i = 0; WalkContext catchChild = new CatchBlockContext(context); CAstNode[] catchAsts = new CAstNode[catchList.size()]; for (Iterator<Node> cns = catchList.iterator(); cns.hasNext();) { catchAsts[i++] = walkNodes(cns.next(), catchChild); } CAstNode catchBlock = Ast.makeNode(CAstNode.CATCH, Ast.makeConstant(catchChild.getCatchVar()), Ast.makeNode(CAstNode.BLOCK_STMT, catchAsts)); context.cfg().map(catchBlock, catchBlock); i = 0; WalkContext tryChild = new TryBlockContext(context, catchBlock); CAstNode[] tryAsts = new CAstNode[tryList.size()]; for (Iterator<Node> tns = tryList.iterator(); tns.hasNext();) { tryAsts[i++] = walkNodes(tns.next(), tryChild); } CAstNode tryBlock = Ast.makeNode(CAstNode.BLOCK_STMT, tryAsts); if (finallyBlock != null) { return Ast.makeNode(CAstNode.BLOCK_STMT, Ast.makeNode(CAstNode.UNWIND, Ast.makeNode(CAstNode.TRY, tryBlock, catchBlock), finallyBlock), walkNodes(c, context)); } else { return Ast.makeNode(CAstNode.BLOCK_STMT, Ast.makeNode(CAstNode.TRY, tryBlock, catchBlock), walkNodes(c, context)); } } else { int i = 0; CAstNode[] tryAsts = new CAstNode[tryList.size()]; for (Iterator<Node> tns = tryList.iterator(); tns.hasNext();) { tryAsts[i++] = walkNodes(tns.next(), context); } CAstNode tryBlock = Ast.makeNode(CAstNode.BLOCK_STMT, tryAsts); return Ast.makeNode( CAstNode.BLOCK_STMT, Ast.makeNode(CAstNode.UNWIND, Ast.makeNode(CAstNode.BLOCK_STMT, tryBlock), Ast.makeNode(CAstNode.BLOCK_STMT, finallyBlock)), walkNodes(c, context)); } } case Token.JSR: { return Ast.makeNode(CAstNode.EMPTY); /* * Node jsrTarget = ((Node.Jump)n).target; Node finallyNode = * jsrTarget.getNext(); return walkNodes(finallyNode, context); */ } case Token.COMMA: { int count = countSiblingsStartingFrom(n.getFirstChild()); CAstNode[] cs = new CAstNode[count]; int i = 0; for (Node c = n.getFirstChild(); c != null; i++, c = c.getNext()) { if (c.getNext() == null) { // for the final sub-expression of the comma, if we care about the // base pointer // of n, we care about the base pointer of c context.updateBase(n, c); } cs[i] = walkNodes(c, context); } return Ast.makeNode(CAstNode.BLOCK_EXPR, cs); } /* * case Token.ENTERWITH: { return * Ast.makeNode(JavaScriptCAstNode.ENTER_WITH, * walkNodes(n.getFirstChild(), context)); } * * case Token.LEAVEWITH: { return * Ast.makeNode(JavaScriptCAstNode.EXIT_WITH, Ast.makeConstant(null)); } */ case Token.ENTERWITH: case Token.LEAVEWITH: { return Ast.makeNode(CAstNode.EMPTY); } case Token.LOOP: { LoopContext child = new LoopContext(context); CAstNode[] nodes = gatherChildren(n, child); if (child.forInInitExpr != null) { String nm = child.forInVar; return Ast.makeNode(CAstNode.BLOCK_STMT, Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(nm, true)), walkNodes(child.forInInitExpr, context)), nodes); } else { return Ast.makeNode(CAstNode.BLOCK_STMT, nodes); } } case Token.WITH: case Token.FINALLY: case Token.BLOCK: case Token.LABEL: { Node c1 = n.getFirstChild(); if (c1 != null && c1.getType() == Token.SWITCH) { Node switchValue = c1.getFirstChild(); CAstNode defaultLabel = Ast.makeNode(CAstNode.LABEL_STMT, Ast.makeNode(CAstNode.EMPTY)); context.cfg().map(defaultLabel, defaultLabel); List<CAstNode> labelCasts = new ArrayList<CAstNode>(); for (Node kase = switchValue.getNext(); kase != null; kase = kase.getNext()) { assert kase.getType() == Token.CASE; Node caseLbl = kase.getFirstChild(); Node target = ((Node.Jump) kase).target; CAstNode labelCast = walkNodes(caseLbl, context); labelCasts.add(labelCast); context.cfg().add(c1, target, labelCast); } CAstNode[] children = new CAstNode[labelCasts.size() + 1]; int i = 0; children[i++] = Ast.makeNode(CAstNode.BLOCK_STMT, defaultLabel, gatherChildren(n, context, 1)); // Note that we are placing the labels as children in the AST // even if they are not used, because we want them copied when AST is // re-written. for (CAstNode labelCast : labelCasts) { children[i++] = labelCast; } context.cfg().add(c1, defaultLabel, CAstControlFlowMap.SWITCH_DEFAULT); CAstNode switchAst = Ast.makeNode(CAstNode.SWITCH, walkNodes(switchValue, context), children); noteSourcePosition(context, switchAst, c1); context.cfg().map(c1, switchAst); return switchAst; } else { return Ast.makeNode(CAstNode.BLOCK_STMT, gatherChildren(n, context)); } } case Token.EXPR_VOID: case Token.EXPR_RESULT: { WalkContext child = new ExpressionContext(context); Node expr = n.getFirstChild(); if (NT == Token.EXPR_RESULT) { // EXPR_RESULT node is just a wrapper, so if we care about base pointer // of n, we // care about child of n child.updateBase(n, expr); } return walkNodes(expr, child); } case Token.POS: { return Ast.makeNode(CAstNode.UNARY_EXPR, translateOpcode(Token.ADD), walkNodes(n.getFirstChild(), context)); } case Token.CALL: { if (!isPrimitiveCall(context, n)) { CAstNode base = makeVarRef("$$ base"); Node callee = n.getFirstChild(); WalkContext child = new BaseCollectingContext(context, callee, "$$ base"); CAstNode fun = walkNodes(callee, child); // the first actual parameter appearing within the parentheses of the // call (i.e., possibly excluding the 'this' parameter) Node firstParamInParens = callee.getNext(); if (child.foundBase(callee)) return Ast.makeNode( CAstNode.LOCAL_SCOPE, Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl("$$ base")), Ast.makeConstant(null)), makeCall(fun, base, firstParamInParens, context))); else { // pass the global object as the receiver argument return makeCall(fun, makeVarRef(JSSSAPropagationCallGraphBuilder.GLOBAL_OBJ_VAR_NAME), firstParamInParens, context); } } else { return Ast.makeNode(CAstNode.PRIMITIVE, gatherChildren(n, context, 1)); } } case Token.BINDNAME: case Token.NAME: { return readName(context, n.getString()); } case Token.THIS: { return makeVarRef("this"); } case Token.THISFN: { return makeVarRef(((FunctionNode) context.top()).getFunctionName()); } case Token.STRING: { return Ast.makeConstant(n.getString()); } case Token.NUMBER: { return Ast.makeConstant(n.getDouble()); } case Token.FALSE: { return Ast.makeConstant(false); } case Token.TRUE: { return Ast.makeConstant(true); } case Token.NULL: case Token.VOID: { return Ast.makeConstant(null); } case Token.ADD: case Token.DIV: case Token.LSH: case Token.MOD: case Token.MUL: case Token.RSH: case Token.SUB: case Token.URSH: case Token.BITAND: case Token.BITOR: case Token.BITXOR: case Token.EQ: case Token.SHEQ: case Token.GE: case Token.GT: case Token.LE: case Token.LT: case Token.SHNE: case Token.NE: { Node l = n.getFirstChild(); Node r = l.getNext(); return Ast.makeNode(CAstNode.BINARY_EXPR, translateOpcode(NT), walkNodes(l, context), walkNodes(r, context)); } case Token.NEG: { return Ast.makeNode(CAstNode.UNARY_EXPR, translateOpcode(Token.SUB), walkNodes(n.getFirstChild(), context)); } case Token.BITNOT: case Token.NOT: { return Ast.makeNode(CAstNode.UNARY_EXPR, translateOpcode(NT), walkNodes(n.getFirstChild(), context)); } case Token.VAR: case Token.CONST: { List<CAstNode> result = new ArrayList<CAstNode>(); Node nm = n.getFirstChild(); while (nm != null) { context.addNameDecl(Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(nm.getString())), readName(context, "$$undefined"))); if (nm.getFirstChild() != null) { WalkContext child = new ExpressionContext(context); result.add(Ast.makeNode(CAstNode.ASSIGN, makeVarRef(nm.getString()), walkNodes(nm.getFirstChild(), child))); } nm = nm.getNext(); } if (result.size() > 0) { return Ast.makeNode(CAstNode.BLOCK_EXPR, result.toArray(new CAstNode[result.size()])); } else { return Ast.makeNode(CAstNode.EMPTY); } } case Token.REGEXP: { int regexIdx = n.getIntProp(Node.REGEXP_PROP, -1); assert regexIdx != -1 : "while converting: " + context.top().toStringTree(context.top()) + "\nlooking at bad regex:\n " + n.toStringTree(context.top()); String flags = context.top().getRegexpFlags(regexIdx); Node flagsNode = Node.newString(flags); String str = context.top().getRegexpString(regexIdx); Node strNode = Node.newString(str); strNode.addChildToFront(flagsNode); return handleNew(context, "RegExp", strNode); } case Token.ENUM_INIT_KEYS: { context.createForInVar(n.getFirstChild()); return Ast.makeNode(CAstNode.EMPTY); } case Token.ENUM_ID: { return Ast.makeNode(CAstNode.EACH_ELEMENT_GET, makeVarRef(context.getForInInitVar())); } case Token.ENUM_NEXT: { return Ast.makeNode(CAstNode.EACH_ELEMENT_HAS_NEXT, makeVarRef(context.getForInInitVar())); } case Token.RETURN: { Node val = n.getFirstChild(); if (val != null) { WalkContext child = new ExpressionContext(context); return Ast.makeNode(CAstNode.RETURN, walkNodes(val, child)); } else { return Ast.makeNode(CAstNode.RETURN); } } case Token.SETNAME: { Node nm = n.getFirstChild(); return Ast.makeNode(CAstNode.ASSIGN, walkNodes(nm, context), walkNodes(nm.getNext(), context)); } case Token.IFNE: case Token.IFEQ: { context.cfg().add(n, ((Node.Jump) n).target, Boolean.TRUE); WalkContext child = new ExpressionContext(context); CAstNode gotoAst = Ast.makeNode(CAstNode.IFGOTO, translateOpcode(NT), walkNodes(n.getFirstChild(), child), Ast.makeConstant(1)); context.cfg().map(n, gotoAst); return gotoAst; } case Token.GOTO: { context.cfg().add(n, ((Node.Jump) n).target, null); CAstNode gotoAst = Ast.makeNode(CAstNode.GOTO, Ast.makeConstant(((Node.Jump) n).target.labelId())); context.cfg().map(n, gotoAst); return gotoAst; } case Token.BREAK: { context.cfg().add(n, ((Node.Jump) n).getJumpStatement().target, null); CAstNode gotoAst = Ast.makeNode(CAstNode.GOTO, Ast.makeConstant(((Node.Jump) n).getJumpStatement().target.labelId())); context.cfg().map(n, gotoAst); return gotoAst; } case Token.CONTINUE: { context.cfg().add(n, ((Node.Jump) n).getJumpStatement().getContinue(), null); CAstNode gotoAst = Ast.makeNode(CAstNode.GOTO, Ast.makeConstant(((Node.Jump) n).getJumpStatement().getContinue().labelId())); context.cfg().map(n, gotoAst); return gotoAst; } case Token.TARGET: { CAstNode result = Ast.makeNode(CAstNode.LABEL_STMT, Ast.makeConstant(n.labelId()), Ast.makeNode(CAstNode.EMPTY)); context.cfg().map(n, result); return result; } case Token.OR: { Node l = n.getFirstChild(); Node r = l.getNext(); CAstNode lhs = walkNodes(l, context); String lhsTempName = "or___lhs"; // { lhsTemp := <lhs>; if(lhsTemp) { lhsTemp } else { <rhs> } return Ast.makeNode( CAstNode.LOCAL_SCOPE, Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(lhsTempName)), lhs), Ast.makeNode(CAstNode.IF_EXPR, makeVarRef(lhsTempName), makeVarRef(lhsTempName), walkNodes(r, context)))); } case Token.AND: { Node l = n.getFirstChild(); Node r = l.getNext(); CAstNode lhs = walkNodes(l, context); String lhsTempName = "and___lhs"; // { lhsTemp := <lhs>; if(lhsTemp) { <rhs> } else { lhsTemp } return Ast.makeNode( CAstNode.LOCAL_SCOPE, Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(lhsTempName)), lhs), Ast.makeNode(CAstNode.IF_EXPR, makeVarRef(lhsTempName), walkNodes(r, context), makeVarRef(lhsTempName)))); } case Token.HOOK: { Node cond = n.getFirstChild(); Node thenBranch = cond.getNext(); Node elseBranch = thenBranch.getNext(); return Ast.makeNode(CAstNode.IF_EXPR, walkNodes(cond, context), walkNodes(thenBranch, context), walkNodes(elseBranch, context)); } case Token.INC: case Token.DEC: { int flags = n.getIntProp(Node.INCRDECR_PROP, -1); CAstNode op = ((flags & Node.DECR_FLAG) != 0) ? CAstOperator.OP_SUB : CAstOperator.OP_ADD; Node l = n.getFirstChild(); CAstNode last = walkNodes(l, context); return Ast.makeNode((((flags & Node.POST_FLAG) != 0) ? CAstNode.ASSIGN_POST_OP : CAstNode.ASSIGN_PRE_OP), last, Ast.makeConstant(1), op); } case Token.NEW: { if (isPrimitiveCreation(context, n)) { return makeBuiltinNew(n.getFirstChild().getString()); } else { Node receiver = n.getFirstChild(); return handleNew(context, walkNodes(receiver, context), receiver.getNext()); } } case Token.ARRAYLIT: { int count = 0; for (Node x = n.getFirstChild(); x != null; count++, x = x.getNext()) ; int i = 0; CAstNode[] args = new CAstNode[2 * count + 1]; args[i++] = (isPrologueScript(context)) ? makeBuiltinNew("Array") : handleNew(context, "Array", null); int[] skips = (int[]) n.getProp(Node.SKIP_INDEXES_PROP); int skip = 0; int idx = 0; Node elt = n.getFirstChild(); while (elt != null) { if (skips != null && skip < skips.length && skips[skip] == idx) { skip++; idx++; continue; } args[i++] = Ast.makeConstant(idx++); args[i++] = walkNodes(elt, context); elt = elt.getNext(); } return Ast.makeNode(CAstNode.OBJECT_LITERAL, args); } case Token.OBJECTLIT: { Object[] propertyList = (Object[]) n.getProp(Node.OBJECT_IDS_PROP); CAstNode[] args = new CAstNode[propertyList.length * 2 + 1]; int i = 0; args[i++] = ((isPrologueScript(context)) ? makeBuiltinNew("Object") : handleNew(context, "Object", null)); Node val = n.getFirstChild(); int nameIdx = 0; for (; nameIdx < propertyList.length; nameIdx++, val = val.getNext()) { args[i++] = Ast.makeConstant(propertyList[nameIdx]); args[i++] = walkNodes(val, context); } return Ast.makeNode(CAstNode.OBJECT_LITERAL, args); } case Token.GETPROP: case Token.GETELEM: { Node receiver = n.getFirstChild(); Node element = receiver.getNext(); CAstNode rcvr = walkNodes(receiver, context); String baseVarName = context.getBaseVarNameIfRelevant(n); CAstNode elt = walkNodes(element, context); CAstNode get, result; if (baseVarName != null) { result = Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.ASSIGN, makeVarRef(baseVarName), rcvr), get = Ast.makeNode(CAstNode.OBJECT_REF, makeVarRef(baseVarName), elt)); } else { result = get = Ast.makeNode(CAstNode.OBJECT_REF, rcvr, elt); } if (context.getCatchTarget() != null) { context.cfg().map(get, get); context.cfg().add(get, context.getCatchTarget(), JavaScriptTypes.TypeError); } return result; } case Token.GET_REF: { // read of __proto__ // first and only child c1 is of type Token.REF_SPECIAL whose NAME_PROP property should be "__proto__". // c1 has a single child, the base pointer for the reference Node child1 = n.getFirstChild(); assert child1.getType() == Token.REF_SPECIAL; assert child1.getProp(Node.NAME_PROP).equals("__proto__"); Node receiver = child1.getFirstChild(); assert child1.getNext() == null; CAstNode rcvr = walkNodes(receiver, context); final CAstNode result = Ast.makeNode(CAstNode.OBJECT_REF, rcvr, Ast.makeConstant("__proto__")); if (context.getCatchTarget() != null) { context.cfg().map(result, result); context.cfg().add(result, context.getCatchTarget(), JavaScriptTypes.TypeError); } return result; } case Token.SETPROP: case Token.SETELEM: { Node receiver = n.getFirstChild(); Node elt = receiver.getNext(); Node val = elt.getNext(); CAstNode rcvr = walkNodes(receiver, context); return Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, walkNodes(elt, context)), walkNodes(val, context)); } case Token.SET_REF: { // first child c1 is of type Token.REF_SPECIAL whose NAME_PROP property should be "__proto__". // c1 has a single child, the base pointer for the reference // second child c2 is RHS of assignment Node child1 = n.getFirstChild(); assert child1.getType() == Token.REF_SPECIAL; assert child1.getProp(Node.NAME_PROP).equals("__proto__"); Node receiver = child1.getFirstChild(); Node val = child1.getNext(); CAstNode rcvr = walkNodes(receiver, context); return Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, Ast.makeConstant("__proto__")), walkNodes(val, context)); } case Token.DELPROP: { Node receiver = n.getFirstChild(); Node element = receiver.getNext(); CAstNode rcvr = walkNodes(receiver, context); String baseVarName = context.getBaseVarNameIfRelevant(n); CAstNode elt = walkNodes(element, context); if (baseVarName != null) { return Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.ASSIGN, makeVarRef(baseVarName), rcvr), Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, makeVarRef(baseVarName), elt), Ast.makeConstant(null))); } else { return Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, elt), Ast.makeConstant(null)); } } case Token.TYPEOFNAME: { return Ast.makeNode(CAstNode.TYPE_OF, makeVarRef(n.getString())); } case Token.TYPEOF: { return Ast.makeNode(CAstNode.TYPE_OF, walkNodes(n.getFirstChild(), context)); } case Token.SETPROP_OP: case Token.SETELEM_OP: { Node receiver = n.getFirstChild(); Node elt = receiver.getNext(); Node op = elt.getNext(); CAstNode rcvr = walkNodes(receiver, context); return Ast.makeNode(CAstNode.ASSIGN_POST_OP, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, walkNodes(elt, context)), walkNodes(op.getFirstChild().getNext(), context), translateOpcode(op.getType())); } case Token.THROW: { CAstNode catchNode = context.getCatchTarget(); if (catchNode != null) context.cfg().add(n, context.getCatchTarget(), null); else context.cfg().add(n, CAstControlFlowMap.EXCEPTION_TO_EXIT, null); CAstNode throwAst = Ast.makeNode(CAstNode.THROW, walkNodes(n.getFirstChild(), context)); context.cfg().map(n, throwAst); return throwAst; } case Token.EMPTY: { return Ast.makeConstant(null); } case Token.INSTANCEOF: { Node value = n.getFirstChild(); Node type = value.getNext(); return Ast.makeNode(CAstNode.INSTANCEOF, walkNodes(value, context), walkNodes(type, context)); } case Token.IN: { Node value = n.getFirstChild(); Node property = value.getNext(); - return Ast.makeNode(CAstNode.IS_DEFINED_EXPR, walkNodes(value, context), walkNodes(property, context)); + return Ast.makeNode(CAstNode.IS_DEFINED_EXPR, walkNodes(property, context), walkNodes(value, context)); } default: { System.err.println("while converting: " + context.top().toStringTree(context.top()) + "\nlooking at unhandled:\n " + n.toStringTree(context.top()) + "\n(of type " + NT + ") (of class " + n.getClass() + ")" + " at " + n.getLineno()); Assertions.UNREACHABLE(); return null; } } } private CAstNode makeVarRef(String varName) { return Ast.makeNode(CAstNode.VAR, Ast.makeConstant(varName)); } /** * parse the JavaScript code using Rhino, and then translate the resulting AST * to CAst */ public CAstEntity translate() throws java.io.IOException { ToolErrorReporter reporter = new ToolErrorReporter(true); CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.setErrorReporter(reporter); compilerEnv.setReservedKeywordAsIdentifier(true); if (DEBUG) System.err.println(("translating " + scriptName + " with Rhino")); Parser P = new Parser(compilerEnv, compilerEnv.getErrorReporter()); sourceReader = sourceModule.getInputReader(); ScriptOrFnNode top = P.parse(sourceReader, scriptName, 1); return walkEntity(top, new RootContext()); } private final CAst Ast; private final String scriptName; private final SourceModule sourceModule; private Reader sourceReader; private int anonymousCounter = 0; public RhinoToAstTranslator(CAst Ast, SourceModule M, String scriptName) { this.Ast = Ast; this.scriptName = scriptName; this.sourceModule = M; } public static void resetGensymCounters() { LoopContext.counter = 0; } }
true
true
private CAstNode walkNodesInternal(final Node n, WalkContext context) { final int NT = n.getType(); switch (NT) { case Token.FUNCTION: { int fnIndex = n.getExistingIntProp(Node.FUNCTION_PROP); FunctionNode fn = context.top().getFunctionNode(fnIndex); CAstEntity fne = walkEntity(fn, context); if (context.expressionContext()) { CAstNode fun = Ast.makeNode(CAstNode.FUNCTION_EXPR, Ast.makeConstant(fne)); context.addScopedEntity(fun, fne); return fun; } else { context.addNameDecl(Ast.makeNode(CAstNode.FUNCTION_STMT, Ast.makeConstant(fne))); context.addScopedEntity(null, fne); return Ast.makeNode(CAstNode.EMPTY); } } case Token.CATCH_SCOPE: { Node catchVarNode = n.getFirstChild(); String catchVarName = catchVarNode.getString(); assert catchVarName != null; context.setCatchVar(catchVarName); return Ast.makeNode(CAstNode.EMPTY); } case Token.LOCAL_BLOCK: { return Ast.makeNode(CAstNode.BLOCK_EXPR, gatherChildren(n, context)); } case Token.TRY: { Node catchNode = ((Node.Jump) n).target; Node finallyNode = ((Node.Jump) n).getFinally(); ArrayList<Node> tryList = new ArrayList<Node>(); ArrayList<Node> catchList = new ArrayList<Node>(); ArrayList<Node> finallyList = new ArrayList<Node>(); ArrayList<Node> current = tryList; Node c; for (c = n.getFirstChild(); c.getNext() != null; c = c.getNext()) { if (c == catchNode) { current = catchList; } else if (c == finallyNode) { current = finallyList; } if (c.getType() == Token.GOTO && // ((Node.Jump)c).target == lastChildNode && (c.getNext() == catchNode || c.getNext() == finallyNode)) { continue; } current.add(c); } CAstNode finallyBlock = null; if (finallyNode != null) { int i = 0; CAstNode[] finallyAsts = new CAstNode[finallyList.size()]; for (Iterator<Node> fns = finallyList.iterator(); fns.hasNext();) { finallyAsts[i++] = walkNodes(fns.next(), context); } finallyBlock = Ast.makeNode(CAstNode.BLOCK_STMT, finallyAsts); } if (catchNode != null) { int i = 0; WalkContext catchChild = new CatchBlockContext(context); CAstNode[] catchAsts = new CAstNode[catchList.size()]; for (Iterator<Node> cns = catchList.iterator(); cns.hasNext();) { catchAsts[i++] = walkNodes(cns.next(), catchChild); } CAstNode catchBlock = Ast.makeNode(CAstNode.CATCH, Ast.makeConstant(catchChild.getCatchVar()), Ast.makeNode(CAstNode.BLOCK_STMT, catchAsts)); context.cfg().map(catchBlock, catchBlock); i = 0; WalkContext tryChild = new TryBlockContext(context, catchBlock); CAstNode[] tryAsts = new CAstNode[tryList.size()]; for (Iterator<Node> tns = tryList.iterator(); tns.hasNext();) { tryAsts[i++] = walkNodes(tns.next(), tryChild); } CAstNode tryBlock = Ast.makeNode(CAstNode.BLOCK_STMT, tryAsts); if (finallyBlock != null) { return Ast.makeNode(CAstNode.BLOCK_STMT, Ast.makeNode(CAstNode.UNWIND, Ast.makeNode(CAstNode.TRY, tryBlock, catchBlock), finallyBlock), walkNodes(c, context)); } else { return Ast.makeNode(CAstNode.BLOCK_STMT, Ast.makeNode(CAstNode.TRY, tryBlock, catchBlock), walkNodes(c, context)); } } else { int i = 0; CAstNode[] tryAsts = new CAstNode[tryList.size()]; for (Iterator<Node> tns = tryList.iterator(); tns.hasNext();) { tryAsts[i++] = walkNodes(tns.next(), context); } CAstNode tryBlock = Ast.makeNode(CAstNode.BLOCK_STMT, tryAsts); return Ast.makeNode( CAstNode.BLOCK_STMT, Ast.makeNode(CAstNode.UNWIND, Ast.makeNode(CAstNode.BLOCK_STMT, tryBlock), Ast.makeNode(CAstNode.BLOCK_STMT, finallyBlock)), walkNodes(c, context)); } } case Token.JSR: { return Ast.makeNode(CAstNode.EMPTY); /* * Node jsrTarget = ((Node.Jump)n).target; Node finallyNode = * jsrTarget.getNext(); return walkNodes(finallyNode, context); */ } case Token.COMMA: { int count = countSiblingsStartingFrom(n.getFirstChild()); CAstNode[] cs = new CAstNode[count]; int i = 0; for (Node c = n.getFirstChild(); c != null; i++, c = c.getNext()) { if (c.getNext() == null) { // for the final sub-expression of the comma, if we care about the // base pointer // of n, we care about the base pointer of c context.updateBase(n, c); } cs[i] = walkNodes(c, context); } return Ast.makeNode(CAstNode.BLOCK_EXPR, cs); } /* * case Token.ENTERWITH: { return * Ast.makeNode(JavaScriptCAstNode.ENTER_WITH, * walkNodes(n.getFirstChild(), context)); } * * case Token.LEAVEWITH: { return * Ast.makeNode(JavaScriptCAstNode.EXIT_WITH, Ast.makeConstant(null)); } */ case Token.ENTERWITH: case Token.LEAVEWITH: { return Ast.makeNode(CAstNode.EMPTY); } case Token.LOOP: { LoopContext child = new LoopContext(context); CAstNode[] nodes = gatherChildren(n, child); if (child.forInInitExpr != null) { String nm = child.forInVar; return Ast.makeNode(CAstNode.BLOCK_STMT, Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(nm, true)), walkNodes(child.forInInitExpr, context)), nodes); } else { return Ast.makeNode(CAstNode.BLOCK_STMT, nodes); } } case Token.WITH: case Token.FINALLY: case Token.BLOCK: case Token.LABEL: { Node c1 = n.getFirstChild(); if (c1 != null && c1.getType() == Token.SWITCH) { Node switchValue = c1.getFirstChild(); CAstNode defaultLabel = Ast.makeNode(CAstNode.LABEL_STMT, Ast.makeNode(CAstNode.EMPTY)); context.cfg().map(defaultLabel, defaultLabel); List<CAstNode> labelCasts = new ArrayList<CAstNode>(); for (Node kase = switchValue.getNext(); kase != null; kase = kase.getNext()) { assert kase.getType() == Token.CASE; Node caseLbl = kase.getFirstChild(); Node target = ((Node.Jump) kase).target; CAstNode labelCast = walkNodes(caseLbl, context); labelCasts.add(labelCast); context.cfg().add(c1, target, labelCast); } CAstNode[] children = new CAstNode[labelCasts.size() + 1]; int i = 0; children[i++] = Ast.makeNode(CAstNode.BLOCK_STMT, defaultLabel, gatherChildren(n, context, 1)); // Note that we are placing the labels as children in the AST // even if they are not used, because we want them copied when AST is // re-written. for (CAstNode labelCast : labelCasts) { children[i++] = labelCast; } context.cfg().add(c1, defaultLabel, CAstControlFlowMap.SWITCH_DEFAULT); CAstNode switchAst = Ast.makeNode(CAstNode.SWITCH, walkNodes(switchValue, context), children); noteSourcePosition(context, switchAst, c1); context.cfg().map(c1, switchAst); return switchAst; } else { return Ast.makeNode(CAstNode.BLOCK_STMT, gatherChildren(n, context)); } } case Token.EXPR_VOID: case Token.EXPR_RESULT: { WalkContext child = new ExpressionContext(context); Node expr = n.getFirstChild(); if (NT == Token.EXPR_RESULT) { // EXPR_RESULT node is just a wrapper, so if we care about base pointer // of n, we // care about child of n child.updateBase(n, expr); } return walkNodes(expr, child); } case Token.POS: { return Ast.makeNode(CAstNode.UNARY_EXPR, translateOpcode(Token.ADD), walkNodes(n.getFirstChild(), context)); } case Token.CALL: { if (!isPrimitiveCall(context, n)) { CAstNode base = makeVarRef("$$ base"); Node callee = n.getFirstChild(); WalkContext child = new BaseCollectingContext(context, callee, "$$ base"); CAstNode fun = walkNodes(callee, child); // the first actual parameter appearing within the parentheses of the // call (i.e., possibly excluding the 'this' parameter) Node firstParamInParens = callee.getNext(); if (child.foundBase(callee)) return Ast.makeNode( CAstNode.LOCAL_SCOPE, Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl("$$ base")), Ast.makeConstant(null)), makeCall(fun, base, firstParamInParens, context))); else { // pass the global object as the receiver argument return makeCall(fun, makeVarRef(JSSSAPropagationCallGraphBuilder.GLOBAL_OBJ_VAR_NAME), firstParamInParens, context); } } else { return Ast.makeNode(CAstNode.PRIMITIVE, gatherChildren(n, context, 1)); } } case Token.BINDNAME: case Token.NAME: { return readName(context, n.getString()); } case Token.THIS: { return makeVarRef("this"); } case Token.THISFN: { return makeVarRef(((FunctionNode) context.top()).getFunctionName()); } case Token.STRING: { return Ast.makeConstant(n.getString()); } case Token.NUMBER: { return Ast.makeConstant(n.getDouble()); } case Token.FALSE: { return Ast.makeConstant(false); } case Token.TRUE: { return Ast.makeConstant(true); } case Token.NULL: case Token.VOID: { return Ast.makeConstant(null); } case Token.ADD: case Token.DIV: case Token.LSH: case Token.MOD: case Token.MUL: case Token.RSH: case Token.SUB: case Token.URSH: case Token.BITAND: case Token.BITOR: case Token.BITXOR: case Token.EQ: case Token.SHEQ: case Token.GE: case Token.GT: case Token.LE: case Token.LT: case Token.SHNE: case Token.NE: { Node l = n.getFirstChild(); Node r = l.getNext(); return Ast.makeNode(CAstNode.BINARY_EXPR, translateOpcode(NT), walkNodes(l, context), walkNodes(r, context)); } case Token.NEG: { return Ast.makeNode(CAstNode.UNARY_EXPR, translateOpcode(Token.SUB), walkNodes(n.getFirstChild(), context)); } case Token.BITNOT: case Token.NOT: { return Ast.makeNode(CAstNode.UNARY_EXPR, translateOpcode(NT), walkNodes(n.getFirstChild(), context)); } case Token.VAR: case Token.CONST: { List<CAstNode> result = new ArrayList<CAstNode>(); Node nm = n.getFirstChild(); while (nm != null) { context.addNameDecl(Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(nm.getString())), readName(context, "$$undefined"))); if (nm.getFirstChild() != null) { WalkContext child = new ExpressionContext(context); result.add(Ast.makeNode(CAstNode.ASSIGN, makeVarRef(nm.getString()), walkNodes(nm.getFirstChild(), child))); } nm = nm.getNext(); } if (result.size() > 0) { return Ast.makeNode(CAstNode.BLOCK_EXPR, result.toArray(new CAstNode[result.size()])); } else { return Ast.makeNode(CAstNode.EMPTY); } } case Token.REGEXP: { int regexIdx = n.getIntProp(Node.REGEXP_PROP, -1); assert regexIdx != -1 : "while converting: " + context.top().toStringTree(context.top()) + "\nlooking at bad regex:\n " + n.toStringTree(context.top()); String flags = context.top().getRegexpFlags(regexIdx); Node flagsNode = Node.newString(flags); String str = context.top().getRegexpString(regexIdx); Node strNode = Node.newString(str); strNode.addChildToFront(flagsNode); return handleNew(context, "RegExp", strNode); } case Token.ENUM_INIT_KEYS: { context.createForInVar(n.getFirstChild()); return Ast.makeNode(CAstNode.EMPTY); } case Token.ENUM_ID: { return Ast.makeNode(CAstNode.EACH_ELEMENT_GET, makeVarRef(context.getForInInitVar())); } case Token.ENUM_NEXT: { return Ast.makeNode(CAstNode.EACH_ELEMENT_HAS_NEXT, makeVarRef(context.getForInInitVar())); } case Token.RETURN: { Node val = n.getFirstChild(); if (val != null) { WalkContext child = new ExpressionContext(context); return Ast.makeNode(CAstNode.RETURN, walkNodes(val, child)); } else { return Ast.makeNode(CAstNode.RETURN); } } case Token.SETNAME: { Node nm = n.getFirstChild(); return Ast.makeNode(CAstNode.ASSIGN, walkNodes(nm, context), walkNodes(nm.getNext(), context)); } case Token.IFNE: case Token.IFEQ: { context.cfg().add(n, ((Node.Jump) n).target, Boolean.TRUE); WalkContext child = new ExpressionContext(context); CAstNode gotoAst = Ast.makeNode(CAstNode.IFGOTO, translateOpcode(NT), walkNodes(n.getFirstChild(), child), Ast.makeConstant(1)); context.cfg().map(n, gotoAst); return gotoAst; } case Token.GOTO: { context.cfg().add(n, ((Node.Jump) n).target, null); CAstNode gotoAst = Ast.makeNode(CAstNode.GOTO, Ast.makeConstant(((Node.Jump) n).target.labelId())); context.cfg().map(n, gotoAst); return gotoAst; } case Token.BREAK: { context.cfg().add(n, ((Node.Jump) n).getJumpStatement().target, null); CAstNode gotoAst = Ast.makeNode(CAstNode.GOTO, Ast.makeConstant(((Node.Jump) n).getJumpStatement().target.labelId())); context.cfg().map(n, gotoAst); return gotoAst; } case Token.CONTINUE: { context.cfg().add(n, ((Node.Jump) n).getJumpStatement().getContinue(), null); CAstNode gotoAst = Ast.makeNode(CAstNode.GOTO, Ast.makeConstant(((Node.Jump) n).getJumpStatement().getContinue().labelId())); context.cfg().map(n, gotoAst); return gotoAst; } case Token.TARGET: { CAstNode result = Ast.makeNode(CAstNode.LABEL_STMT, Ast.makeConstant(n.labelId()), Ast.makeNode(CAstNode.EMPTY)); context.cfg().map(n, result); return result; } case Token.OR: { Node l = n.getFirstChild(); Node r = l.getNext(); CAstNode lhs = walkNodes(l, context); String lhsTempName = "or___lhs"; // { lhsTemp := <lhs>; if(lhsTemp) { lhsTemp } else { <rhs> } return Ast.makeNode( CAstNode.LOCAL_SCOPE, Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(lhsTempName)), lhs), Ast.makeNode(CAstNode.IF_EXPR, makeVarRef(lhsTempName), makeVarRef(lhsTempName), walkNodes(r, context)))); } case Token.AND: { Node l = n.getFirstChild(); Node r = l.getNext(); CAstNode lhs = walkNodes(l, context); String lhsTempName = "and___lhs"; // { lhsTemp := <lhs>; if(lhsTemp) { <rhs> } else { lhsTemp } return Ast.makeNode( CAstNode.LOCAL_SCOPE, Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(lhsTempName)), lhs), Ast.makeNode(CAstNode.IF_EXPR, makeVarRef(lhsTempName), walkNodes(r, context), makeVarRef(lhsTempName)))); } case Token.HOOK: { Node cond = n.getFirstChild(); Node thenBranch = cond.getNext(); Node elseBranch = thenBranch.getNext(); return Ast.makeNode(CAstNode.IF_EXPR, walkNodes(cond, context), walkNodes(thenBranch, context), walkNodes(elseBranch, context)); } case Token.INC: case Token.DEC: { int flags = n.getIntProp(Node.INCRDECR_PROP, -1); CAstNode op = ((flags & Node.DECR_FLAG) != 0) ? CAstOperator.OP_SUB : CAstOperator.OP_ADD; Node l = n.getFirstChild(); CAstNode last = walkNodes(l, context); return Ast.makeNode((((flags & Node.POST_FLAG) != 0) ? CAstNode.ASSIGN_POST_OP : CAstNode.ASSIGN_PRE_OP), last, Ast.makeConstant(1), op); } case Token.NEW: { if (isPrimitiveCreation(context, n)) { return makeBuiltinNew(n.getFirstChild().getString()); } else { Node receiver = n.getFirstChild(); return handleNew(context, walkNodes(receiver, context), receiver.getNext()); } } case Token.ARRAYLIT: { int count = 0; for (Node x = n.getFirstChild(); x != null; count++, x = x.getNext()) ; int i = 0; CAstNode[] args = new CAstNode[2 * count + 1]; args[i++] = (isPrologueScript(context)) ? makeBuiltinNew("Array") : handleNew(context, "Array", null); int[] skips = (int[]) n.getProp(Node.SKIP_INDEXES_PROP); int skip = 0; int idx = 0; Node elt = n.getFirstChild(); while (elt != null) { if (skips != null && skip < skips.length && skips[skip] == idx) { skip++; idx++; continue; } args[i++] = Ast.makeConstant(idx++); args[i++] = walkNodes(elt, context); elt = elt.getNext(); } return Ast.makeNode(CAstNode.OBJECT_LITERAL, args); } case Token.OBJECTLIT: { Object[] propertyList = (Object[]) n.getProp(Node.OBJECT_IDS_PROP); CAstNode[] args = new CAstNode[propertyList.length * 2 + 1]; int i = 0; args[i++] = ((isPrologueScript(context)) ? makeBuiltinNew("Object") : handleNew(context, "Object", null)); Node val = n.getFirstChild(); int nameIdx = 0; for (; nameIdx < propertyList.length; nameIdx++, val = val.getNext()) { args[i++] = Ast.makeConstant(propertyList[nameIdx]); args[i++] = walkNodes(val, context); } return Ast.makeNode(CAstNode.OBJECT_LITERAL, args); } case Token.GETPROP: case Token.GETELEM: { Node receiver = n.getFirstChild(); Node element = receiver.getNext(); CAstNode rcvr = walkNodes(receiver, context); String baseVarName = context.getBaseVarNameIfRelevant(n); CAstNode elt = walkNodes(element, context); CAstNode get, result; if (baseVarName != null) { result = Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.ASSIGN, makeVarRef(baseVarName), rcvr), get = Ast.makeNode(CAstNode.OBJECT_REF, makeVarRef(baseVarName), elt)); } else { result = get = Ast.makeNode(CAstNode.OBJECT_REF, rcvr, elt); } if (context.getCatchTarget() != null) { context.cfg().map(get, get); context.cfg().add(get, context.getCatchTarget(), JavaScriptTypes.TypeError); } return result; } case Token.GET_REF: { // read of __proto__ // first and only child c1 is of type Token.REF_SPECIAL whose NAME_PROP property should be "__proto__". // c1 has a single child, the base pointer for the reference Node child1 = n.getFirstChild(); assert child1.getType() == Token.REF_SPECIAL; assert child1.getProp(Node.NAME_PROP).equals("__proto__"); Node receiver = child1.getFirstChild(); assert child1.getNext() == null; CAstNode rcvr = walkNodes(receiver, context); final CAstNode result = Ast.makeNode(CAstNode.OBJECT_REF, rcvr, Ast.makeConstant("__proto__")); if (context.getCatchTarget() != null) { context.cfg().map(result, result); context.cfg().add(result, context.getCatchTarget(), JavaScriptTypes.TypeError); } return result; } case Token.SETPROP: case Token.SETELEM: { Node receiver = n.getFirstChild(); Node elt = receiver.getNext(); Node val = elt.getNext(); CAstNode rcvr = walkNodes(receiver, context); return Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, walkNodes(elt, context)), walkNodes(val, context)); } case Token.SET_REF: { // first child c1 is of type Token.REF_SPECIAL whose NAME_PROP property should be "__proto__". // c1 has a single child, the base pointer for the reference // second child c2 is RHS of assignment Node child1 = n.getFirstChild(); assert child1.getType() == Token.REF_SPECIAL; assert child1.getProp(Node.NAME_PROP).equals("__proto__"); Node receiver = child1.getFirstChild(); Node val = child1.getNext(); CAstNode rcvr = walkNodes(receiver, context); return Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, Ast.makeConstant("__proto__")), walkNodes(val, context)); } case Token.DELPROP: { Node receiver = n.getFirstChild(); Node element = receiver.getNext(); CAstNode rcvr = walkNodes(receiver, context); String baseVarName = context.getBaseVarNameIfRelevant(n); CAstNode elt = walkNodes(element, context); if (baseVarName != null) { return Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.ASSIGN, makeVarRef(baseVarName), rcvr), Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, makeVarRef(baseVarName), elt), Ast.makeConstant(null))); } else { return Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, elt), Ast.makeConstant(null)); } } case Token.TYPEOFNAME: { return Ast.makeNode(CAstNode.TYPE_OF, makeVarRef(n.getString())); } case Token.TYPEOF: { return Ast.makeNode(CAstNode.TYPE_OF, walkNodes(n.getFirstChild(), context)); } case Token.SETPROP_OP: case Token.SETELEM_OP: { Node receiver = n.getFirstChild(); Node elt = receiver.getNext(); Node op = elt.getNext(); CAstNode rcvr = walkNodes(receiver, context); return Ast.makeNode(CAstNode.ASSIGN_POST_OP, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, walkNodes(elt, context)), walkNodes(op.getFirstChild().getNext(), context), translateOpcode(op.getType())); } case Token.THROW: { CAstNode catchNode = context.getCatchTarget(); if (catchNode != null) context.cfg().add(n, context.getCatchTarget(), null); else context.cfg().add(n, CAstControlFlowMap.EXCEPTION_TO_EXIT, null); CAstNode throwAst = Ast.makeNode(CAstNode.THROW, walkNodes(n.getFirstChild(), context)); context.cfg().map(n, throwAst); return throwAst; } case Token.EMPTY: { return Ast.makeConstant(null); } case Token.INSTANCEOF: { Node value = n.getFirstChild(); Node type = value.getNext(); return Ast.makeNode(CAstNode.INSTANCEOF, walkNodes(value, context), walkNodes(type, context)); } case Token.IN: { Node value = n.getFirstChild(); Node property = value.getNext(); return Ast.makeNode(CAstNode.IS_DEFINED_EXPR, walkNodes(value, context), walkNodes(property, context)); } default: { System.err.println("while converting: " + context.top().toStringTree(context.top()) + "\nlooking at unhandled:\n " + n.toStringTree(context.top()) + "\n(of type " + NT + ") (of class " + n.getClass() + ")" + " at " + n.getLineno()); Assertions.UNREACHABLE(); return null; } } }
private CAstNode walkNodesInternal(final Node n, WalkContext context) { final int NT = n.getType(); switch (NT) { case Token.FUNCTION: { int fnIndex = n.getExistingIntProp(Node.FUNCTION_PROP); FunctionNode fn = context.top().getFunctionNode(fnIndex); CAstEntity fne = walkEntity(fn, context); if (context.expressionContext()) { CAstNode fun = Ast.makeNode(CAstNode.FUNCTION_EXPR, Ast.makeConstant(fne)); context.addScopedEntity(fun, fne); return fun; } else { context.addNameDecl(Ast.makeNode(CAstNode.FUNCTION_STMT, Ast.makeConstant(fne))); context.addScopedEntity(null, fne); return Ast.makeNode(CAstNode.EMPTY); } } case Token.CATCH_SCOPE: { Node catchVarNode = n.getFirstChild(); String catchVarName = catchVarNode.getString(); assert catchVarName != null; context.setCatchVar(catchVarName); return Ast.makeNode(CAstNode.EMPTY); } case Token.LOCAL_BLOCK: { return Ast.makeNode(CAstNode.BLOCK_EXPR, gatherChildren(n, context)); } case Token.TRY: { Node catchNode = ((Node.Jump) n).target; Node finallyNode = ((Node.Jump) n).getFinally(); ArrayList<Node> tryList = new ArrayList<Node>(); ArrayList<Node> catchList = new ArrayList<Node>(); ArrayList<Node> finallyList = new ArrayList<Node>(); ArrayList<Node> current = tryList; Node c; for (c = n.getFirstChild(); c.getNext() != null; c = c.getNext()) { if (c == catchNode) { current = catchList; } else if (c == finallyNode) { current = finallyList; } if (c.getType() == Token.GOTO && // ((Node.Jump)c).target == lastChildNode && (c.getNext() == catchNode || c.getNext() == finallyNode)) { continue; } current.add(c); } CAstNode finallyBlock = null; if (finallyNode != null) { int i = 0; CAstNode[] finallyAsts = new CAstNode[finallyList.size()]; for (Iterator<Node> fns = finallyList.iterator(); fns.hasNext();) { finallyAsts[i++] = walkNodes(fns.next(), context); } finallyBlock = Ast.makeNode(CAstNode.BLOCK_STMT, finallyAsts); } if (catchNode != null) { int i = 0; WalkContext catchChild = new CatchBlockContext(context); CAstNode[] catchAsts = new CAstNode[catchList.size()]; for (Iterator<Node> cns = catchList.iterator(); cns.hasNext();) { catchAsts[i++] = walkNodes(cns.next(), catchChild); } CAstNode catchBlock = Ast.makeNode(CAstNode.CATCH, Ast.makeConstant(catchChild.getCatchVar()), Ast.makeNode(CAstNode.BLOCK_STMT, catchAsts)); context.cfg().map(catchBlock, catchBlock); i = 0; WalkContext tryChild = new TryBlockContext(context, catchBlock); CAstNode[] tryAsts = new CAstNode[tryList.size()]; for (Iterator<Node> tns = tryList.iterator(); tns.hasNext();) { tryAsts[i++] = walkNodes(tns.next(), tryChild); } CAstNode tryBlock = Ast.makeNode(CAstNode.BLOCK_STMT, tryAsts); if (finallyBlock != null) { return Ast.makeNode(CAstNode.BLOCK_STMT, Ast.makeNode(CAstNode.UNWIND, Ast.makeNode(CAstNode.TRY, tryBlock, catchBlock), finallyBlock), walkNodes(c, context)); } else { return Ast.makeNode(CAstNode.BLOCK_STMT, Ast.makeNode(CAstNode.TRY, tryBlock, catchBlock), walkNodes(c, context)); } } else { int i = 0; CAstNode[] tryAsts = new CAstNode[tryList.size()]; for (Iterator<Node> tns = tryList.iterator(); tns.hasNext();) { tryAsts[i++] = walkNodes(tns.next(), context); } CAstNode tryBlock = Ast.makeNode(CAstNode.BLOCK_STMT, tryAsts); return Ast.makeNode( CAstNode.BLOCK_STMT, Ast.makeNode(CAstNode.UNWIND, Ast.makeNode(CAstNode.BLOCK_STMT, tryBlock), Ast.makeNode(CAstNode.BLOCK_STMT, finallyBlock)), walkNodes(c, context)); } } case Token.JSR: { return Ast.makeNode(CAstNode.EMPTY); /* * Node jsrTarget = ((Node.Jump)n).target; Node finallyNode = * jsrTarget.getNext(); return walkNodes(finallyNode, context); */ } case Token.COMMA: { int count = countSiblingsStartingFrom(n.getFirstChild()); CAstNode[] cs = new CAstNode[count]; int i = 0; for (Node c = n.getFirstChild(); c != null; i++, c = c.getNext()) { if (c.getNext() == null) { // for the final sub-expression of the comma, if we care about the // base pointer // of n, we care about the base pointer of c context.updateBase(n, c); } cs[i] = walkNodes(c, context); } return Ast.makeNode(CAstNode.BLOCK_EXPR, cs); } /* * case Token.ENTERWITH: { return * Ast.makeNode(JavaScriptCAstNode.ENTER_WITH, * walkNodes(n.getFirstChild(), context)); } * * case Token.LEAVEWITH: { return * Ast.makeNode(JavaScriptCAstNode.EXIT_WITH, Ast.makeConstant(null)); } */ case Token.ENTERWITH: case Token.LEAVEWITH: { return Ast.makeNode(CAstNode.EMPTY); } case Token.LOOP: { LoopContext child = new LoopContext(context); CAstNode[] nodes = gatherChildren(n, child); if (child.forInInitExpr != null) { String nm = child.forInVar; return Ast.makeNode(CAstNode.BLOCK_STMT, Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(nm, true)), walkNodes(child.forInInitExpr, context)), nodes); } else { return Ast.makeNode(CAstNode.BLOCK_STMT, nodes); } } case Token.WITH: case Token.FINALLY: case Token.BLOCK: case Token.LABEL: { Node c1 = n.getFirstChild(); if (c1 != null && c1.getType() == Token.SWITCH) { Node switchValue = c1.getFirstChild(); CAstNode defaultLabel = Ast.makeNode(CAstNode.LABEL_STMT, Ast.makeNode(CAstNode.EMPTY)); context.cfg().map(defaultLabel, defaultLabel); List<CAstNode> labelCasts = new ArrayList<CAstNode>(); for (Node kase = switchValue.getNext(); kase != null; kase = kase.getNext()) { assert kase.getType() == Token.CASE; Node caseLbl = kase.getFirstChild(); Node target = ((Node.Jump) kase).target; CAstNode labelCast = walkNodes(caseLbl, context); labelCasts.add(labelCast); context.cfg().add(c1, target, labelCast); } CAstNode[] children = new CAstNode[labelCasts.size() + 1]; int i = 0; children[i++] = Ast.makeNode(CAstNode.BLOCK_STMT, defaultLabel, gatherChildren(n, context, 1)); // Note that we are placing the labels as children in the AST // even if they are not used, because we want them copied when AST is // re-written. for (CAstNode labelCast : labelCasts) { children[i++] = labelCast; } context.cfg().add(c1, defaultLabel, CAstControlFlowMap.SWITCH_DEFAULT); CAstNode switchAst = Ast.makeNode(CAstNode.SWITCH, walkNodes(switchValue, context), children); noteSourcePosition(context, switchAst, c1); context.cfg().map(c1, switchAst); return switchAst; } else { return Ast.makeNode(CAstNode.BLOCK_STMT, gatherChildren(n, context)); } } case Token.EXPR_VOID: case Token.EXPR_RESULT: { WalkContext child = new ExpressionContext(context); Node expr = n.getFirstChild(); if (NT == Token.EXPR_RESULT) { // EXPR_RESULT node is just a wrapper, so if we care about base pointer // of n, we // care about child of n child.updateBase(n, expr); } return walkNodes(expr, child); } case Token.POS: { return Ast.makeNode(CAstNode.UNARY_EXPR, translateOpcode(Token.ADD), walkNodes(n.getFirstChild(), context)); } case Token.CALL: { if (!isPrimitiveCall(context, n)) { CAstNode base = makeVarRef("$$ base"); Node callee = n.getFirstChild(); WalkContext child = new BaseCollectingContext(context, callee, "$$ base"); CAstNode fun = walkNodes(callee, child); // the first actual parameter appearing within the parentheses of the // call (i.e., possibly excluding the 'this' parameter) Node firstParamInParens = callee.getNext(); if (child.foundBase(callee)) return Ast.makeNode( CAstNode.LOCAL_SCOPE, Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl("$$ base")), Ast.makeConstant(null)), makeCall(fun, base, firstParamInParens, context))); else { // pass the global object as the receiver argument return makeCall(fun, makeVarRef(JSSSAPropagationCallGraphBuilder.GLOBAL_OBJ_VAR_NAME), firstParamInParens, context); } } else { return Ast.makeNode(CAstNode.PRIMITIVE, gatherChildren(n, context, 1)); } } case Token.BINDNAME: case Token.NAME: { return readName(context, n.getString()); } case Token.THIS: { return makeVarRef("this"); } case Token.THISFN: { return makeVarRef(((FunctionNode) context.top()).getFunctionName()); } case Token.STRING: { return Ast.makeConstant(n.getString()); } case Token.NUMBER: { return Ast.makeConstant(n.getDouble()); } case Token.FALSE: { return Ast.makeConstant(false); } case Token.TRUE: { return Ast.makeConstant(true); } case Token.NULL: case Token.VOID: { return Ast.makeConstant(null); } case Token.ADD: case Token.DIV: case Token.LSH: case Token.MOD: case Token.MUL: case Token.RSH: case Token.SUB: case Token.URSH: case Token.BITAND: case Token.BITOR: case Token.BITXOR: case Token.EQ: case Token.SHEQ: case Token.GE: case Token.GT: case Token.LE: case Token.LT: case Token.SHNE: case Token.NE: { Node l = n.getFirstChild(); Node r = l.getNext(); return Ast.makeNode(CAstNode.BINARY_EXPR, translateOpcode(NT), walkNodes(l, context), walkNodes(r, context)); } case Token.NEG: { return Ast.makeNode(CAstNode.UNARY_EXPR, translateOpcode(Token.SUB), walkNodes(n.getFirstChild(), context)); } case Token.BITNOT: case Token.NOT: { return Ast.makeNode(CAstNode.UNARY_EXPR, translateOpcode(NT), walkNodes(n.getFirstChild(), context)); } case Token.VAR: case Token.CONST: { List<CAstNode> result = new ArrayList<CAstNode>(); Node nm = n.getFirstChild(); while (nm != null) { context.addNameDecl(Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(nm.getString())), readName(context, "$$undefined"))); if (nm.getFirstChild() != null) { WalkContext child = new ExpressionContext(context); result.add(Ast.makeNode(CAstNode.ASSIGN, makeVarRef(nm.getString()), walkNodes(nm.getFirstChild(), child))); } nm = nm.getNext(); } if (result.size() > 0) { return Ast.makeNode(CAstNode.BLOCK_EXPR, result.toArray(new CAstNode[result.size()])); } else { return Ast.makeNode(CAstNode.EMPTY); } } case Token.REGEXP: { int regexIdx = n.getIntProp(Node.REGEXP_PROP, -1); assert regexIdx != -1 : "while converting: " + context.top().toStringTree(context.top()) + "\nlooking at bad regex:\n " + n.toStringTree(context.top()); String flags = context.top().getRegexpFlags(regexIdx); Node flagsNode = Node.newString(flags); String str = context.top().getRegexpString(regexIdx); Node strNode = Node.newString(str); strNode.addChildToFront(flagsNode); return handleNew(context, "RegExp", strNode); } case Token.ENUM_INIT_KEYS: { context.createForInVar(n.getFirstChild()); return Ast.makeNode(CAstNode.EMPTY); } case Token.ENUM_ID: { return Ast.makeNode(CAstNode.EACH_ELEMENT_GET, makeVarRef(context.getForInInitVar())); } case Token.ENUM_NEXT: { return Ast.makeNode(CAstNode.EACH_ELEMENT_HAS_NEXT, makeVarRef(context.getForInInitVar())); } case Token.RETURN: { Node val = n.getFirstChild(); if (val != null) { WalkContext child = new ExpressionContext(context); return Ast.makeNode(CAstNode.RETURN, walkNodes(val, child)); } else { return Ast.makeNode(CAstNode.RETURN); } } case Token.SETNAME: { Node nm = n.getFirstChild(); return Ast.makeNode(CAstNode.ASSIGN, walkNodes(nm, context), walkNodes(nm.getNext(), context)); } case Token.IFNE: case Token.IFEQ: { context.cfg().add(n, ((Node.Jump) n).target, Boolean.TRUE); WalkContext child = new ExpressionContext(context); CAstNode gotoAst = Ast.makeNode(CAstNode.IFGOTO, translateOpcode(NT), walkNodes(n.getFirstChild(), child), Ast.makeConstant(1)); context.cfg().map(n, gotoAst); return gotoAst; } case Token.GOTO: { context.cfg().add(n, ((Node.Jump) n).target, null); CAstNode gotoAst = Ast.makeNode(CAstNode.GOTO, Ast.makeConstant(((Node.Jump) n).target.labelId())); context.cfg().map(n, gotoAst); return gotoAst; } case Token.BREAK: { context.cfg().add(n, ((Node.Jump) n).getJumpStatement().target, null); CAstNode gotoAst = Ast.makeNode(CAstNode.GOTO, Ast.makeConstant(((Node.Jump) n).getJumpStatement().target.labelId())); context.cfg().map(n, gotoAst); return gotoAst; } case Token.CONTINUE: { context.cfg().add(n, ((Node.Jump) n).getJumpStatement().getContinue(), null); CAstNode gotoAst = Ast.makeNode(CAstNode.GOTO, Ast.makeConstant(((Node.Jump) n).getJumpStatement().getContinue().labelId())); context.cfg().map(n, gotoAst); return gotoAst; } case Token.TARGET: { CAstNode result = Ast.makeNode(CAstNode.LABEL_STMT, Ast.makeConstant(n.labelId()), Ast.makeNode(CAstNode.EMPTY)); context.cfg().map(n, result); return result; } case Token.OR: { Node l = n.getFirstChild(); Node r = l.getNext(); CAstNode lhs = walkNodes(l, context); String lhsTempName = "or___lhs"; // { lhsTemp := <lhs>; if(lhsTemp) { lhsTemp } else { <rhs> } return Ast.makeNode( CAstNode.LOCAL_SCOPE, Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(lhsTempName)), lhs), Ast.makeNode(CAstNode.IF_EXPR, makeVarRef(lhsTempName), makeVarRef(lhsTempName), walkNodes(r, context)))); } case Token.AND: { Node l = n.getFirstChild(); Node r = l.getNext(); CAstNode lhs = walkNodes(l, context); String lhsTempName = "and___lhs"; // { lhsTemp := <lhs>; if(lhsTemp) { <rhs> } else { lhsTemp } return Ast.makeNode( CAstNode.LOCAL_SCOPE, Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(lhsTempName)), lhs), Ast.makeNode(CAstNode.IF_EXPR, makeVarRef(lhsTempName), walkNodes(r, context), makeVarRef(lhsTempName)))); } case Token.HOOK: { Node cond = n.getFirstChild(); Node thenBranch = cond.getNext(); Node elseBranch = thenBranch.getNext(); return Ast.makeNode(CAstNode.IF_EXPR, walkNodes(cond, context), walkNodes(thenBranch, context), walkNodes(elseBranch, context)); } case Token.INC: case Token.DEC: { int flags = n.getIntProp(Node.INCRDECR_PROP, -1); CAstNode op = ((flags & Node.DECR_FLAG) != 0) ? CAstOperator.OP_SUB : CAstOperator.OP_ADD; Node l = n.getFirstChild(); CAstNode last = walkNodes(l, context); return Ast.makeNode((((flags & Node.POST_FLAG) != 0) ? CAstNode.ASSIGN_POST_OP : CAstNode.ASSIGN_PRE_OP), last, Ast.makeConstant(1), op); } case Token.NEW: { if (isPrimitiveCreation(context, n)) { return makeBuiltinNew(n.getFirstChild().getString()); } else { Node receiver = n.getFirstChild(); return handleNew(context, walkNodes(receiver, context), receiver.getNext()); } } case Token.ARRAYLIT: { int count = 0; for (Node x = n.getFirstChild(); x != null; count++, x = x.getNext()) ; int i = 0; CAstNode[] args = new CAstNode[2 * count + 1]; args[i++] = (isPrologueScript(context)) ? makeBuiltinNew("Array") : handleNew(context, "Array", null); int[] skips = (int[]) n.getProp(Node.SKIP_INDEXES_PROP); int skip = 0; int idx = 0; Node elt = n.getFirstChild(); while (elt != null) { if (skips != null && skip < skips.length && skips[skip] == idx) { skip++; idx++; continue; } args[i++] = Ast.makeConstant(idx++); args[i++] = walkNodes(elt, context); elt = elt.getNext(); } return Ast.makeNode(CAstNode.OBJECT_LITERAL, args); } case Token.OBJECTLIT: { Object[] propertyList = (Object[]) n.getProp(Node.OBJECT_IDS_PROP); CAstNode[] args = new CAstNode[propertyList.length * 2 + 1]; int i = 0; args[i++] = ((isPrologueScript(context)) ? makeBuiltinNew("Object") : handleNew(context, "Object", null)); Node val = n.getFirstChild(); int nameIdx = 0; for (; nameIdx < propertyList.length; nameIdx++, val = val.getNext()) { args[i++] = Ast.makeConstant(propertyList[nameIdx]); args[i++] = walkNodes(val, context); } return Ast.makeNode(CAstNode.OBJECT_LITERAL, args); } case Token.GETPROP: case Token.GETELEM: { Node receiver = n.getFirstChild(); Node element = receiver.getNext(); CAstNode rcvr = walkNodes(receiver, context); String baseVarName = context.getBaseVarNameIfRelevant(n); CAstNode elt = walkNodes(element, context); CAstNode get, result; if (baseVarName != null) { result = Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.ASSIGN, makeVarRef(baseVarName), rcvr), get = Ast.makeNode(CAstNode.OBJECT_REF, makeVarRef(baseVarName), elt)); } else { result = get = Ast.makeNode(CAstNode.OBJECT_REF, rcvr, elt); } if (context.getCatchTarget() != null) { context.cfg().map(get, get); context.cfg().add(get, context.getCatchTarget(), JavaScriptTypes.TypeError); } return result; } case Token.GET_REF: { // read of __proto__ // first and only child c1 is of type Token.REF_SPECIAL whose NAME_PROP property should be "__proto__". // c1 has a single child, the base pointer for the reference Node child1 = n.getFirstChild(); assert child1.getType() == Token.REF_SPECIAL; assert child1.getProp(Node.NAME_PROP).equals("__proto__"); Node receiver = child1.getFirstChild(); assert child1.getNext() == null; CAstNode rcvr = walkNodes(receiver, context); final CAstNode result = Ast.makeNode(CAstNode.OBJECT_REF, rcvr, Ast.makeConstant("__proto__")); if (context.getCatchTarget() != null) { context.cfg().map(result, result); context.cfg().add(result, context.getCatchTarget(), JavaScriptTypes.TypeError); } return result; } case Token.SETPROP: case Token.SETELEM: { Node receiver = n.getFirstChild(); Node elt = receiver.getNext(); Node val = elt.getNext(); CAstNode rcvr = walkNodes(receiver, context); return Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, walkNodes(elt, context)), walkNodes(val, context)); } case Token.SET_REF: { // first child c1 is of type Token.REF_SPECIAL whose NAME_PROP property should be "__proto__". // c1 has a single child, the base pointer for the reference // second child c2 is RHS of assignment Node child1 = n.getFirstChild(); assert child1.getType() == Token.REF_SPECIAL; assert child1.getProp(Node.NAME_PROP).equals("__proto__"); Node receiver = child1.getFirstChild(); Node val = child1.getNext(); CAstNode rcvr = walkNodes(receiver, context); return Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, Ast.makeConstant("__proto__")), walkNodes(val, context)); } case Token.DELPROP: { Node receiver = n.getFirstChild(); Node element = receiver.getNext(); CAstNode rcvr = walkNodes(receiver, context); String baseVarName = context.getBaseVarNameIfRelevant(n); CAstNode elt = walkNodes(element, context); if (baseVarName != null) { return Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.ASSIGN, makeVarRef(baseVarName), rcvr), Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, makeVarRef(baseVarName), elt), Ast.makeConstant(null))); } else { return Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, elt), Ast.makeConstant(null)); } } case Token.TYPEOFNAME: { return Ast.makeNode(CAstNode.TYPE_OF, makeVarRef(n.getString())); } case Token.TYPEOF: { return Ast.makeNode(CAstNode.TYPE_OF, walkNodes(n.getFirstChild(), context)); } case Token.SETPROP_OP: case Token.SETELEM_OP: { Node receiver = n.getFirstChild(); Node elt = receiver.getNext(); Node op = elt.getNext(); CAstNode rcvr = walkNodes(receiver, context); return Ast.makeNode(CAstNode.ASSIGN_POST_OP, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, walkNodes(elt, context)), walkNodes(op.getFirstChild().getNext(), context), translateOpcode(op.getType())); } case Token.THROW: { CAstNode catchNode = context.getCatchTarget(); if (catchNode != null) context.cfg().add(n, context.getCatchTarget(), null); else context.cfg().add(n, CAstControlFlowMap.EXCEPTION_TO_EXIT, null); CAstNode throwAst = Ast.makeNode(CAstNode.THROW, walkNodes(n.getFirstChild(), context)); context.cfg().map(n, throwAst); return throwAst; } case Token.EMPTY: { return Ast.makeConstant(null); } case Token.INSTANCEOF: { Node value = n.getFirstChild(); Node type = value.getNext(); return Ast.makeNode(CAstNode.INSTANCEOF, walkNodes(value, context), walkNodes(type, context)); } case Token.IN: { Node value = n.getFirstChild(); Node property = value.getNext(); return Ast.makeNode(CAstNode.IS_DEFINED_EXPR, walkNodes(property, context), walkNodes(value, context)); } default: { System.err.println("while converting: " + context.top().toStringTree(context.top()) + "\nlooking at unhandled:\n " + n.toStringTree(context.top()) + "\n(of type " + NT + ") (of class " + n.getClass() + ")" + " at " + n.getLineno()); Assertions.UNREACHABLE(); return null; } } }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/actions/NewLocalTaskAction.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/actions/NewLocalTaskAction.java index 84cf24419..8c5f4b147 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/actions/NewLocalTaskAction.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/actions/NewLocalTaskAction.java @@ -1,132 +1,132 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 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.internal.tasklist.ui.actions; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.mylar.internal.tasklist.TaskListPreferenceConstants; import org.eclipse.mylar.internal.tasklist.ui.TaskListImages; import org.eclipse.mylar.internal.tasklist.ui.TaskListUiUtil; import org.eclipse.mylar.internal.tasklist.ui.views.TaskInputDialog; import org.eclipse.mylar.internal.tasklist.ui.views.TaskListView; import org.eclipse.mylar.provisional.core.MylarPlugin; import org.eclipse.mylar.provisional.tasklist.ITask; import org.eclipse.mylar.provisional.tasklist.MylarTaskListPlugin; import org.eclipse.mylar.provisional.tasklist.Task; import org.eclipse.mylar.provisional.tasklist.TaskCategory; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.widgets.Display; /** * @author Mik Kersten */ public class NewLocalTaskAction extends Action { private static final String NEW_TASK_DESCRIPTION = "New task"; public static final String ID = "org.eclipse.mylar.tasklist.actions.create.task"; private final TaskListView view; public NewLocalTaskAction(TaskListView view) { this.view = view; setText(TaskInputDialog.LABEL_SHELL); setToolTipText(TaskInputDialog.LABEL_SHELL); setId(ID); setImageDescriptor(TaskListImages.TASK_NEW); } /** * Returns the default URL text for the task by first checking the contents * of the clipboard and then using the default prefix preference if that * fails */ protected String getDefaultIssueURL() { String clipboardText = getClipboardText(); if ((clipboardText.startsWith("http://") || clipboardText.startsWith("https://") && clipboardText.length() > 10)) { return clipboardText; } String defaultPrefix = MylarPlugin.getDefault().getPreferenceStore().getString( TaskListPreferenceConstants.DEFAULT_URL_PREFIX); if (!defaultPrefix.equals("")) { return defaultPrefix; } return ""; } /** * Returns the contents of the clipboard or "" if no text content was * available */ protected String getClipboardText() { Clipboard clipboard = new Clipboard(Display.getDefault()); TextTransfer transfer = TextTransfer.getInstance(); String contents = (String) clipboard.getContents(transfer); if (contents != null) { return contents; } else { return ""; } } @Override public void run() { // TaskInputDialog dialog = new // TaskInputDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()); // int dialogResult = dialog.open(); // if (dialogResult == Window.OK) { Task newTask = new Task(MylarTaskListPlugin.getTaskListManager().genUniqueTaskHandle(), NEW_TASK_DESCRIPTION, true); // Task newTask = new // Task(MylarTaskListPlugin.getTaskListManager().genUniqueTaskHandle(), // dialog // .getTaskname(), true); // MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask); // newTask.setPriority(dialog.getSelectedPriority()); // newTask.setReminderDate(dialog.getReminderDate()); newTask.setUrl(getDefaultIssueURL()); Object selectedObject = ((IStructuredSelection) view.getViewer().getSelection()).getFirstElement(); if (selectedObject instanceof TaskCategory) { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, (TaskCategory) selectedObject); } else if (selectedObject instanceof ITask) { ITask task = (ITask) selectedObject; - if (task.getContainer() != null) { + if (task.getContainer() instanceof TaskCategory) { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, (TaskCategory) task.getContainer()); - } else if (view.getDrilledIntoCategory() != null) { + } else if (view.getDrilledIntoCategory() instanceof TaskCategory) { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, (TaskCategory) view.getDrilledIntoCategory()); } else { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, MylarTaskListPlugin.getTaskListManager().getTaskList().getRootCategory()); // MylarTaskListPlugin.getTaskListManager().getTaskList().moveToRoot(newTask); } } else if (view.getDrilledIntoCategory() != null) { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, (TaskCategory) view.getDrilledIntoCategory()); } else { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, MylarTaskListPlugin.getTaskListManager().getTaskList().getRootCategory()); } TaskListUiUtil.openEditor(newTask); // newTask.openTaskInEditor(false); view.getViewer().refresh(); view.getViewer().setSelection(new StructuredSelection(newTask)); // } } }
false
true
public void run() { // TaskInputDialog dialog = new // TaskInputDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()); // int dialogResult = dialog.open(); // if (dialogResult == Window.OK) { Task newTask = new Task(MylarTaskListPlugin.getTaskListManager().genUniqueTaskHandle(), NEW_TASK_DESCRIPTION, true); // Task newTask = new // Task(MylarTaskListPlugin.getTaskListManager().genUniqueTaskHandle(), // dialog // .getTaskname(), true); // MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask); // newTask.setPriority(dialog.getSelectedPriority()); // newTask.setReminderDate(dialog.getReminderDate()); newTask.setUrl(getDefaultIssueURL()); Object selectedObject = ((IStructuredSelection) view.getViewer().getSelection()).getFirstElement(); if (selectedObject instanceof TaskCategory) { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, (TaskCategory) selectedObject); } else if (selectedObject instanceof ITask) { ITask task = (ITask) selectedObject; if (task.getContainer() != null) { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, (TaskCategory) task.getContainer()); } else if (view.getDrilledIntoCategory() != null) { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, (TaskCategory) view.getDrilledIntoCategory()); } else { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, MylarTaskListPlugin.getTaskListManager().getTaskList().getRootCategory()); // MylarTaskListPlugin.getTaskListManager().getTaskList().moveToRoot(newTask); } } else if (view.getDrilledIntoCategory() != null) { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, (TaskCategory) view.getDrilledIntoCategory()); } else { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, MylarTaskListPlugin.getTaskListManager().getTaskList().getRootCategory()); } TaskListUiUtil.openEditor(newTask); // newTask.openTaskInEditor(false); view.getViewer().refresh(); view.getViewer().setSelection(new StructuredSelection(newTask)); // } }
public void run() { // TaskInputDialog dialog = new // TaskInputDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()); // int dialogResult = dialog.open(); // if (dialogResult == Window.OK) { Task newTask = new Task(MylarTaskListPlugin.getTaskListManager().genUniqueTaskHandle(), NEW_TASK_DESCRIPTION, true); // Task newTask = new // Task(MylarTaskListPlugin.getTaskListManager().genUniqueTaskHandle(), // dialog // .getTaskname(), true); // MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask); // newTask.setPriority(dialog.getSelectedPriority()); // newTask.setReminderDate(dialog.getReminderDate()); newTask.setUrl(getDefaultIssueURL()); Object selectedObject = ((IStructuredSelection) view.getViewer().getSelection()).getFirstElement(); if (selectedObject instanceof TaskCategory) { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, (TaskCategory) selectedObject); } else if (selectedObject instanceof ITask) { ITask task = (ITask) selectedObject; if (task.getContainer() instanceof TaskCategory) { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, (TaskCategory) task.getContainer()); } else if (view.getDrilledIntoCategory() instanceof TaskCategory) { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, (TaskCategory) view.getDrilledIntoCategory()); } else { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, MylarTaskListPlugin.getTaskListManager().getTaskList().getRootCategory()); // MylarTaskListPlugin.getTaskListManager().getTaskList().moveToRoot(newTask); } } else if (view.getDrilledIntoCategory() != null) { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, (TaskCategory) view.getDrilledIntoCategory()); } else { MylarTaskListPlugin.getTaskListManager().getTaskList().addTask(newTask, MylarTaskListPlugin.getTaskListManager().getTaskList().getRootCategory()); } TaskListUiUtil.openEditor(newTask); // newTask.openTaskInEditor(false); view.getViewer().refresh(); view.getViewer().setSelection(new StructuredSelection(newTask)); // } }
diff --git a/ghana-national-web/src/main/java/org/motechproject/ghana/national/web/helper/FacilityHelper.java b/ghana-national-web/src/main/java/org/motechproject/ghana/national/web/helper/FacilityHelper.java index decf2196..1669da8b 100644 --- a/ghana-national-web/src/main/java/org/motechproject/ghana/national/web/helper/FacilityHelper.java +++ b/ghana-national-web/src/main/java/org/motechproject/ghana/national/web/helper/FacilityHelper.java @@ -1,109 +1,109 @@ package org.motechproject.ghana.national.web.helper; import ch.lambdaj.group.Group; import org.apache.commons.lang.StringUtils; import org.motechproject.ghana.national.domain.Constants; import org.motechproject.ghana.national.domain.Facility; import org.motechproject.ghana.national.service.FacilityService; import org.motechproject.ghana.national.vo.FacilityVO; import org.motechproject.ghana.national.web.FacilityController; import org.motechproject.ghana.national.web.form.FacilityForm; import org.motechproject.mrs.model.MRSFacility; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static ch.lambdaj.Lambda.*; import static ch.lambdaj.group.Groups.by; import static ch.lambdaj.group.Groups.group; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.core.Is.is; import static org.motechproject.ghana.national.tools.Utility.mapConverter; import static org.motechproject.ghana.national.tools.Utility.reverseKeyValues; @Component public class FacilityHelper { @Autowired FacilityService facilityService; public Map<String, Object> locationMap() { List<Facility> facilities = facilityService.facilities(); final HashMap<String, Object> modelMap = new HashMap<String, Object>(); List<Facility> withValidCountryNames = select(facilities, having(on(Facility.class).country(), is(not(equalTo(StringUtils.EMPTY))))); final Group<Facility> byCountryRegion = group(withValidCountryNames, by(on(Facility.class).country()), by(on(Facility.class).region())); final Group<Facility> byRegionDistrict = group(withValidCountryNames, by(on(Facility.class).region()), by(on(Facility.class).district())); final Group<Facility> byDistrictProvince = group(withValidCountryNames, by(on(Facility.class).district()), by(on(Facility.class).province())); modelMap.put(Constants.COUNTRIES, extract(selectDistinct(withValidCountryNames, "country"), on(Facility.class).country())); modelMap.put(Constants.REGIONS, reverseKeyValues(map(byCountryRegion.keySet(), mapConverter(byCountryRegion)))); modelMap.put(Constants.DISTRICTS, reverseKeyValues(map(byRegionDistrict.keySet(), mapConverter(byRegionDistrict)))); modelMap.put(Constants.PROVINCES, reverseKeyValues(map(byDistrictProvince.keySet(), mapConverter(byDistrictProvince)))); modelMap.put(Constants.FACILITIES, facilityVOs(facilities)); return modelMap; } private List<FacilityVO> facilityVOs(List<Facility> facilities) { List<FacilityVO> facilityVOs = new ArrayList<FacilityVO>(); for (Facility facility : facilities) { - if (facility.province() != null) { + if (StringUtils.isNotBlank(facility.province())) { facilityVOs.add(new FacilityVO(facility.mrsFacility().getId(), facility.name(), facility.province())); continue; } - if (facility.district() != null) { + if (StringUtils.isNotBlank(facility.district())) { facilityVOs.add(new FacilityVO(facility.mrsFacility().getId(), facility.name(), facility.district())); continue; } - if (facility.region() != null) { + if (StringUtils.isNotBlank(facility.region())) { facilityVOs.add(new FacilityVO(facility.mrsFacility().getId(), facility.name(), facility.region())); } } return facilityVOs; } public FacilityForm copyFacilityValuesToForm(Facility facility) { FacilityForm facilityForm = new FacilityForm(); facilityForm.setAdditionalPhoneNumber1(facility.additionalPhoneNumber1()); facilityForm.setAdditionalPhoneNumber2(facility.additionalPhoneNumber2()); facilityForm.setAdditionalPhoneNumber3(facility.additionalPhoneNumber3()); facilityForm.setPhoneNumber(facility.phoneNumber()); facilityForm.setCountry(facility.country()); facilityForm.setCountyDistrict(facility.district()); facilityForm.setName(facility.name()); facilityForm.setRegion(facility.region()); facilityForm.setStateProvince(facility.province()); facilityForm.setId(facility.mrsFacilityId()); facilityForm.setFacilityId(facility.motechId()); return facilityForm; } public void handleExistingFacilityError(BindingResult bindingResult, ModelMap modelMap, String message, String formName) { bindingResult.addError(new FieldError(formName, "name", message)); modelMap.mergeAttributes(bindingResult.getModel()); } public String getFacilityForId(ModelMap modelMap, Facility facility) { modelMap.addAttribute(FacilityController.FACILITY_FORM, copyFacilityValuesToForm(facility)); modelMap.addAttribute("message", "facility created successfully."); modelMap.mergeAttributes(locationMap()); return FacilityController.EDIT_FACILITY_VIEW; } public Facility createFacilityVO(FacilityForm updateFacilityForm) { MRSFacility mrsFacility = new MRSFacility(updateFacilityForm.getId(), updateFacilityForm.getName(), updateFacilityForm.getCountry(), updateFacilityForm.getRegion(), updateFacilityForm.getCountyDistrict(), updateFacilityForm.getStateProvince()); Facility facility = new Facility().mrsFacility(mrsFacility).mrsFacilityId(updateFacilityForm.getId()).motechId(updateFacilityForm.getFacilityId()).phoneNumber(updateFacilityForm.getPhoneNumber()). additionalPhoneNumber1(updateFacilityForm.getAdditionalPhoneNumber1()).additionalPhoneNumber2(updateFacilityForm.getAdditionalPhoneNumber2()).additionalPhoneNumber3(updateFacilityForm.getAdditionalPhoneNumber3()); return facility; } }
false
true
private List<FacilityVO> facilityVOs(List<Facility> facilities) { List<FacilityVO> facilityVOs = new ArrayList<FacilityVO>(); for (Facility facility : facilities) { if (facility.province() != null) { facilityVOs.add(new FacilityVO(facility.mrsFacility().getId(), facility.name(), facility.province())); continue; } if (facility.district() != null) { facilityVOs.add(new FacilityVO(facility.mrsFacility().getId(), facility.name(), facility.district())); continue; } if (facility.region() != null) { facilityVOs.add(new FacilityVO(facility.mrsFacility().getId(), facility.name(), facility.region())); } } return facilityVOs; }
private List<FacilityVO> facilityVOs(List<Facility> facilities) { List<FacilityVO> facilityVOs = new ArrayList<FacilityVO>(); for (Facility facility : facilities) { if (StringUtils.isNotBlank(facility.province())) { facilityVOs.add(new FacilityVO(facility.mrsFacility().getId(), facility.name(), facility.province())); continue; } if (StringUtils.isNotBlank(facility.district())) { facilityVOs.add(new FacilityVO(facility.mrsFacility().getId(), facility.name(), facility.district())); continue; } if (StringUtils.isNotBlank(facility.region())) { facilityVOs.add(new FacilityVO(facility.mrsFacility().getId(), facility.name(), facility.region())); } } return facilityVOs; }
diff --git a/robocodeextract/robots/sample/Tracker.java b/robocodeextract/robots/sample/Tracker.java index e85debe9d..5b23b733b 100644 --- a/robocodeextract/robots/sample/Tracker.java +++ b/robocodeextract/robots/sample/Tracker.java @@ -1,147 +1,147 @@ /******************************************************************************* * Copyright (c) 2001, 2008 Mathew A. Nelson and Robocode contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://robocode.sourceforge.net/license/cpl-v10.html * * Contributors: * Mathew A. Nelson * - Initial implementation * Flemming N. Larsen * - Maintainance *******************************************************************************/ package sample; import robocode.HitRobotEvent; import robocode.Robot; import robocode.ScannedRobotEvent; import robocode.WinEvent; import static robocode.util.Utils.normalRelativeAngleDegrees; import java.awt.*; /** * Tracker - a sample robot by Mathew Nelson, and maintained by Flemming N. Larsen * <p/> * Locks onto a robot, moves close, fires when close. */ public class Tracker extends Robot { int count = 0; // Keeps track of how long we've // been searching for our target double gunTurnAmt; // How much to turn our gun when searching String trackName; // Name of the robot we're currently tracking /** * run: Tracker's main run function */ public void run() { // Set colors setBodyColor(new Color(128, 128, 50)); setGunColor(new Color(50, 50, 20)); setRadarColor(new Color(200, 200, 70)); setScanColor(Color.white); setBulletColor(Color.blue); // Prepare gun trackName = null; // Initialize to not tracking anyone setAdjustGunForRobotTurn(true); // Keep the gun still when we turn gunTurnAmt = 10; // Initialize gunTurn to 10 // Loop forever while (true) { // turn the Gun (looks for enemy) turnGunRight(gunTurnAmt); // Keep track of how long we've been looking count++; // If we've haven't seen our target for 2 turns, look left if (count > 2) { gunTurnAmt = -10; } // If we still haven't seen our target for 5 turns, look right if (count > 5) { gunTurnAmt = 10; } // If we *still* haven't seen our target after 10 turns, find another target if (count > 11) { trackName = null; } } } /** * onScannedRobot: Here's the good stuff */ public void onScannedRobot(ScannedRobotEvent e) { // If we have a target, and this isn't it, return immediately // so we can get more ScannedRobotEvents. if (trackName != null && !e.getName().equals(trackName)) { return; } // If we don't have a target, well, now we do! if (trackName == null) { trackName = e.getName(); out.println("Tracking " + trackName); } // This is our target. Reset count (see the run method) count = 0; - // If our target is too far away, turn and move torward it. + // If our target is too far away, turn and move toward it. if (e.getDistance() > 150) { gunTurnAmt = normalRelativeAngleDegrees(e.getBearing() + (getHeading() - getRadarHeading())); turnGunRight(gunTurnAmt); // Try changing these to setTurnGunRight, turnRight(e.getBearing()); // and see how much Tracker improves... // (you'll have to make Tracker an AdvancedRobot) ahead(e.getDistance() - 140); return; } // Our target is close. gunTurnAmt = normalRelativeAngleDegrees(e.getBearing() + (getHeading() - getRadarHeading())); turnGunRight(gunTurnAmt); fire(3); // Our target is too close! Back up. if (e.getDistance() < 100) { if (e.getBearing() > -90 && e.getBearing() <= 90) { back(40); } else { ahead(40); } } scan(); } /** * onHitRobot: Set him as our new target */ public void onHitRobot(HitRobotEvent e) { // Only print if he's not already our target. if (trackName != null && !trackName.equals(e.getName())) { out.println("Tracking " + e.getName() + " due to collision"); } // Set the target trackName = e.getName(); // Back up a bit. // Note: We won't get scan events while we're doing this! // An AdvancedRobot might use setBack(); execute(); gunTurnAmt = normalRelativeAngleDegrees(e.getBearing() + (getHeading() - getRadarHeading())); turnGunRight(gunTurnAmt); fire(3); back(50); } /** * onWin: Do a victory dance */ public void onWin(WinEvent e) { for (int i = 0; i < 50; i++) { turnRight(30); turnLeft(30); } } }
true
true
public void onScannedRobot(ScannedRobotEvent e) { // If we have a target, and this isn't it, return immediately // so we can get more ScannedRobotEvents. if (trackName != null && !e.getName().equals(trackName)) { return; } // If we don't have a target, well, now we do! if (trackName == null) { trackName = e.getName(); out.println("Tracking " + trackName); } // This is our target. Reset count (see the run method) count = 0; // If our target is too far away, turn and move torward it. if (e.getDistance() > 150) { gunTurnAmt = normalRelativeAngleDegrees(e.getBearing() + (getHeading() - getRadarHeading())); turnGunRight(gunTurnAmt); // Try changing these to setTurnGunRight, turnRight(e.getBearing()); // and see how much Tracker improves... // (you'll have to make Tracker an AdvancedRobot) ahead(e.getDistance() - 140); return; } // Our target is close. gunTurnAmt = normalRelativeAngleDegrees(e.getBearing() + (getHeading() - getRadarHeading())); turnGunRight(gunTurnAmt); fire(3); // Our target is too close! Back up. if (e.getDistance() < 100) { if (e.getBearing() > -90 && e.getBearing() <= 90) { back(40); } else { ahead(40); } } scan(); }
public void onScannedRobot(ScannedRobotEvent e) { // If we have a target, and this isn't it, return immediately // so we can get more ScannedRobotEvents. if (trackName != null && !e.getName().equals(trackName)) { return; } // If we don't have a target, well, now we do! if (trackName == null) { trackName = e.getName(); out.println("Tracking " + trackName); } // This is our target. Reset count (see the run method) count = 0; // If our target is too far away, turn and move toward it. if (e.getDistance() > 150) { gunTurnAmt = normalRelativeAngleDegrees(e.getBearing() + (getHeading() - getRadarHeading())); turnGunRight(gunTurnAmt); // Try changing these to setTurnGunRight, turnRight(e.getBearing()); // and see how much Tracker improves... // (you'll have to make Tracker an AdvancedRobot) ahead(e.getDistance() - 140); return; } // Our target is close. gunTurnAmt = normalRelativeAngleDegrees(e.getBearing() + (getHeading() - getRadarHeading())); turnGunRight(gunTurnAmt); fire(3); // Our target is too close! Back up. if (e.getDistance() < 100) { if (e.getBearing() > -90 && e.getBearing() <= 90) { back(40); } else { ahead(40); } } scan(); }
diff --git a/tool/epub3-sliderizer/src/danielweck/epub3/sliderizer/XHTML.java b/tool/epub3-sliderizer/src/danielweck/epub3/sliderizer/XHTML.java index 3312f87..708cf22 100644 --- a/tool/epub3-sliderizer/src/danielweck/epub3/sliderizer/XHTML.java +++ b/tool/epub3-sliderizer/src/danielweck/epub3/sliderizer/XHTML.java @@ -1,684 +1,684 @@ package danielweck.epub3.sliderizer; import java.nio.charset.Charset; import java.util.ArrayList; import javax.xml.XMLConstants; import org.jsoup.Jsoup; import org.jsoup.nodes.Entities.EscapeMode; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import danielweck.epub3.sliderizer.model.Slide; import danielweck.epub3.sliderizer.model.SlideShow; import danielweck.xml.XmlDocument; public final class XHTML { public static String getFileName(int i) { // String nStr = String.format("0\1", n); String nStr = i <= 9 ? "0" + i : "" + i; String htmlFile = "slide_" + nStr + ".xhtml"; return htmlFile; } public static String getFileName_Notes(int i) { return getFileName(i).replace(".xhtml", "_NOTES.xhtml"); } public static void createAll(SlideShow slideShow, String pathEpubFolder, int verbosity) throws Exception { int n = slideShow.slides.size(); for (int i = 0; i < n; i++) { XHTML.create(slideShow, i, pathEpubFolder, verbosity); } } private static ArrayList<String> alreadyAddedHeadLinks = new ArrayList<String>(); private static void create_HeadLinks(String paths, Document document, Element elementHead, String linkRel, String linkType, String destFolder) { if (paths == null) { return; } ArrayList<String> array = Epub3FileSet.splitPaths(paths); for (String path : array) { String ref = destFolder + "/" + path; if (alreadyAddedHeadLinks.contains(ref)) { continue; } alreadyAddedHeadLinks.add(ref); Element elementLink = document.createElement("link"); elementHead.appendChild(elementLink); elementLink.setAttribute("rel", linkRel); elementLink.setAttribute("href", ref); if (linkType != null) { elementLink.setAttribute("type", linkType); } } } private static ArrayList<String> alreadyAddedHeadScripts = new ArrayList<String>(); private static void create_HeadScripts(String paths, Document document, Element elementHead, String linkType, String destFolder) { if (paths == null) { return; } ArrayList<String> array = Epub3FileSet.splitPaths(paths); for (String path : array) { String ref = destFolder + "/" + path; if (alreadyAddedHeadScripts.contains(ref)) { continue; } alreadyAddedHeadScripts.add(ref); Element elementScript = document.createElement("script"); elementHead.appendChild(elementScript); elementScript.setAttribute("src", ref); elementScript.appendChild(document.createTextNode(" ")); if (linkType != null) { elementScript.setAttribute("type", linkType); } } } static Element create_Boilerplate(Document document, Slide slide, SlideShow slideShow, String pathEpubFolder, int verbosity, boolean notes) throws Exception { int i = slide == null ? -1 : slideShow.slides.indexOf(slide) + 1; alreadyAddedHeadScripts.clear(); alreadyAddedHeadLinks.clear(); String PATH_PREFIX = slide == null ? "" : "../"; Element elementHtml = document.createElementNS( "http://www.w3.org/1999/xhtml", "html"); document.appendChild(elementHtml); if (slide == null) { elementHtml.setAttribute("id", "epb3sldrzr-NavDoc"); } else { elementHtml.setAttribute("id", "epb3sldrzr-Slide" + (notes ? "Notes" : "") + "_" + i); } elementHtml.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":epub", "http://www.idpf.org/2007/ops"); elementHtml.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":m", "http://www.w3.org/1998/Math/MathML"); elementHtml.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":svg", "http://www.w3.org/2000/svg"); elementHtml .setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":" + XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI); elementHtml.setAttributeNS(XMLConstants.XML_NS_URI, XMLConstants.XML_NS_PREFIX + ":lang", slideShow.LANGUAGE); elementHtml.setAttribute("lang", slideShow.LANGUAGE); Element elementHead = document.createElement("head"); elementHtml.appendChild(elementHead); Element elementMeta = document.createElement("meta"); elementHead.appendChild(elementMeta); elementMeta.setAttribute("charset", "UTF-8"); elementMeta = document.createElement("meta"); elementHead.appendChild(elementMeta); elementMeta.setAttribute("name", "description"); elementMeta.setAttribute("content", Epub3FileSet.THIS); elementMeta = document.createElement("meta"); elementHead.appendChild(elementMeta); elementMeta.setAttribute("name", "keywords"); elementMeta .setAttribute("content", "EPUB EPUB3 HTML5 Sliderizer slideshow slide deck e-book ebook"); String title = slide == null ? slideShow.TITLE : slide.TITLE; if (title == null || title.isEmpty()) { title = "NO TITLE!"; } String subtitle = slide == null ? slideShow.SUBTITLE : slide.SUBTITLE; String htmlTitle = (slideShow.TITLE != null ? slideShow.TITLE : "") + (slideShow.SUBTITLE != null ? " - " + slideShow.SUBTITLE : "") + (slide == null ? "" : " / " + (slide.TITLE != null ? slide.TITLE : "") + (slide.SUBTITLE != null ? " - " + slide.SUBTITLE : "")); if (notes) { htmlTitle = htmlTitle + " (NOTES)"; } - htmlTitle = "(" + i + "/" + slideShow.slides.size() + ") " + htmlTitle; + htmlTitle = "(" + (i == -1 ? 0 : i) + "/" + slideShow.slides.size() + ") " + htmlTitle; Element elementTitle = document.createElement("title"); elementHead.appendChild(elementTitle); elementTitle.appendChild(document.createTextNode(htmlTitle)); create_HeadLinks(slideShow.FAVICON, document, elementHead, "shortcut icon", null, PATH_PREFIX + Epub3FileSet.FOLDER_IMG + (slideShow.FAVICON.equals("favicon.ico") ? "" : "/" + Epub3FileSet.FOLDER_CUSTOM)); if (// !notes && slideShow.VIEWPORT_WIDTH != null && slideShow.VIEWPORT_HEIGHT != null) { Element elementMeta2 = document.createElement("meta"); elementHead.appendChild(elementMeta2); elementMeta2.setAttribute("name", "viewport"); elementMeta2.setAttribute("content", "width=" + slideShow.VIEWPORT_WIDTH + ", height=" + slideShow.VIEWPORT_HEIGHT // + // ", user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1" ); } // create_HeadLinks(Epub3FileSet.CSS_ANIMATE, document, elementHead, // "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); create_HeadLinks(Epub3FileSet.CSS_JQUERY_UI, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); create_HeadLinks(Epub3FileSet.CSS_FONT_AWESOME, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); if (!slideShow.importedConverted) { create_HeadLinks(Epub3FileSet.CSS_DEFAULT, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); } create_HeadLinks(slideShow.FILES_CSS, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS + "/" + Epub3FileSet.FOLDER_CUSTOM); if (slide != null) { create_HeadLinks(slide.FILES_CSS, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS + "/" + Epub3FileSet.FOLDER_CUSTOM); } if (slideShow.importedConverted) { create_HeadLinks(Epub3FileSet.CSS_DEFAULT, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); } create_HeadScripts(Epub3FileSet.JS_CLASSLIST, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_SCREENFULL, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_HAMMER, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_HAMMER_FAKEMULTITOUCH, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_HAMMER_SHOWTOUCHES, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_JQUERY, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_JQUERY_UI, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_JQUERY_BLOCKUI, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_JQUERY_MOUSEWHEEL, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_DEFAULT, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); // create_HeadScripts(Epub3FileSet.JS_SCROLLFIX_NAME, document, // elementHead, null, // "text/javascript", // PATH_PREFIX + Epub3FileSet.JS_FOLDER_NAME); // // create_HeadScripts(Epub3FileSet.JS_iSCROLL_NAME, document, // elementHead, null, // "text/javascript", // PATH_PREFIX + Epub3FileSet.JS_FOLDER_NAME); // // create_HeadScripts(Epub3FileSet.JS_HISTORY_NAME, document, // elementHead, // null, // "text/javascript", // PATH_PREFIX + Epub3FileSet.JS_FOLDER_NAME); // // create_HeadScripts(Epub3FileSet.JS_JSON_NAME, document, elementHead, // null, // "text/javascript", // PATH_PREFIX + Epub3FileSet.JS_FOLDER_NAME); create_HeadScripts(slideShow.FILES_JS, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS + "/" + Epub3FileSet.FOLDER_CUSTOM); if (slide != null) { create_HeadScripts(slide.FILES_JS, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS + "/" + Epub3FileSet.FOLDER_CUSTOM); } if (slide == null) { create_HeadLinks(XHTML.getFileName(1), document, elementHead, "next", null, Epub3FileSet.FOLDER_HTML); create_HeadLinks(slideShow.FILE_EPUB != null ? slideShow.FILE_EPUB : "EPUB3.epub", document, elementHead, "epub", null, "../.."); } else if (!notes) { String prev = "../" + NavDoc.getFileName(); if (i > 1) { prev = XHTML.getFileName(i - 1); } create_HeadLinks(prev, document, elementHead, "prev", null, "."); if (i < slideShow.slides.size()) { String next = XHTML.getFileName(i + 1); create_HeadLinks(next, document, elementHead, "next", null, "."); } } if (slideShow.CSS_STYLE != null) { Element elementStyle = document.createElement("style"); elementHead.appendChild(elementStyle); elementStyle.setAttribute("type", "text/css"); elementStyle.appendChild(document.createTextNode("\n")); String css = Epub3FileSet.processCssStyle(slideShow, slideShow.CSS_STYLE); elementStyle.appendChild(document.createTextNode(css)); elementStyle.appendChild(document.createTextNode("\n")); } if (slide != null && slide.CSS_STYLE != null) { Element elementStyle = document.createElement("style"); elementHead.appendChild(elementStyle); elementStyle.setAttribute("type", "text/css"); elementStyle.appendChild(document.createTextNode("\n")); String css = Epub3FileSet.processCssStyle(slideShow, slide.CSS_STYLE); elementStyle.appendChild(document.createTextNode(css)); elementStyle.appendChild(document.createTextNode("\n")); } if (slideShow.importedConverted) { Element elementStyle = document.createElement("style"); elementHead.appendChild(elementStyle); elementStyle.setAttribute("type", "text/css"); elementStyle.appendChild(document.createTextNode("\n")); String css = "\n\nh1#epb3sldrzr-title,\nh1#epb3sldrzr-title-NOTES\n{\nposition: absolute; left: 0; top: 0; right: 0; display: none; \n}\n\n"; css += "\n\ndiv#epb3sldrzr-root-NOTES,div#epb3sldrzr-root{overflow:hidden;}\n\n"; elementStyle.appendChild(document.createTextNode(css)); elementStyle.appendChild(document.createTextNode("\n")); } if (slideShow.JS_SCRIPT != null) { Element elementScript = document.createElement("script"); elementHead.appendChild(elementScript); // elementScript.setAttribute("type", "text/javascript"); elementScript.appendChild(document.createTextNode("\n//")); elementScript.appendChild(document.createCDATASection("\n" + slideShow.JS_SCRIPT + "\n//")); elementScript.appendChild(document.createTextNode("\n")); } if (slide != null && slide.JS_SCRIPT != null) { Element elementScript = document.createElement("script"); elementHead.appendChild(elementScript); // elementScript.setAttribute("type", "text/javascript"); elementScript.appendChild(document.createTextNode("\n//")); elementScript.appendChild(document.createCDATASection("\n" + slide.JS_SCRIPT + "\n//")); elementScript.appendChild(document.createTextNode("\n")); } Element elementBody_ = document.createElement("body"); elementHtml.appendChild(elementBody_); elementBody_.setAttributeNS("http://www.idpf.org/2007/ops", "epub:type", "bodymatter"); if (notes) { elementBody_.setAttribute("class", "epb3sldrzr-NOTES"); } else if (slide != null) { elementBody_.setAttribute("class", "epb3sldrzr-SLIDE"); } else { elementBody_.setAttribute("class", "epb3sldrzr-NAVDOC"); } Element elementBody = null; if (false && notes) { elementBody = elementBody_; } else { elementBody = document.createElement("div"); elementBody.setAttribute("id", "epb3sldrzr-body" + (notes ? "-NOTES" : "")); elementBody_.appendChild(elementBody); } if (// !notes && slideShow.LOGO != null) { String relativeDestinationPath = PATH_PREFIX + Epub3FileSet.FOLDER_IMG + "/" + Epub3FileSet.FOLDER_CUSTOM + '/' + slideShow.LOGO; Element elementImg = document.createElement("img"); elementBody.appendChild(elementImg); elementImg.setAttribute("id", "epb3sldrzr-logo"); elementImg.setAttribute("alt", ""); elementImg.setAttribute("src", relativeDestinationPath); } Element elementDiv = null; if (false && notes) { elementDiv = elementBody_; } else { elementDiv = document.createElement("div"); elementBody.appendChild(elementDiv); elementDiv.setAttribute("id", "epb3sldrzr-root" + (notes ? "-NOTES" : "")); } Element elementH1 = document.createElement("h1"); elementH1.setAttribute("id", "epb3sldrzr-title" + (notes ? "-NOTES" : "")); elementDiv.appendChild(elementH1); elementH1.appendChild(document.createTextNode(title)); if (subtitle != null) { if (slide == null // || notes ) { Element elementLineBreak = document.createElement("br"); elementH1.appendChild(elementLineBreak); } Element elementSpan = document.createElement("span"); elementH1.appendChild(document.createTextNode(" ")); elementH1.appendChild(elementSpan); elementSpan.setAttribute("id", "epb3sldrzr-subtitle" + (notes ? "-NOTES" : "")); // elementSpan.setAttribute("class", "fade smaller"); elementSpan.appendChild(document.createTextNode(subtitle)); } if (notes) { Element elementA = document.createElement("a"); elementA.setAttribute("href", XHTML.getFileName(i)); elementA.setAttribute("id", "epb3sldrzr-link-noteback"); elementA.appendChild(document.createTextNode("Back")); Element elementP = document.createElement("p"); elementP.appendChild(elementA); elementDiv.appendChild(elementP); } Element elementSection = document.createElement("section"); elementDiv.appendChild(elementSection); elementSection.setAttribute("id", "epb3sldrzr-content" + (notes ? "-NOTES" : "")); return elementSection; } private static void fixRelativeReferences(Element element, Document document, String content, SlideShow slideShow, Slide slide, String pathEpubFolder, int verbosity) throws Exception { if (slide == null) { return; } String name = element.getLocalName(); if (name == null) { name = element.getNodeName(); } // // if (name.equals("svg")) { // slide.containsSVG = true; // } // if (name.equals("math")) { // slide.containsMATHML = true; // } if (name.equals("image") || name.equals("img")) { ArrayList<String> allReferences_IMG = slideShow .getAllReferences_IMG(); NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); String attrVal = attr.getNodeValue(); String attrName = attr.getLocalName(); if (attrName == null) { attrName = attr.getNodeName(); } if (attrName != null && (attrName.equals("xlink:href") || attrName.equals("href") || attrName .equals("src"))) { System.out.println("###### " + attrVal); for (String path : allReferences_IMG) { if (attrVal.indexOf(path) >= 0) { attrVal = attrVal.replaceAll(path, "../" + Epub3FileSet.FOLDER_IMG + "/" + Epub3FileSet.FOLDER_CUSTOM + "/" + path); } } if (attrVal != attr.getNodeValue()) { attr.setNodeValue(attrVal); } } } } NodeList list = element.getChildNodes(); for (int j = 0; j < list.getLength(); j++) { Node node = list.item(j); if (node.getNodeType() != Node.ELEMENT_NODE) { continue; } fixRelativeReferences((Element) node, document, content, slideShow, slide, pathEpubFolder, verbosity); } } static void create_Content(Element elementSection, Document document, String content, SlideShow slideShow, Slide slide, String pathEpubFolder, int verbosity) throws Exception { if (content == null) { return; } String wrappedContent = "<wrapper xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\" xmlns:svg=\"http://www.w3.org/2000/svg\" xmlns:m=\"http://www.w3.org/1998/Math/MathML\">" + content + "</wrapper>"; boolean xmlSuccess = false; Document documentFragment = null; try { documentFragment = XmlDocument.parse(wrappedContent); xmlSuccess = true; } catch (Exception ex) { // ex.printStackTrace(); } boolean soupedUp = false; if (documentFragment == null) { org.jsoup.nodes.Document soupDoc = null; try { soupDoc = Jsoup.parse(wrappedContent, "UTF-8"); soupDoc.outputSettings().prettyPrint(false); soupDoc.outputSettings().charset(Charset.forName("UTF-8")); soupDoc.outputSettings().escapeMode(EscapeMode.xhtml); wrappedContent = soupDoc.outerHtml(); try { documentFragment = XmlDocument.parse(wrappedContent); soupedUp = true; } catch (Exception ex) { // ex.printStackTrace(); } } catch (Exception ex) { // ex.printStackTrace(); } } if (documentFragment != null) { Element docElement = documentFragment.getDocumentElement(); if (soupedUp) { try { docElement = (Element) ((Element) docElement .getElementsByTagName("body").item(0)) .getElementsByTagName("wrapper").item(0); } catch (Exception ex) { ex.printStackTrace(); } } if (xmlSuccess) { elementSection.appendChild(document.createComment("XML")); } else { elementSection.appendChild(document.createComment("SOUP")); } NodeList list = docElement.getChildNodes(); for (int j = 0; j < list.getLength(); j++) { Node node = list.item(j); // if (node.getNodeType() == Node.TEXT_NODE // && node.getTextContent().trim().isEmpty()) { // //if (true) throw new Exception("HERE"); // elementSection.appendChild(document // .createComment("EMPTY_TEXT")); // continue; // } if (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.ELEMENT_NODE || node.getNodeType() == Node.COMMENT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE) { elementSection.appendChild(document.importNode(node, true)); } else { throw new Exception("node.getNodeType() = " + node.getNodeType()); } } fixRelativeReferences(elementSection, document, content, slideShow, slide, pathEpubFolder, verbosity); } else { elementSection.appendChild(document .createComment("XML / SOUP FAIL")); elementSection.appendChild(document.createTextNode(content)); throw new Exception("XML / SOUP FAIL"); } } private static void create_Notes(String notes, SlideShow slideShow, Slide slide, int i, String pathEpubFolder, int verbosity) throws Exception { Document document = XmlDocument.create(); Element elementSection = create_Boilerplate(document, slide, slideShow, pathEpubFolder, verbosity, true); create_Content(elementSection, document, notes, slideShow, slide, pathEpubFolder, verbosity); String fileName = XHTML.getFileName_Notes(i); XmlDocument.save(document, pathEpubFolder + "/" + Epub3FileSet.FOLDER_HTML + "/" + fileName, verbosity); } private static void create(SlideShow slideShow, int i, String pathEpubFolder, int verbosity) throws Exception { Slide slide = slideShow.slides.get(i); i++; Document document = XmlDocument.create(); Element elementSection = create_Boilerplate(document, slide, slideShow, pathEpubFolder, verbosity, false); create_Content(elementSection, document, slide.CONTENT, slideShow, slide, pathEpubFolder, verbosity); if (slide.NOTES != null) { create_Notes(slide.NOTES, slideShow, slide, i, pathEpubFolder, verbosity); Element elementNotesRef = document.createElement("a"); elementSection.appendChild(elementNotesRef); elementNotesRef.appendChild(document.createTextNode("Notes")); elementNotesRef.setAttribute("id", "epb3sldrzr-link-notesref"); elementNotesRef.setAttributeNS("http://www.idpf.org/2007/ops", "epub:type", "noteref"); // elementNotesRef.setAttribute("href", "#epb3sldrzr-notes"); elementNotesRef.setAttribute("href", getFileName_Notes(i)); Element elementNotes = document.createElement("aside"); elementSection.getParentNode().appendChild(elementNotes); elementNotes.setAttribute("id", "epb3sldrzr-notes"); elementNotes.setAttributeNS("http://www.idpf.org/2007/ops", "epub:type", "footnote"); create_Content(elementNotes, document, slide.NOTES, slideShow, slide, pathEpubFolder, verbosity); } String fileName = XHTML.getFileName(i); XmlDocument.save(document, pathEpubFolder + "/" + Epub3FileSet.FOLDER_HTML + "/" + fileName, verbosity); } }
true
true
static Element create_Boilerplate(Document document, Slide slide, SlideShow slideShow, String pathEpubFolder, int verbosity, boolean notes) throws Exception { int i = slide == null ? -1 : slideShow.slides.indexOf(slide) + 1; alreadyAddedHeadScripts.clear(); alreadyAddedHeadLinks.clear(); String PATH_PREFIX = slide == null ? "" : "../"; Element elementHtml = document.createElementNS( "http://www.w3.org/1999/xhtml", "html"); document.appendChild(elementHtml); if (slide == null) { elementHtml.setAttribute("id", "epb3sldrzr-NavDoc"); } else { elementHtml.setAttribute("id", "epb3sldrzr-Slide" + (notes ? "Notes" : "") + "_" + i); } elementHtml.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":epub", "http://www.idpf.org/2007/ops"); elementHtml.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":m", "http://www.w3.org/1998/Math/MathML"); elementHtml.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":svg", "http://www.w3.org/2000/svg"); elementHtml .setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":" + XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI); elementHtml.setAttributeNS(XMLConstants.XML_NS_URI, XMLConstants.XML_NS_PREFIX + ":lang", slideShow.LANGUAGE); elementHtml.setAttribute("lang", slideShow.LANGUAGE); Element elementHead = document.createElement("head"); elementHtml.appendChild(elementHead); Element elementMeta = document.createElement("meta"); elementHead.appendChild(elementMeta); elementMeta.setAttribute("charset", "UTF-8"); elementMeta = document.createElement("meta"); elementHead.appendChild(elementMeta); elementMeta.setAttribute("name", "description"); elementMeta.setAttribute("content", Epub3FileSet.THIS); elementMeta = document.createElement("meta"); elementHead.appendChild(elementMeta); elementMeta.setAttribute("name", "keywords"); elementMeta .setAttribute("content", "EPUB EPUB3 HTML5 Sliderizer slideshow slide deck e-book ebook"); String title = slide == null ? slideShow.TITLE : slide.TITLE; if (title == null || title.isEmpty()) { title = "NO TITLE!"; } String subtitle = slide == null ? slideShow.SUBTITLE : slide.SUBTITLE; String htmlTitle = (slideShow.TITLE != null ? slideShow.TITLE : "") + (slideShow.SUBTITLE != null ? " - " + slideShow.SUBTITLE : "") + (slide == null ? "" : " / " + (slide.TITLE != null ? slide.TITLE : "") + (slide.SUBTITLE != null ? " - " + slide.SUBTITLE : "")); if (notes) { htmlTitle = htmlTitle + " (NOTES)"; } htmlTitle = "(" + i + "/" + slideShow.slides.size() + ") " + htmlTitle; Element elementTitle = document.createElement("title"); elementHead.appendChild(elementTitle); elementTitle.appendChild(document.createTextNode(htmlTitle)); create_HeadLinks(slideShow.FAVICON, document, elementHead, "shortcut icon", null, PATH_PREFIX + Epub3FileSet.FOLDER_IMG + (slideShow.FAVICON.equals("favicon.ico") ? "" : "/" + Epub3FileSet.FOLDER_CUSTOM)); if (// !notes && slideShow.VIEWPORT_WIDTH != null && slideShow.VIEWPORT_HEIGHT != null) { Element elementMeta2 = document.createElement("meta"); elementHead.appendChild(elementMeta2); elementMeta2.setAttribute("name", "viewport"); elementMeta2.setAttribute("content", "width=" + slideShow.VIEWPORT_WIDTH + ", height=" + slideShow.VIEWPORT_HEIGHT // + // ", user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1" ); } // create_HeadLinks(Epub3FileSet.CSS_ANIMATE, document, elementHead, // "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); create_HeadLinks(Epub3FileSet.CSS_JQUERY_UI, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); create_HeadLinks(Epub3FileSet.CSS_FONT_AWESOME, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); if (!slideShow.importedConverted) { create_HeadLinks(Epub3FileSet.CSS_DEFAULT, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); } create_HeadLinks(slideShow.FILES_CSS, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS + "/" + Epub3FileSet.FOLDER_CUSTOM); if (slide != null) { create_HeadLinks(slide.FILES_CSS, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS + "/" + Epub3FileSet.FOLDER_CUSTOM); } if (slideShow.importedConverted) { create_HeadLinks(Epub3FileSet.CSS_DEFAULT, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); } create_HeadScripts(Epub3FileSet.JS_CLASSLIST, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_SCREENFULL, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_HAMMER, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_HAMMER_FAKEMULTITOUCH, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_HAMMER_SHOWTOUCHES, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_JQUERY, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_JQUERY_UI, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_JQUERY_BLOCKUI, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_JQUERY_MOUSEWHEEL, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_DEFAULT, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); // create_HeadScripts(Epub3FileSet.JS_SCROLLFIX_NAME, document, // elementHead, null, // "text/javascript", // PATH_PREFIX + Epub3FileSet.JS_FOLDER_NAME); // // create_HeadScripts(Epub3FileSet.JS_iSCROLL_NAME, document, // elementHead, null, // "text/javascript", // PATH_PREFIX + Epub3FileSet.JS_FOLDER_NAME); // // create_HeadScripts(Epub3FileSet.JS_HISTORY_NAME, document, // elementHead, // null, // "text/javascript", // PATH_PREFIX + Epub3FileSet.JS_FOLDER_NAME); // // create_HeadScripts(Epub3FileSet.JS_JSON_NAME, document, elementHead, // null, // "text/javascript", // PATH_PREFIX + Epub3FileSet.JS_FOLDER_NAME); create_HeadScripts(slideShow.FILES_JS, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS + "/" + Epub3FileSet.FOLDER_CUSTOM); if (slide != null) { create_HeadScripts(slide.FILES_JS, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS + "/" + Epub3FileSet.FOLDER_CUSTOM); } if (slide == null) { create_HeadLinks(XHTML.getFileName(1), document, elementHead, "next", null, Epub3FileSet.FOLDER_HTML); create_HeadLinks(slideShow.FILE_EPUB != null ? slideShow.FILE_EPUB : "EPUB3.epub", document, elementHead, "epub", null, "../.."); } else if (!notes) { String prev = "../" + NavDoc.getFileName(); if (i > 1) { prev = XHTML.getFileName(i - 1); } create_HeadLinks(prev, document, elementHead, "prev", null, "."); if (i < slideShow.slides.size()) { String next = XHTML.getFileName(i + 1); create_HeadLinks(next, document, elementHead, "next", null, "."); } } if (slideShow.CSS_STYLE != null) { Element elementStyle = document.createElement("style"); elementHead.appendChild(elementStyle); elementStyle.setAttribute("type", "text/css"); elementStyle.appendChild(document.createTextNode("\n")); String css = Epub3FileSet.processCssStyle(slideShow, slideShow.CSS_STYLE); elementStyle.appendChild(document.createTextNode(css)); elementStyle.appendChild(document.createTextNode("\n")); } if (slide != null && slide.CSS_STYLE != null) { Element elementStyle = document.createElement("style"); elementHead.appendChild(elementStyle); elementStyle.setAttribute("type", "text/css"); elementStyle.appendChild(document.createTextNode("\n")); String css = Epub3FileSet.processCssStyle(slideShow, slide.CSS_STYLE); elementStyle.appendChild(document.createTextNode(css)); elementStyle.appendChild(document.createTextNode("\n")); } if (slideShow.importedConverted) { Element elementStyle = document.createElement("style"); elementHead.appendChild(elementStyle); elementStyle.setAttribute("type", "text/css"); elementStyle.appendChild(document.createTextNode("\n")); String css = "\n\nh1#epb3sldrzr-title,\nh1#epb3sldrzr-title-NOTES\n{\nposition: absolute; left: 0; top: 0; right: 0; display: none; \n}\n\n"; css += "\n\ndiv#epb3sldrzr-root-NOTES,div#epb3sldrzr-root{overflow:hidden;}\n\n"; elementStyle.appendChild(document.createTextNode(css)); elementStyle.appendChild(document.createTextNode("\n")); } if (slideShow.JS_SCRIPT != null) { Element elementScript = document.createElement("script"); elementHead.appendChild(elementScript); // elementScript.setAttribute("type", "text/javascript"); elementScript.appendChild(document.createTextNode("\n//")); elementScript.appendChild(document.createCDATASection("\n" + slideShow.JS_SCRIPT + "\n//")); elementScript.appendChild(document.createTextNode("\n")); } if (slide != null && slide.JS_SCRIPT != null) { Element elementScript = document.createElement("script"); elementHead.appendChild(elementScript); // elementScript.setAttribute("type", "text/javascript"); elementScript.appendChild(document.createTextNode("\n//")); elementScript.appendChild(document.createCDATASection("\n" + slide.JS_SCRIPT + "\n//")); elementScript.appendChild(document.createTextNode("\n")); } Element elementBody_ = document.createElement("body"); elementHtml.appendChild(elementBody_); elementBody_.setAttributeNS("http://www.idpf.org/2007/ops", "epub:type", "bodymatter"); if (notes) { elementBody_.setAttribute("class", "epb3sldrzr-NOTES"); } else if (slide != null) { elementBody_.setAttribute("class", "epb3sldrzr-SLIDE"); } else { elementBody_.setAttribute("class", "epb3sldrzr-NAVDOC"); } Element elementBody = null; if (false && notes) { elementBody = elementBody_; } else { elementBody = document.createElement("div"); elementBody.setAttribute("id", "epb3sldrzr-body" + (notes ? "-NOTES" : "")); elementBody_.appendChild(elementBody); } if (// !notes && slideShow.LOGO != null) { String relativeDestinationPath = PATH_PREFIX + Epub3FileSet.FOLDER_IMG + "/" + Epub3FileSet.FOLDER_CUSTOM + '/' + slideShow.LOGO; Element elementImg = document.createElement("img"); elementBody.appendChild(elementImg); elementImg.setAttribute("id", "epb3sldrzr-logo"); elementImg.setAttribute("alt", ""); elementImg.setAttribute("src", relativeDestinationPath); } Element elementDiv = null; if (false && notes) { elementDiv = elementBody_; } else { elementDiv = document.createElement("div"); elementBody.appendChild(elementDiv); elementDiv.setAttribute("id", "epb3sldrzr-root" + (notes ? "-NOTES" : "")); } Element elementH1 = document.createElement("h1"); elementH1.setAttribute("id", "epb3sldrzr-title" + (notes ? "-NOTES" : "")); elementDiv.appendChild(elementH1); elementH1.appendChild(document.createTextNode(title)); if (subtitle != null) { if (slide == null // || notes ) { Element elementLineBreak = document.createElement("br"); elementH1.appendChild(elementLineBreak); } Element elementSpan = document.createElement("span"); elementH1.appendChild(document.createTextNode(" ")); elementH1.appendChild(elementSpan); elementSpan.setAttribute("id", "epb3sldrzr-subtitle" + (notes ? "-NOTES" : "")); // elementSpan.setAttribute("class", "fade smaller"); elementSpan.appendChild(document.createTextNode(subtitle)); } if (notes) { Element elementA = document.createElement("a"); elementA.setAttribute("href", XHTML.getFileName(i)); elementA.setAttribute("id", "epb3sldrzr-link-noteback"); elementA.appendChild(document.createTextNode("Back")); Element elementP = document.createElement("p"); elementP.appendChild(elementA); elementDiv.appendChild(elementP); } Element elementSection = document.createElement("section"); elementDiv.appendChild(elementSection); elementSection.setAttribute("id", "epb3sldrzr-content" + (notes ? "-NOTES" : "")); return elementSection; }
static Element create_Boilerplate(Document document, Slide slide, SlideShow slideShow, String pathEpubFolder, int verbosity, boolean notes) throws Exception { int i = slide == null ? -1 : slideShow.slides.indexOf(slide) + 1; alreadyAddedHeadScripts.clear(); alreadyAddedHeadLinks.clear(); String PATH_PREFIX = slide == null ? "" : "../"; Element elementHtml = document.createElementNS( "http://www.w3.org/1999/xhtml", "html"); document.appendChild(elementHtml); if (slide == null) { elementHtml.setAttribute("id", "epb3sldrzr-NavDoc"); } else { elementHtml.setAttribute("id", "epb3sldrzr-Slide" + (notes ? "Notes" : "") + "_" + i); } elementHtml.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":epub", "http://www.idpf.org/2007/ops"); elementHtml.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":m", "http://www.w3.org/1998/Math/MathML"); elementHtml.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":svg", "http://www.w3.org/2000/svg"); elementHtml .setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":" + XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI); elementHtml.setAttributeNS(XMLConstants.XML_NS_URI, XMLConstants.XML_NS_PREFIX + ":lang", slideShow.LANGUAGE); elementHtml.setAttribute("lang", slideShow.LANGUAGE); Element elementHead = document.createElement("head"); elementHtml.appendChild(elementHead); Element elementMeta = document.createElement("meta"); elementHead.appendChild(elementMeta); elementMeta.setAttribute("charset", "UTF-8"); elementMeta = document.createElement("meta"); elementHead.appendChild(elementMeta); elementMeta.setAttribute("name", "description"); elementMeta.setAttribute("content", Epub3FileSet.THIS); elementMeta = document.createElement("meta"); elementHead.appendChild(elementMeta); elementMeta.setAttribute("name", "keywords"); elementMeta .setAttribute("content", "EPUB EPUB3 HTML5 Sliderizer slideshow slide deck e-book ebook"); String title = slide == null ? slideShow.TITLE : slide.TITLE; if (title == null || title.isEmpty()) { title = "NO TITLE!"; } String subtitle = slide == null ? slideShow.SUBTITLE : slide.SUBTITLE; String htmlTitle = (slideShow.TITLE != null ? slideShow.TITLE : "") + (slideShow.SUBTITLE != null ? " - " + slideShow.SUBTITLE : "") + (slide == null ? "" : " / " + (slide.TITLE != null ? slide.TITLE : "") + (slide.SUBTITLE != null ? " - " + slide.SUBTITLE : "")); if (notes) { htmlTitle = htmlTitle + " (NOTES)"; } htmlTitle = "(" + (i == -1 ? 0 : i) + "/" + slideShow.slides.size() + ") " + htmlTitle; Element elementTitle = document.createElement("title"); elementHead.appendChild(elementTitle); elementTitle.appendChild(document.createTextNode(htmlTitle)); create_HeadLinks(slideShow.FAVICON, document, elementHead, "shortcut icon", null, PATH_PREFIX + Epub3FileSet.FOLDER_IMG + (slideShow.FAVICON.equals("favicon.ico") ? "" : "/" + Epub3FileSet.FOLDER_CUSTOM)); if (// !notes && slideShow.VIEWPORT_WIDTH != null && slideShow.VIEWPORT_HEIGHT != null) { Element elementMeta2 = document.createElement("meta"); elementHead.appendChild(elementMeta2); elementMeta2.setAttribute("name", "viewport"); elementMeta2.setAttribute("content", "width=" + slideShow.VIEWPORT_WIDTH + ", height=" + slideShow.VIEWPORT_HEIGHT // + // ", user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1" ); } // create_HeadLinks(Epub3FileSet.CSS_ANIMATE, document, elementHead, // "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); create_HeadLinks(Epub3FileSet.CSS_JQUERY_UI, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); create_HeadLinks(Epub3FileSet.CSS_FONT_AWESOME, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); if (!slideShow.importedConverted) { create_HeadLinks(Epub3FileSet.CSS_DEFAULT, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); } create_HeadLinks(slideShow.FILES_CSS, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS + "/" + Epub3FileSet.FOLDER_CUSTOM); if (slide != null) { create_HeadLinks(slide.FILES_CSS, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS + "/" + Epub3FileSet.FOLDER_CUSTOM); } if (slideShow.importedConverted) { create_HeadLinks(Epub3FileSet.CSS_DEFAULT, document, elementHead, "stylesheet", "text/css", PATH_PREFIX + Epub3FileSet.FOLDER_CSS); } create_HeadScripts(Epub3FileSet.JS_CLASSLIST, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_SCREENFULL, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_HAMMER, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_HAMMER_FAKEMULTITOUCH, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_HAMMER_SHOWTOUCHES, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_JQUERY, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_JQUERY_UI, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_JQUERY_BLOCKUI, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_JQUERY_MOUSEWHEEL, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); create_HeadScripts(Epub3FileSet.JS_DEFAULT, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS); // create_HeadScripts(Epub3FileSet.JS_SCROLLFIX_NAME, document, // elementHead, null, // "text/javascript", // PATH_PREFIX + Epub3FileSet.JS_FOLDER_NAME); // // create_HeadScripts(Epub3FileSet.JS_iSCROLL_NAME, document, // elementHead, null, // "text/javascript", // PATH_PREFIX + Epub3FileSet.JS_FOLDER_NAME); // // create_HeadScripts(Epub3FileSet.JS_HISTORY_NAME, document, // elementHead, // null, // "text/javascript", // PATH_PREFIX + Epub3FileSet.JS_FOLDER_NAME); // // create_HeadScripts(Epub3FileSet.JS_JSON_NAME, document, elementHead, // null, // "text/javascript", // PATH_PREFIX + Epub3FileSet.JS_FOLDER_NAME); create_HeadScripts(slideShow.FILES_JS, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS + "/" + Epub3FileSet.FOLDER_CUSTOM); if (slide != null) { create_HeadScripts(slide.FILES_JS, document, elementHead, null, // "text/javascript", PATH_PREFIX + Epub3FileSet.FOLDER_JS + "/" + Epub3FileSet.FOLDER_CUSTOM); } if (slide == null) { create_HeadLinks(XHTML.getFileName(1), document, elementHead, "next", null, Epub3FileSet.FOLDER_HTML); create_HeadLinks(slideShow.FILE_EPUB != null ? slideShow.FILE_EPUB : "EPUB3.epub", document, elementHead, "epub", null, "../.."); } else if (!notes) { String prev = "../" + NavDoc.getFileName(); if (i > 1) { prev = XHTML.getFileName(i - 1); } create_HeadLinks(prev, document, elementHead, "prev", null, "."); if (i < slideShow.slides.size()) { String next = XHTML.getFileName(i + 1); create_HeadLinks(next, document, elementHead, "next", null, "."); } } if (slideShow.CSS_STYLE != null) { Element elementStyle = document.createElement("style"); elementHead.appendChild(elementStyle); elementStyle.setAttribute("type", "text/css"); elementStyle.appendChild(document.createTextNode("\n")); String css = Epub3FileSet.processCssStyle(slideShow, slideShow.CSS_STYLE); elementStyle.appendChild(document.createTextNode(css)); elementStyle.appendChild(document.createTextNode("\n")); } if (slide != null && slide.CSS_STYLE != null) { Element elementStyle = document.createElement("style"); elementHead.appendChild(elementStyle); elementStyle.setAttribute("type", "text/css"); elementStyle.appendChild(document.createTextNode("\n")); String css = Epub3FileSet.processCssStyle(slideShow, slide.CSS_STYLE); elementStyle.appendChild(document.createTextNode(css)); elementStyle.appendChild(document.createTextNode("\n")); } if (slideShow.importedConverted) { Element elementStyle = document.createElement("style"); elementHead.appendChild(elementStyle); elementStyle.setAttribute("type", "text/css"); elementStyle.appendChild(document.createTextNode("\n")); String css = "\n\nh1#epb3sldrzr-title,\nh1#epb3sldrzr-title-NOTES\n{\nposition: absolute; left: 0; top: 0; right: 0; display: none; \n}\n\n"; css += "\n\ndiv#epb3sldrzr-root-NOTES,div#epb3sldrzr-root{overflow:hidden;}\n\n"; elementStyle.appendChild(document.createTextNode(css)); elementStyle.appendChild(document.createTextNode("\n")); } if (slideShow.JS_SCRIPT != null) { Element elementScript = document.createElement("script"); elementHead.appendChild(elementScript); // elementScript.setAttribute("type", "text/javascript"); elementScript.appendChild(document.createTextNode("\n//")); elementScript.appendChild(document.createCDATASection("\n" + slideShow.JS_SCRIPT + "\n//")); elementScript.appendChild(document.createTextNode("\n")); } if (slide != null && slide.JS_SCRIPT != null) { Element elementScript = document.createElement("script"); elementHead.appendChild(elementScript); // elementScript.setAttribute("type", "text/javascript"); elementScript.appendChild(document.createTextNode("\n//")); elementScript.appendChild(document.createCDATASection("\n" + slide.JS_SCRIPT + "\n//")); elementScript.appendChild(document.createTextNode("\n")); } Element elementBody_ = document.createElement("body"); elementHtml.appendChild(elementBody_); elementBody_.setAttributeNS("http://www.idpf.org/2007/ops", "epub:type", "bodymatter"); if (notes) { elementBody_.setAttribute("class", "epb3sldrzr-NOTES"); } else if (slide != null) { elementBody_.setAttribute("class", "epb3sldrzr-SLIDE"); } else { elementBody_.setAttribute("class", "epb3sldrzr-NAVDOC"); } Element elementBody = null; if (false && notes) { elementBody = elementBody_; } else { elementBody = document.createElement("div"); elementBody.setAttribute("id", "epb3sldrzr-body" + (notes ? "-NOTES" : "")); elementBody_.appendChild(elementBody); } if (// !notes && slideShow.LOGO != null) { String relativeDestinationPath = PATH_PREFIX + Epub3FileSet.FOLDER_IMG + "/" + Epub3FileSet.FOLDER_CUSTOM + '/' + slideShow.LOGO; Element elementImg = document.createElement("img"); elementBody.appendChild(elementImg); elementImg.setAttribute("id", "epb3sldrzr-logo"); elementImg.setAttribute("alt", ""); elementImg.setAttribute("src", relativeDestinationPath); } Element elementDiv = null; if (false && notes) { elementDiv = elementBody_; } else { elementDiv = document.createElement("div"); elementBody.appendChild(elementDiv); elementDiv.setAttribute("id", "epb3sldrzr-root" + (notes ? "-NOTES" : "")); } Element elementH1 = document.createElement("h1"); elementH1.setAttribute("id", "epb3sldrzr-title" + (notes ? "-NOTES" : "")); elementDiv.appendChild(elementH1); elementH1.appendChild(document.createTextNode(title)); if (subtitle != null) { if (slide == null // || notes ) { Element elementLineBreak = document.createElement("br"); elementH1.appendChild(elementLineBreak); } Element elementSpan = document.createElement("span"); elementH1.appendChild(document.createTextNode(" ")); elementH1.appendChild(elementSpan); elementSpan.setAttribute("id", "epb3sldrzr-subtitle" + (notes ? "-NOTES" : "")); // elementSpan.setAttribute("class", "fade smaller"); elementSpan.appendChild(document.createTextNode(subtitle)); } if (notes) { Element elementA = document.createElement("a"); elementA.setAttribute("href", XHTML.getFileName(i)); elementA.setAttribute("id", "epb3sldrzr-link-noteback"); elementA.appendChild(document.createTextNode("Back")); Element elementP = document.createElement("p"); elementP.appendChild(elementA); elementDiv.appendChild(elementP); } Element elementSection = document.createElement("section"); elementDiv.appendChild(elementSection); elementSection.setAttribute("id", "epb3sldrzr-content" + (notes ? "-NOTES" : "")); return elementSection; }
diff --git a/SilverSurferPC/src/mapping/MapReader.java b/SilverSurferPC/src/mapping/MapReader.java index 2377348..ee2b25f 100644 --- a/SilverSurferPC/src/mapping/MapReader.java +++ b/SilverSurferPC/src/mapping/MapReader.java @@ -1,271 +1,280 @@ package mapping; import java.awt.Point; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; /** * Used to read a map from a given ASCII file. */ public class MapReader { public static MapGraph createMapFromFile(final File txtFile) { final String[][] infoMatrix = createInfoMatrixFromFile(txtFile); // Fill a graph with the information in infoMatrix. MapGraph map = new MapGraph(); for (int row = 0; row < infoMatrix.length; row++) for (int column = 0; column < infoMatrix[row].length; column++) { map.addTileXY(new Point(column, row)); } // // Link all tiles (Al gebeurt in addTileXY) // for (int row = 0; row < infoMatrix.length - 1; row++) // for (int column = 0; column < infoMatrix[row].length - 1; column++) { // Tile tile = map.getTile(new Point(column, row)); // // set east tile's edge // map.getTile(new Point(column + 1, row)).replaceEdge( // Orientation.WEST, tile.getEdge(Orientation.EAST)); // // set south tile's edge // map.getTile(new Point(column, row + 1)).replaceEdge( // Orientation.NORTH, tile.getEdge(Orientation.SOUTH)); // } for (int row = 0; row < infoMatrix.length; row++) { for (int column = 0; column < infoMatrix[row].length; column++) { final String[] seperatedInfoIJ = infoMatrix[row][column] .split("\\."); // Create the desired tile form first // connect it to the graph in a right way later! Point pointIJ = new Point(column, row); Tile tileIJ = map.getTile(pointIJ); if (seperatedInfoIJ[0].equals("Cross")) { createCrossFromTile(tileIJ); } else if (seperatedInfoIJ[0].equals("Straight")) { createStraightFromTile( tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } else if (seperatedInfoIJ[0].equals("Corner")) { createCornerFromTile( tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } else if (seperatedInfoIJ[0].equals("T")) { createTFromTile( tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } else if (seperatedInfoIJ[0].equals("DeadEnd")) { createDeadEndFromTile( tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } else if (seperatedInfoIJ[0].equals("Closed")){ createClosedFromTile(tileIJ); } else if (seperatedInfoIJ[0].equals("Seesaw")){ createSeesawFromTile(tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } // a Barcode value has been specified if (seperatedInfoIJ.length == 3) { //An object has been specified. if (seperatedInfoIJ[2].equals("V")){ - tileIJ.setContent(new TreasureObject(tileIJ, 0)); + Orientation orientation = Orientation.switchStringToOrientation(seperatedInfoIJ[1]); + String[] barcodeInfo = infoMatrix[row+1][column].split("\\."); + if(orientation == Orientation.SOUTH) + barcodeInfo = infoMatrix[row-1][column].split("\\."); + else if(orientation == Orientation.WEST) + barcodeInfo = infoMatrix[row][column+1].split("\\."); + else if(orientation == Orientation.EAST) + barcodeInfo = infoMatrix[row][column-1].split("\\."); + int value = Integer.valueOf(barcodeInfo[2]); + tileIJ.setContent(new TreasureObject(tileIJ, value)); } //A StartTile has been specified else if (seperatedInfoIJ[2].startsWith("S")){ Character player = seperatedInfoIJ[2].charAt(1); int pNo = Character.getNumericValue(player); Character oriChar = seperatedInfoIJ[2].charAt(2); Orientation ori = Orientation.switchStringToOrientation(oriChar.toString()); StartBase base = new StartBase(tileIJ, pNo, ori); tileIJ.setContent(base); } //only possibility left @3 is a barcode. else{ tileIJ.setContent(new Barcode(tileIJ, Integer .valueOf(seperatedInfoIJ[2]), Orientation .switchStringToOrientation(seperatedInfoIJ[1]))); } } //A StartTile has been specified if (seperatedInfoIJ.length == 4) { Character player = seperatedInfoIJ[3].charAt(1); int pNo = Character.getNumericValue(player); Character oriChar = seperatedInfoIJ[3].charAt(2); Orientation ori = Orientation.switchStringToOrientation(oriChar.toString()); StartBase base = new StartBase(tileIJ, pNo, ori); tileIJ.setContent(base); } // a seesaw has been specified // if (seperatedInfoIJ.length == 4 // && "s".equals(seperatedInfoIJ[2])) { // // // add a seesaw to the tile // char[] values = seperatedInfoIJ[3].toCharArray(); // tileIJ.setContent(new Seesaw(tileIJ, values[2])); // // // set the right edges // Orientation orientation = Orientation.switchStringToOrientation((String.valueOf(values[0]))); // if(Integer.valueOf(String.valueOf(values[1])) == 0) // tileIJ.getEdge(orientation).replaceObstruction(Obstruction.SEESAW_DOWN); // else if(Integer.valueOf(String.valueOf(values[1])) == 1) // tileIJ.getEdge(orientation).replaceObstruction(Obstruction.SEESAW_UP); // // } } } return map; } private static String[][] createInfoMatrixFromFile(final File f) { int collums; int rows; try { // Setup I/O final BufferedReader readbuffer = new BufferedReader( new FileReader(f)); String strRead; // Read first line, extract Map-dimensions. strRead = readbuffer.readLine(); final String values[] = strRead.split(" "); collums = Integer.valueOf(values[0]); rows = Integer.valueOf(values[1]); final String[][] tileTypes = new String[rows][collums]; int lineNo = 0; while ((strRead = readbuffer.readLine()) != null) { int collumNo = 0; // Seperate comment from non-comment final String splitComment[] = strRead.split("#"); // Filter whitespace if (isValuableString(splitComment[0])) { // Split information on tabs final String splitarray[] = splitComment[0].split("\t"); for (final String string : splitarray) { if (isValuableString(string)) { tileTypes[lineNo][collumNo++] = string; } } lineNo++; } } readbuffer.close(); // toegevoegd om warning weg te werken, geeft // geen errors? return tileTypes; } catch (final Exception e) { System.err .println("[I/O] Sorry, something went wrong reading the File."); } return new String[0][0]; } public static void createDeadEndFromTile(final Tile t, final Orientation orientation) { for (final Orientation ori : Orientation.values()) { if (!ori.equals(orientation.getOppositeOrientation())) { t.getEdge(ori).replaceObstruction(Obstruction.WALL); } else { t.getEdge(ori).replaceObstruction(Obstruction.WHITE_LINE); } } } /** * Makes sure all edges of this Tile are un-obstructed. */ public static void createCrossFromTile(final Tile t) { return; } public static void createCornerFromTile(final Tile t, final Orientation orientation) { t.getEdge(orientation).replaceObstruction(Obstruction.WALL); t.getEdge(orientation.getOtherOrientationCorner()).replaceObstruction( Obstruction.WALL); t.getEdge(orientation.getOppositeOrientation()).replaceObstruction(Obstruction.WHITE_LINE); t.getEdge(orientation.getOppositeOrientation().getOtherOrientationCorner()).replaceObstruction( Obstruction.WHITE_LINE); } public static void createStraightFromTile(final Tile t, final Orientation orientation) { for (final Orientation ori : Orientation.values()) { if ((!(ori.equals(orientation))) && (!(ori.equals(orientation.getOppositeOrientation())))) { t.getEdge(ori).replaceObstruction(Obstruction.WALL); } else { t.getEdge(ori).replaceObstruction(Obstruction.WHITE_LINE); } } } public static void createTFromTile(final Tile t, final Orientation orientation) { for (final Orientation ori : Orientation.values()) { if(ori.equals(orientation)) { t.getEdge(ori).replaceObstruction(Obstruction.WALL); } else { t.getEdge(ori).replaceObstruction(Obstruction.WHITE_LINE); } } } public static void createClosedFromTile(final Tile t){ for (final Orientation ori : Orientation.values()) t.getEdge(ori).replaceObstruction(Obstruction.WALL); } public static void createSeesawFromTile(final Tile t, Orientation ori){ createStraightFromTile(t, ori); Seesaw saw = new Seesaw(t, ori); t.setContent(saw); } /** * Checks if this String has any character that isn't a * whitespace-character. */ private static boolean isValuableString(final String string) { final char[] chars = new char[string.length()]; string.getChars(0, string.length(), chars, 0); for (final char c : chars) { if (!Character.isWhitespace(c)) { return true; } } return false; } }
true
true
public static MapGraph createMapFromFile(final File txtFile) { final String[][] infoMatrix = createInfoMatrixFromFile(txtFile); // Fill a graph with the information in infoMatrix. MapGraph map = new MapGraph(); for (int row = 0; row < infoMatrix.length; row++) for (int column = 0; column < infoMatrix[row].length; column++) { map.addTileXY(new Point(column, row)); } // // Link all tiles (Al gebeurt in addTileXY) // for (int row = 0; row < infoMatrix.length - 1; row++) // for (int column = 0; column < infoMatrix[row].length - 1; column++) { // Tile tile = map.getTile(new Point(column, row)); // // set east tile's edge // map.getTile(new Point(column + 1, row)).replaceEdge( // Orientation.WEST, tile.getEdge(Orientation.EAST)); // // set south tile's edge // map.getTile(new Point(column, row + 1)).replaceEdge( // Orientation.NORTH, tile.getEdge(Orientation.SOUTH)); // } for (int row = 0; row < infoMatrix.length; row++) { for (int column = 0; column < infoMatrix[row].length; column++) { final String[] seperatedInfoIJ = infoMatrix[row][column] .split("\\."); // Create the desired tile form first // connect it to the graph in a right way later! Point pointIJ = new Point(column, row); Tile tileIJ = map.getTile(pointIJ); if (seperatedInfoIJ[0].equals("Cross")) { createCrossFromTile(tileIJ); } else if (seperatedInfoIJ[0].equals("Straight")) { createStraightFromTile( tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } else if (seperatedInfoIJ[0].equals("Corner")) { createCornerFromTile( tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } else if (seperatedInfoIJ[0].equals("T")) { createTFromTile( tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } else if (seperatedInfoIJ[0].equals("DeadEnd")) { createDeadEndFromTile( tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } else if (seperatedInfoIJ[0].equals("Closed")){ createClosedFromTile(tileIJ); } else if (seperatedInfoIJ[0].equals("Seesaw")){ createSeesawFromTile(tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } // a Barcode value has been specified if (seperatedInfoIJ.length == 3) { //An object has been specified. if (seperatedInfoIJ[2].equals("V")){ tileIJ.setContent(new TreasureObject(tileIJ, 0)); } //A StartTile has been specified else if (seperatedInfoIJ[2].startsWith("S")){ Character player = seperatedInfoIJ[2].charAt(1); int pNo = Character.getNumericValue(player); Character oriChar = seperatedInfoIJ[2].charAt(2); Orientation ori = Orientation.switchStringToOrientation(oriChar.toString()); StartBase base = new StartBase(tileIJ, pNo, ori); tileIJ.setContent(base); } //only possibility left @3 is a barcode. else{ tileIJ.setContent(new Barcode(tileIJ, Integer .valueOf(seperatedInfoIJ[2]), Orientation .switchStringToOrientation(seperatedInfoIJ[1]))); } } //A StartTile has been specified if (seperatedInfoIJ.length == 4) { Character player = seperatedInfoIJ[3].charAt(1); int pNo = Character.getNumericValue(player); Character oriChar = seperatedInfoIJ[3].charAt(2); Orientation ori = Orientation.switchStringToOrientation(oriChar.toString()); StartBase base = new StartBase(tileIJ, pNo, ori); tileIJ.setContent(base); } // a seesaw has been specified // if (seperatedInfoIJ.length == 4 // && "s".equals(seperatedInfoIJ[2])) { // // // add a seesaw to the tile // char[] values = seperatedInfoIJ[3].toCharArray(); // tileIJ.setContent(new Seesaw(tileIJ, values[2])); // // // set the right edges // Orientation orientation = Orientation.switchStringToOrientation((String.valueOf(values[0]))); // if(Integer.valueOf(String.valueOf(values[1])) == 0) // tileIJ.getEdge(orientation).replaceObstruction(Obstruction.SEESAW_DOWN); // else if(Integer.valueOf(String.valueOf(values[1])) == 1) // tileIJ.getEdge(orientation).replaceObstruction(Obstruction.SEESAW_UP); // // } } } return map; }
public static MapGraph createMapFromFile(final File txtFile) { final String[][] infoMatrix = createInfoMatrixFromFile(txtFile); // Fill a graph with the information in infoMatrix. MapGraph map = new MapGraph(); for (int row = 0; row < infoMatrix.length; row++) for (int column = 0; column < infoMatrix[row].length; column++) { map.addTileXY(new Point(column, row)); } // // Link all tiles (Al gebeurt in addTileXY) // for (int row = 0; row < infoMatrix.length - 1; row++) // for (int column = 0; column < infoMatrix[row].length - 1; column++) { // Tile tile = map.getTile(new Point(column, row)); // // set east tile's edge // map.getTile(new Point(column + 1, row)).replaceEdge( // Orientation.WEST, tile.getEdge(Orientation.EAST)); // // set south tile's edge // map.getTile(new Point(column, row + 1)).replaceEdge( // Orientation.NORTH, tile.getEdge(Orientation.SOUTH)); // } for (int row = 0; row < infoMatrix.length; row++) { for (int column = 0; column < infoMatrix[row].length; column++) { final String[] seperatedInfoIJ = infoMatrix[row][column] .split("\\."); // Create the desired tile form first // connect it to the graph in a right way later! Point pointIJ = new Point(column, row); Tile tileIJ = map.getTile(pointIJ); if (seperatedInfoIJ[0].equals("Cross")) { createCrossFromTile(tileIJ); } else if (seperatedInfoIJ[0].equals("Straight")) { createStraightFromTile( tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } else if (seperatedInfoIJ[0].equals("Corner")) { createCornerFromTile( tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } else if (seperatedInfoIJ[0].equals("T")) { createTFromTile( tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } else if (seperatedInfoIJ[0].equals("DeadEnd")) { createDeadEndFromTile( tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } else if (seperatedInfoIJ[0].equals("Closed")){ createClosedFromTile(tileIJ); } else if (seperatedInfoIJ[0].equals("Seesaw")){ createSeesawFromTile(tileIJ, Orientation .switchStringToOrientation(seperatedInfoIJ[1])); } // a Barcode value has been specified if (seperatedInfoIJ.length == 3) { //An object has been specified. if (seperatedInfoIJ[2].equals("V")){ Orientation orientation = Orientation.switchStringToOrientation(seperatedInfoIJ[1]); String[] barcodeInfo = infoMatrix[row+1][column].split("\\."); if(orientation == Orientation.SOUTH) barcodeInfo = infoMatrix[row-1][column].split("\\."); else if(orientation == Orientation.WEST) barcodeInfo = infoMatrix[row][column+1].split("\\."); else if(orientation == Orientation.EAST) barcodeInfo = infoMatrix[row][column-1].split("\\."); int value = Integer.valueOf(barcodeInfo[2]); tileIJ.setContent(new TreasureObject(tileIJ, value)); } //A StartTile has been specified else if (seperatedInfoIJ[2].startsWith("S")){ Character player = seperatedInfoIJ[2].charAt(1); int pNo = Character.getNumericValue(player); Character oriChar = seperatedInfoIJ[2].charAt(2); Orientation ori = Orientation.switchStringToOrientation(oriChar.toString()); StartBase base = new StartBase(tileIJ, pNo, ori); tileIJ.setContent(base); } //only possibility left @3 is a barcode. else{ tileIJ.setContent(new Barcode(tileIJ, Integer .valueOf(seperatedInfoIJ[2]), Orientation .switchStringToOrientation(seperatedInfoIJ[1]))); } } //A StartTile has been specified if (seperatedInfoIJ.length == 4) { Character player = seperatedInfoIJ[3].charAt(1); int pNo = Character.getNumericValue(player); Character oriChar = seperatedInfoIJ[3].charAt(2); Orientation ori = Orientation.switchStringToOrientation(oriChar.toString()); StartBase base = new StartBase(tileIJ, pNo, ori); tileIJ.setContent(base); } // a seesaw has been specified // if (seperatedInfoIJ.length == 4 // && "s".equals(seperatedInfoIJ[2])) { // // // add a seesaw to the tile // char[] values = seperatedInfoIJ[3].toCharArray(); // tileIJ.setContent(new Seesaw(tileIJ, values[2])); // // // set the right edges // Orientation orientation = Orientation.switchStringToOrientation((String.valueOf(values[0]))); // if(Integer.valueOf(String.valueOf(values[1])) == 0) // tileIJ.getEdge(orientation).replaceObstruction(Obstruction.SEESAW_DOWN); // else if(Integer.valueOf(String.valueOf(values[1])) == 1) // tileIJ.getEdge(orientation).replaceObstruction(Obstruction.SEESAW_UP); // // } } } return map; }
diff --git a/commons/src/main/java/org/apache/commons/httpclient/Cookie.java b/commons/src/main/java/org/apache/commons/httpclient/Cookie.java index 49984fa..2dcf987 100644 --- a/commons/src/main/java/org/apache/commons/httpclient/Cookie.java +++ b/commons/src/main/java/org/apache/commons/httpclient/Cookie.java @@ -1,575 +1,579 @@ /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/Cookie.java,v 1.44 2004/06/05 16:49:20 olegk Exp $ * $Revision$ * $Date$ * * ==================================================================== * * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.commons.httpclient; import java.io.Serializable; import java.text.RuleBasedCollator; import java.util.Comparator; import java.util.Date; import java.util.Locale; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.httpclient.util.LangUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * <p> * HTTP "magic-cookie" represents a piece of state information * that the HTTP agent and the target server can exchange to maintain * a session. * </p> * * @author B.C. Holmes * @author <a href="mailto:[email protected]">Park, Sung-Gu</a> * @author <a href="mailto:[email protected]">Doug Sale</a> * @author Rod Waldhoff * @author dIon Gillard * @author Sean C. Sullivan * @author <a href="mailto:[email protected]">John Evans</a> * @author Marc A. Saegesser * @author <a href="mailto:[email protected]">Oleg Kalnichevski</a> * @author <a href="mailto:[email protected]">Mike Bowler</a> * * @version $Revision$ $Date$ */ @SuppressWarnings({"serial","unchecked"}) // <- HERITRIX CHANGE public class Cookie extends NameValuePair implements Serializable, Comparator { // ----------------------------------------------------------- Constructors /** * Default constructor. Creates a blank cookie */ public Cookie() { this(null, "noname", null, null, null, false); } /** * Creates a cookie with the given name, value and domain attribute. * * @param name the cookie name * @param value the cookie value * @param domain the domain this cookie can be sent to */ public Cookie(String domain, String name, String value) { this(domain, name, value, null, null, false); } /** * Creates a cookie with the given name, value, domain attribute, * path attribute, expiration attribute, and secure attribute * * @param name the cookie name * @param value the cookie value * @param domain the domain this cookie can be sent to * @param path the path prefix for which this cookie can be sent * @param expires the {@link Date} at which this cookie expires, * or <tt>null</tt> if the cookie expires at the end * of the session * @param secure if true this cookie can only be sent over secure * connections * @throws IllegalArgumentException If cookie name is null or blank, * cookie name contains a blank, or cookie name starts with character $ * */ public Cookie(String domain, String name, String value, String path, Date expires, boolean secure) { super(name, value); LOG.trace("enter Cookie(String, String, String, String, Date, boolean)"); if (name == null) { throw new IllegalArgumentException("Cookie name may not be null"); } if (name.trim().equals("")) { throw new IllegalArgumentException("Cookie name may not be blank"); } this.setPath(path); this.setDomain(domain); this.setExpiryDate(expires); this.setSecure(secure); } /** * Creates a cookie with the given name, value, domain attribute, * path attribute, maximum age attribute, and secure attribute * * @param name the cookie name * @param value the cookie value * @param domain the domain this cookie can be sent to * @param path the path prefix for which this cookie can be sent * @param maxAge the number of seconds for which this cookie is valid. * maxAge is expected to be a non-negative number. * <tt>-1</tt> signifies that the cookie should never expire. * @param secure if <tt>true</tt> this cookie can only be sent over secure * connections */ public Cookie(String domain, String name, String value, String path, int maxAge, boolean secure) { this(domain, name, value, path, null, secure); if (maxAge < -1) { throw new IllegalArgumentException("Invalid max age: " + Integer.toString(maxAge)); } if (maxAge >= 0) { setExpiryDate(new Date(System.currentTimeMillis() + maxAge * 1000L)); } } /** * Returns the comment describing the purpose of this cookie, or * <tt>null</tt> if no such comment has been defined. * * @return comment * * @see #setComment(String) */ public String getComment() { return cookieComment; } /** * If a user agent (web browser) presents this cookie to a user, the * cookie's purpose will be described using this comment. * * @param comment * * @see #getComment() */ public void setComment(String comment) { cookieComment = comment; } /** * Returns the expiration {@link Date} of the cookie, or <tt>null</tt> * if none exists. * <p><strong>Note:</strong> the object returned by this method is * considered immutable. Changing it (e.g. using setTime()) could result * in undefined behaviour. Do so at your peril. </p> * @return Expiration {@link Date}, or <tt>null</tt>. * * @see #setExpiryDate(java.util.Date) * */ public Date getExpiryDate() { return cookieExpiryDate; } /** * Sets expiration date. * <p><strong>Note:</strong> the object returned by this method is considered * immutable. Changing it (e.g. using setTime()) could result in undefined * behaviour. Do so at your peril.</p> * * @param expiryDate the {@link Date} after which this cookie is no longer valid. * * @see #getExpiryDate * */ public void setExpiryDate (Date expiryDate) { cookieExpiryDate = expiryDate; } /** * Returns <tt>false</tt> if the cookie should be discarded at the end * of the "session"; <tt>true</tt> otherwise. * * @return <tt>false</tt> if the cookie should be discarded at the end * of the "session"; <tt>true</tt> otherwise */ public boolean isPersistent() { return (null != cookieExpiryDate); } /** * Returns domain attribute of the cookie. * * @return the value of the domain attribute * * @see #setDomain(java.lang.String) */ public String getDomain() { return cookieDomain; } /** * Sets the domain attribute. * * @param domain The value of the domain attribute * * @see #getDomain */ public void setDomain(String domain) { if (domain != null) { int ndx = domain.indexOf(":"); if (ndx != -1) { domain = domain.substring(0, ndx); } cookieDomain = domain.toLowerCase(); } } /** * Returns the path attribute of the cookie * * @return The value of the path attribute. * * @see #setPath(java.lang.String) */ public String getPath() { return cookiePath; } /** * Sets the path attribute. * * @param path The value of the path attribute * * @see #getPath * */ public void setPath(String path) { cookiePath = path; } /** * @return <code>true</code> if this cookie should only be sent over secure connections. * @see #setSecure(boolean) */ public boolean getSecure() { return isSecure; } /** * Sets the secure attribute of the cookie. * <p> * When <tt>true</tt> the cookie should only be sent * using a secure protocol (https). This should only be set when * the cookie's originating server used a secure protocol to set the * cookie's value. * * @param secure The value of the secure attribute * * @see #getSecure() */ public void setSecure (boolean secure) { isSecure = secure; } /** * Returns the version of the cookie specification to which this * cookie conforms. * * @return the version of the cookie. * * @see #setVersion(int) * */ public int getVersion() { return cookieVersion; } /** * Sets the version of the cookie specification to which this * cookie conforms. * * @param version the version of the cookie. * * @see #getVersion */ public void setVersion(int version) { cookieVersion = version; } /** * Returns true if this cookie has expired. * * @return <tt>true</tt> if the cookie has expired. */ public boolean isExpired() { return (cookieExpiryDate != null && cookieExpiryDate.getTime() <= System.currentTimeMillis()); } /** * Returns true if this cookie has expired according to the time passed in. * * @param now The current time. * * @return <tt>true</tt> if the cookie expired. */ public boolean isExpired(Date now) { return (cookieExpiryDate != null && cookieExpiryDate.getTime() <= now.getTime()); } /** * Indicates whether the cookie had a path specified in a * path attribute of the <tt>Set-Cookie</tt> header. This value * is important for generating the <tt>Cookie</tt> header because * some cookie specifications require that the <tt>Cookie</tt> header * should only include a path attribute if the cookie's path * was specified in the <tt>Set-Cookie</tt> header. * * @param value <tt>true</tt> if the cookie's path was explicitly * set, <tt>false</tt> otherwise. * * @see #isPathAttributeSpecified */ public void setPathAttributeSpecified(boolean value) { hasPathAttribute = value; } /** * Returns <tt>true</tt> if cookie's path was set via a path attribute * in the <tt>Set-Cookie</tt> header. * * @return value <tt>true</tt> if the cookie's path was explicitly * set, <tt>false</tt> otherwise. * * @see #setPathAttributeSpecified */ public boolean isPathAttributeSpecified() { return hasPathAttribute; } /** * Indicates whether the cookie had a domain specified in a * domain attribute of the <tt>Set-Cookie</tt> header. This value * is important for generating the <tt>Cookie</tt> header because * some cookie specifications require that the <tt>Cookie</tt> header * should only include a domain attribute if the cookie's domain * was specified in the <tt>Set-Cookie</tt> header. * * @param value <tt>true</tt> if the cookie's domain was explicitly * set, <tt>false</tt> otherwise. * * @see #isDomainAttributeSpecified */ public void setDomainAttributeSpecified(boolean value) { hasDomainAttribute = value; } /** * Returns <tt>true</tt> if cookie's domain was set via a domain * attribute in the <tt>Set-Cookie</tt> header. * * @return value <tt>true</tt> if the cookie's domain was explicitly * set, <tt>false</tt> otherwise. * * @see #setDomainAttributeSpecified */ public boolean isDomainAttributeSpecified() { return hasDomainAttribute; } /** * Returns a hash code in keeping with the * {@link Object#hashCode} general hashCode contract. * @return A hash code */ public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.getName()); hash = LangUtils.hashCode(hash, this.cookieDomain); hash = LangUtils.hashCode(hash, this.cookiePath); return hash; } /** * Two cookies are equal if the name, path and domain match. * @param obj The object to compare against. * @return true if the two objects are equal. */ public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (obj instanceof Cookie) { Cookie that = (Cookie) obj; return LangUtils.equals(this.getName(), that.getName()) && LangUtils.equals(this.cookieDomain, that.cookieDomain) && LangUtils.equals(this.cookiePath, that.cookiePath); } else { return false; } } /** * Return a textual representation of the cookie. * * @return string. */ public String toExternalForm() { CookieSpec spec = null; if (getVersion() > 0) { spec = CookiePolicy.getDefaultSpec(); } else { spec = CookiePolicy.getCookieSpec(CookiePolicy.NETSCAPE); } return spec.formatCookie(this); } /** * <p>Compares two cookies to determine order for cookie header.</p> * <p>Most specific should be first. </p> * <p>This method is implemented so a cookie can be used as a comparator for * a SortedSet of cookies. Specifically it's used above in the * createCookieHeader method.</p> * @param o1 The first object to be compared * @param o2 The second object to be compared * @return See {@link java.util.Comparator#compare(Object,Object)} */ public int compare(Object o1, Object o2) { LOG.trace("enter Cookie.compare(Object, Object)"); if (!(o1 instanceof Cookie)) { throw new ClassCastException(o1.getClass().getName()); } if (!(o2 instanceof Cookie)) { throw new ClassCastException(o2.getClass().getName()); } Cookie c1 = (Cookie) o1; Cookie c2 = (Cookie) o2; if (c1.getPath() == null && c2.getPath() == null) { return 0; } else if (c1.getPath() == null) { // null is assumed to be "/" if (c2.getPath().equals(CookieSpec.PATH_DELIM)) { return 0; } else { return -1; } } else if (c2.getPath() == null) { // null is assumed to be "/" if (c1.getPath().equals(CookieSpec.PATH_DELIM)) { return 0; } else { return 1; } } else { - return STRING_COLLATOR.compare(c1.getPath(), c2.getPath()); +// BEGIN IA/HERITRIX CHANGE +// based on: https://cwiki.apache.org/jira/browse/HTTPCLIENT-645 + return c1.getPath().compareTo(c2.getPath()); +// return STRING_COLLATOR.compare(c1.getPath(), c2.getPath()); +// END IA/HERITRIX CHANGE } } /** * Return a textual representation of the cookie. * * @return string. * * @see #toExternalForm */ public String toString() { return toExternalForm(); } // BEGIN IA/HERITRIX ADDITION /** * Create a 'sort key' for this Cookie that will cause it to sort * alongside other Cookies of the same domain (with or without leading * '.'). This helps cookie-match checks consider only narrow set of * possible matches, rather than all cookies. * * Only two cookies that are equals() (same domain, path, name) will have * the same sort key. The '\1' separator character is important in * conjunction with Cookie.DOMAIN+OVERBOUNDS, allowing keys based on the * domain plus an extension to define the relevant range in a SortedMap. * @return String sort key for this cookie */ public String getSortKey() { String domain = getDomain(); return (domain.startsWith(".")) ? domain.substring(1) + "\1.\1" + getPath() + "\1" + getName() : domain + "\1\1" + getPath() + "\1" + getName(); } // END IA/HERITRIX ADDITION // ----------------------------------------------------- Instance Variables /** Comment attribute. */ private String cookieComment; /** Domain attribute. */ private String cookieDomain; /** Expiration {@link Date}. */ private Date cookieExpiryDate; /** Path attribute. */ private String cookiePath; /** My secure flag. */ private boolean isSecure; /** * Specifies if the set-cookie header included a Path attribute for this * cookie */ private boolean hasPathAttribute = false; /** * Specifies if the set-cookie header included a Domain attribute for this * cookie */ private boolean hasDomainAttribute = false; /** The version of the cookie specification I was created from. */ private int cookieVersion = 0; // -------------------------------------------------------------- Constants /** * Collator for Cookie comparisons. Could be replaced with references to * specific Locales. */ private static final RuleBasedCollator STRING_COLLATOR = (RuleBasedCollator) RuleBasedCollator.getInstance( new Locale("en", "US", "")); /** Log object for this class */ private static final Log LOG = LogFactory.getLog(Cookie.class); // BEGIN IA/HERITRIX ADDITION /** * Character which, if appended to end of a domain, will give a * boundary key that sorts past all Cookie sortKeys for the same * domain. */ public static final char DOMAIN_OVERBOUNDS = '\2'; // END IA/HERITRIX ADDITION }
true
true
public int compare(Object o1, Object o2) { LOG.trace("enter Cookie.compare(Object, Object)"); if (!(o1 instanceof Cookie)) { throw new ClassCastException(o1.getClass().getName()); } if (!(o2 instanceof Cookie)) { throw new ClassCastException(o2.getClass().getName()); } Cookie c1 = (Cookie) o1; Cookie c2 = (Cookie) o2; if (c1.getPath() == null && c2.getPath() == null) { return 0; } else if (c1.getPath() == null) { // null is assumed to be "/" if (c2.getPath().equals(CookieSpec.PATH_DELIM)) { return 0; } else { return -1; } } else if (c2.getPath() == null) { // null is assumed to be "/" if (c1.getPath().equals(CookieSpec.PATH_DELIM)) { return 0; } else { return 1; } } else { return STRING_COLLATOR.compare(c1.getPath(), c2.getPath()); } }
public int compare(Object o1, Object o2) { LOG.trace("enter Cookie.compare(Object, Object)"); if (!(o1 instanceof Cookie)) { throw new ClassCastException(o1.getClass().getName()); } if (!(o2 instanceof Cookie)) { throw new ClassCastException(o2.getClass().getName()); } Cookie c1 = (Cookie) o1; Cookie c2 = (Cookie) o2; if (c1.getPath() == null && c2.getPath() == null) { return 0; } else if (c1.getPath() == null) { // null is assumed to be "/" if (c2.getPath().equals(CookieSpec.PATH_DELIM)) { return 0; } else { return -1; } } else if (c2.getPath() == null) { // null is assumed to be "/" if (c1.getPath().equals(CookieSpec.PATH_DELIM)) { return 0; } else { return 1; } } else { // BEGIN IA/HERITRIX CHANGE // based on: https://cwiki.apache.org/jira/browse/HTTPCLIENT-645 return c1.getPath().compareTo(c2.getPath()); // return STRING_COLLATOR.compare(c1.getPath(), c2.getPath()); // END IA/HERITRIX CHANGE } }
diff --git a/plugins/org.xwiki.eclipse.ui/src/main/java/org/xwiki/eclipse/ui/wizards/NewConnectionWizard.java b/plugins/org.xwiki.eclipse.ui/src/main/java/org/xwiki/eclipse/ui/wizards/NewConnectionWizard.java index 03ad91e..5004bd0 100644 --- a/plugins/org.xwiki.eclipse.ui/src/main/java/org/xwiki/eclipse/ui/wizards/NewConnectionWizard.java +++ b/plugins/org.xwiki.eclipse.ui/src/main/java/org/xwiki/eclipse/ui/wizards/NewConnectionWizard.java @@ -1,201 +1,205 @@ /* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package org.xwiki.eclipse.ui.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExecutableExtension; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.ui.INewWizard; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard; import org.xwiki.eclipse.core.XWikiEclipseNature; import org.xwiki.eclipse.storage.DataManager; import org.xwiki.eclipse.storage.XWikiClient; import org.xwiki.eclipse.storage.utils.StorageUtils; import org.xwiki.eclipse.ui.perspectives.XWikiPerspectiveFactory; /** * @version $Id$ */ public class NewConnectionWizard extends Wizard implements INewWizard, IExecutableExtension { /* * The Wizard's ID */ public final static String WIZARD_ID = "org.xwiki.eclipse.ui.wizards.NewConnection"; /* * The ConfigurationElement required to activate the XWiki Eclipse perspective after finishing creating the new * connection. */ private IConfigurationElement config; private NewConnectionWizardState newConnectionWizardState; public NewConnectionWizard() { super(); newConnectionWizardState = new NewConnectionWizardState(); setNeedsProgressMonitor(true); } @Override public void addPages() { addPage(new ConnectionSettingsWizardPage("Connection settings")); } @Override public boolean canFinish() { if (newConnectionWizardState.getConnectionName() == null || newConnectionWizardState.getConnectionName().length() == 0) { return false; } if (newConnectionWizardState.getServerUrl() == null || newConnectionWizardState.getServerUrl().length() == 0) { return false; } if (newConnectionWizardState.getUserName() == null || newConnectionWizardState.getUserName().length() == 0) { return false; } if (newConnectionWizardState.getPassword() == null || newConnectionWizardState.getPassword().length() == 0) { return false; } return super.canFinish(); } @Override public boolean performFinish() { WizardPage currentPage = (WizardPage) getContainer().getCurrentPage(); try { getContainer().run(true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { monitor.beginTask("Setting up connection", IProgressMonitor.UNKNOWN); /* Try to login with the specified username + password */ XWikiClient client = new XWikiClient(newConnectionWizardState.getServerUrl(), newConnectionWizardState .getUserName(), newConnectionWizardState.getPassword()); client.login(newConnectionWizardState.getUserName(), newConnectionWizardState.getPassword()); client.logout(); } catch (Exception e) { throw new InvocationTargetException(e, e.getMessage()); } finally { monitor.done(); } } }); } catch (Exception e) { e.printStackTrace(); currentPage.setErrorMessage(String.format( "Error connecting to remote XWiki: '%s'. Please check your settings.", e.getMessage())); return false; } /* Create a workbench project containing connection data */ try { getContainer().run(true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IProject project = workspaceRoot.getProject(newConnectionWizardState.getConnectionName()); if (project.exists()) { return; } project.create(null); project.open(null); project.setPersistentProperty(DataManager.BACKEND, StorageUtils.getBackend(newConnectionWizardState.getServerUrl()).toString()); project.setPersistentProperty(DataManager.ENDPOINT, newConnectionWizardState.getServerUrl()); - project.setPersistentProperty(DataManager.USERNAME, newConnectionWizardState.getUserName()); + String userName = newConnectionWizardState.getUserName(); + if (!userName.startsWith("XWiki.")) { + userName = "XWiki." + userName; + } + project.setPersistentProperty(DataManager.USERNAME, userName); project.setPersistentProperty(DataManager.PASSWORD, newConnectionWizardState.getPassword()); project.setPersistentProperty(DataManager.AUTO_CONNECT, "true"); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] {XWikiEclipseNature.ID}); project.setDescription(description, null); ResourcesPlugin.getWorkspace().save(true, new NullProgressMonitor()); } catch (Exception e) { throw new InvocationTargetException(e, e.getMessage()); } } }); } catch (Exception e) { currentPage.setErrorMessage(String.format("Error creating project data: '%s'.", e.getMessage())); return false; } if (!PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getPerspective().getId() .equals(XWikiPerspectiveFactory.PERSPECTIVE_ID)) { // Ask the user to switch to XWiki Eclipse perspective. BasicNewProjectResourceWizard.updatePerspective(config); } return true; } public void init(IWorkbench workbench, IStructuredSelection selection) { // Empty method. } public NewConnectionWizardState getNewConnectionWizardState() { return newConnectionWizardState; } public void setInitializationData(IConfigurationElement config, String propertyName, Object data) throws CoreException { // Store the ConfigurationElement to use later when calling updatePerspective(). this.config = config; } }
true
true
public boolean performFinish() { WizardPage currentPage = (WizardPage) getContainer().getCurrentPage(); try { getContainer().run(true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { monitor.beginTask("Setting up connection", IProgressMonitor.UNKNOWN); /* Try to login with the specified username + password */ XWikiClient client = new XWikiClient(newConnectionWizardState.getServerUrl(), newConnectionWizardState .getUserName(), newConnectionWizardState.getPassword()); client.login(newConnectionWizardState.getUserName(), newConnectionWizardState.getPassword()); client.logout(); } catch (Exception e) { throw new InvocationTargetException(e, e.getMessage()); } finally { monitor.done(); } } }); } catch (Exception e) { e.printStackTrace(); currentPage.setErrorMessage(String.format( "Error connecting to remote XWiki: '%s'. Please check your settings.", e.getMessage())); return false; } /* Create a workbench project containing connection data */ try { getContainer().run(true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IProject project = workspaceRoot.getProject(newConnectionWizardState.getConnectionName()); if (project.exists()) { return; } project.create(null); project.open(null); project.setPersistentProperty(DataManager.BACKEND, StorageUtils.getBackend(newConnectionWizardState.getServerUrl()).toString()); project.setPersistentProperty(DataManager.ENDPOINT, newConnectionWizardState.getServerUrl()); project.setPersistentProperty(DataManager.USERNAME, newConnectionWizardState.getUserName()); project.setPersistentProperty(DataManager.PASSWORD, newConnectionWizardState.getPassword()); project.setPersistentProperty(DataManager.AUTO_CONNECT, "true"); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] {XWikiEclipseNature.ID}); project.setDescription(description, null); ResourcesPlugin.getWorkspace().save(true, new NullProgressMonitor()); } catch (Exception e) { throw new InvocationTargetException(e, e.getMessage()); } } }); } catch (Exception e) { currentPage.setErrorMessage(String.format("Error creating project data: '%s'.", e.getMessage())); return false; } if (!PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getPerspective().getId() .equals(XWikiPerspectiveFactory.PERSPECTIVE_ID)) { // Ask the user to switch to XWiki Eclipse perspective. BasicNewProjectResourceWizard.updatePerspective(config); } return true; }
public boolean performFinish() { WizardPage currentPage = (WizardPage) getContainer().getCurrentPage(); try { getContainer().run(true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { monitor.beginTask("Setting up connection", IProgressMonitor.UNKNOWN); /* Try to login with the specified username + password */ XWikiClient client = new XWikiClient(newConnectionWizardState.getServerUrl(), newConnectionWizardState .getUserName(), newConnectionWizardState.getPassword()); client.login(newConnectionWizardState.getUserName(), newConnectionWizardState.getPassword()); client.logout(); } catch (Exception e) { throw new InvocationTargetException(e, e.getMessage()); } finally { monitor.done(); } } }); } catch (Exception e) { e.printStackTrace(); currentPage.setErrorMessage(String.format( "Error connecting to remote XWiki: '%s'. Please check your settings.", e.getMessage())); return false; } /* Create a workbench project containing connection data */ try { getContainer().run(true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IProject project = workspaceRoot.getProject(newConnectionWizardState.getConnectionName()); if (project.exists()) { return; } project.create(null); project.open(null); project.setPersistentProperty(DataManager.BACKEND, StorageUtils.getBackend(newConnectionWizardState.getServerUrl()).toString()); project.setPersistentProperty(DataManager.ENDPOINT, newConnectionWizardState.getServerUrl()); String userName = newConnectionWizardState.getUserName(); if (!userName.startsWith("XWiki.")) { userName = "XWiki." + userName; } project.setPersistentProperty(DataManager.USERNAME, userName); project.setPersistentProperty(DataManager.PASSWORD, newConnectionWizardState.getPassword()); project.setPersistentProperty(DataManager.AUTO_CONNECT, "true"); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] {XWikiEclipseNature.ID}); project.setDescription(description, null); ResourcesPlugin.getWorkspace().save(true, new NullProgressMonitor()); } catch (Exception e) { throw new InvocationTargetException(e, e.getMessage()); } } }); } catch (Exception e) { currentPage.setErrorMessage(String.format("Error creating project data: '%s'.", e.getMessage())); return false; } if (!PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getPerspective().getId() .equals(XWikiPerspectiveFactory.PERSPECTIVE_ID)) { // Ask the user to switch to XWiki Eclipse perspective. BasicNewProjectResourceWizard.updatePerspective(config); } return true; }
diff --git a/webapp/src/main/java/com/seo/webapp/Query.java b/webapp/src/main/java/com/seo/webapp/Query.java index 19d7b9b..5600683 100644 --- a/webapp/src/main/java/com/seo/webapp/Query.java +++ b/webapp/src/main/java/com/seo/webapp/Query.java @@ -1,41 +1,41 @@ package com.seo.webapp; import java.net.*; import java.io.*; public class Query { private String m_query; private String m_siteToCompare = "Shopzilla"; public String HTTP_Request() throws Exception { URL url = new URL("http://localhost:5000/"); URLConnection uc = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); - String inputLine = ""; - String prev = ""; + String inputLine = ""; + String prev = ""; - while ( (inputLine = in.readLine()) != null) { + while ( (inputLine = in.readLine()) != null ) { System.out.println(inputLine); prev = inputLine; } in.close(); return prev; } public String getQuery() { return m_query; } public void setQuery(String query) { m_query = query; } public String getSiteToCompare() { return m_siteToCompare; } public void setSiteToCompare(String siteToCompare) { m_siteToCompare = siteToCompare; } }
false
true
public String HTTP_Request() throws Exception { URL url = new URL("http://localhost:5000/"); URLConnection uc = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String inputLine = ""; String prev = ""; while ( (inputLine = in.readLine()) != null) { System.out.println(inputLine); prev = inputLine; } in.close(); return prev; }
public String HTTP_Request() throws Exception { URL url = new URL("http://localhost:5000/"); URLConnection uc = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String inputLine = ""; String prev = ""; while ( (inputLine = in.readLine()) != null ) { System.out.println(inputLine); prev = inputLine; } in.close(); return prev; }
diff --git a/src/simulation/eventHandlers/StartTakeOffHandler.java b/src/simulation/eventHandlers/StartTakeOffHandler.java index 8263bf8..eb6ab31 100644 --- a/src/simulation/eventHandlers/StartTakeOffHandler.java +++ b/src/simulation/eventHandlers/StartTakeOffHandler.java @@ -1,66 +1,67 @@ package simulation.eventHandlers; import simulation.definition.EventScheduler; import simulation.definition.TransactionalEventHandler; import simulation.model.Aircraft; import simulation.model.Airport; import simulation.model.Event; import simulation.model.RollBackVariables; public class StartTakeOffHandler implements TransactionalEventHandler { static private final String KEY_LAST_TIME = "LAST_TIME"; static private final String KEY_TIMESTAMP = "TIMESTAMP"; @Override public void process(Event e, EventScheduler scheduler) { final Aircraft ac = e.getAirCraft(); final Airport ap = e.getAirPort(); ac.setState(Aircraft.TAKING_OFF); ac.setLastTime(e.getTimeStamp()); RollBackVariables rv = new RollBackVariables(StartTakeOffHandler.KEY_LAST_TIME, e.getTimeStamp()); + e.setRollBackVariable(rv); // we assume a constant acceleration maxAcceleration long takeOffDuration = Aircraft.MAX_SPEED / Aircraft.MAX_ACCEL; // distance for the accelerating part: double dist = Aircraft.MAX_ACCEL * takeOffDuration * takeOffDuration / 2.0; // the remaining part double remainingDist = ap.getRunwayLength() - dist; // the remaining distance of the runway we have constant speed if (remainingDist > 0) { takeOffDuration += remainingDist / Aircraft.MAX_SPEED; } else { throw new RuntimeException("runway too short!!"); } // schedule next event // to do! long eventTimeStamp = e.getTimeStamp() + takeOffDuration; Event eNew = new Event(Event.END_TAKE_OFF, eventTimeStamp, ap, ac); rv.setValue(StartTakeOffHandler.KEY_TIMESTAMP, eventTimeStamp); scheduler.scheduleEvent(eNew); } @Override public void rollback(Event e, EventScheduler scheduler) { Aircraft ac = e.getAirCraft(); Airport ap = e.getAirPort(); //rollback airplane state ac.setState(Event.READY_FOR_DEPARTURE); ac.setLastTime(e.getRollBackVariable().getLongValue(StartTakeOffHandler.KEY_LAST_TIME)); //remove event from event List Event endTakeOffEvent = new Event( Event.END_TAKE_OFF, e.getRollBackVariable().getLongValue(StartTakeOffHandler.KEY_TIMESTAMP), ap, ac ); endTakeOffEvent.setAntiMessage(true); scheduler.scheduleEvent(endTakeOffEvent); } }
true
true
public void process(Event e, EventScheduler scheduler) { final Aircraft ac = e.getAirCraft(); final Airport ap = e.getAirPort(); ac.setState(Aircraft.TAKING_OFF); ac.setLastTime(e.getTimeStamp()); RollBackVariables rv = new RollBackVariables(StartTakeOffHandler.KEY_LAST_TIME, e.getTimeStamp()); // we assume a constant acceleration maxAcceleration long takeOffDuration = Aircraft.MAX_SPEED / Aircraft.MAX_ACCEL; // distance for the accelerating part: double dist = Aircraft.MAX_ACCEL * takeOffDuration * takeOffDuration / 2.0; // the remaining part double remainingDist = ap.getRunwayLength() - dist; // the remaining distance of the runway we have constant speed if (remainingDist > 0) { takeOffDuration += remainingDist / Aircraft.MAX_SPEED; } else { throw new RuntimeException("runway too short!!"); } // schedule next event // to do! long eventTimeStamp = e.getTimeStamp() + takeOffDuration; Event eNew = new Event(Event.END_TAKE_OFF, eventTimeStamp, ap, ac); rv.setValue(StartTakeOffHandler.KEY_TIMESTAMP, eventTimeStamp); scheduler.scheduleEvent(eNew); }
public void process(Event e, EventScheduler scheduler) { final Aircraft ac = e.getAirCraft(); final Airport ap = e.getAirPort(); ac.setState(Aircraft.TAKING_OFF); ac.setLastTime(e.getTimeStamp()); RollBackVariables rv = new RollBackVariables(StartTakeOffHandler.KEY_LAST_TIME, e.getTimeStamp()); e.setRollBackVariable(rv); // we assume a constant acceleration maxAcceleration long takeOffDuration = Aircraft.MAX_SPEED / Aircraft.MAX_ACCEL; // distance for the accelerating part: double dist = Aircraft.MAX_ACCEL * takeOffDuration * takeOffDuration / 2.0; // the remaining part double remainingDist = ap.getRunwayLength() - dist; // the remaining distance of the runway we have constant speed if (remainingDist > 0) { takeOffDuration += remainingDist / Aircraft.MAX_SPEED; } else { throw new RuntimeException("runway too short!!"); } // schedule next event // to do! long eventTimeStamp = e.getTimeStamp() + takeOffDuration; Event eNew = new Event(Event.END_TAKE_OFF, eventTimeStamp, ap, ac); rv.setValue(StartTakeOffHandler.KEY_TIMESTAMP, eventTimeStamp); scheduler.scheduleEvent(eNew); }
diff --git a/src/main/java/jline/console/completer/FileNameCompleter.java b/src/main/java/jline/console/completer/FileNameCompleter.java index 1ab5f9a..edb97c7 100644 --- a/src/main/java/jline/console/completer/FileNameCompleter.java +++ b/src/main/java/jline/console/completer/FileNameCompleter.java @@ -1,131 +1,131 @@ /* * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved. * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. */ package jline.console.completer; import java.io.File; import java.util.List; /** * A file name completer takes the buffer and issues a list of * potential completions. * <p/> * This completer tries to behave as similar as possible to * <i>bash</i>'s file name completion (using GNU readline) * with the following exceptions: * <p/> * <ul> * <li>Candidates that are directories will end with "/"</li> * <li>Wildcard regular expressions are not evaluated or replaced</li> * <li>The "~" character can be used to represent the user's home, * but it cannot complete to other users' homes, since java does * not provide any way of determining that easily</li> * </ul> * * @author <a href="mailto:[email protected]">Marc Prud'hommeaux</a> * @author <a href="mailto:[email protected]">Jason Dillon</a> * @since 2.3 */ public class FileNameCompleter implements Completer { // TODO: Handle files with spaces in them private static final boolean OS_IS_WINDOWS; static { String os = System.getProperty("os.name").toLowerCase(); OS_IS_WINDOWS = os.contains("windows"); } public int complete(String buffer, final int cursor, final List<CharSequence> candidates) { // buffer can be null assert candidates != null; if (buffer == null) { buffer = ""; } if (OS_IS_WINDOWS) { buffer = buffer.replace('/', '\\'); } String translated = buffer; File homeDir = getUserHome(); // Special character: ~ maps to the user's home directory if (translated.startsWith("~" + separator())) { translated = homeDir.getPath() + translated.substring(1); } else if (translated.startsWith("~")) { translated = homeDir.getParentFile().getAbsolutePath(); } else if (!(translated.startsWith(separator()))) { - String cwd = getUserDir().getPath(); + String cwd = getUserDir().getAbsolutePath(); translated = cwd + separator() + translated; } File file = new File(translated); final File dir; if (translated.endsWith(separator())) { dir = file; } else { dir = file.getParentFile(); } File[] entries = dir == null ? new File[0] : dir.listFiles(); return matchFiles(buffer, translated, entries, candidates); } protected String separator() { return File.separator; } protected File getUserHome() { return new File(System.getProperty("user.home")); } protected File getUserDir() { return new File("."); } protected int matchFiles(final String buffer, final String translated, final File[] files, final List<CharSequence> candidates) { if (files == null) { return -1; } int matches = 0; // first pass: just count the matches for (File file : files) { if (file.getAbsolutePath().startsWith(translated)) { matches++; } } for (File file : files) { if (file.getAbsolutePath().startsWith(translated)) { CharSequence name = file.getName() + (matches == 1 && file.isDirectory() ? separator() : " "); candidates.add(render(file, name).toString()); } } final int index = buffer.lastIndexOf(separator()); return index + separator().length(); } protected CharSequence render(final File file, final CharSequence name) { assert file != null; assert name != null; return name; } }
true
true
public int complete(String buffer, final int cursor, final List<CharSequence> candidates) { // buffer can be null assert candidates != null; if (buffer == null) { buffer = ""; } if (OS_IS_WINDOWS) { buffer = buffer.replace('/', '\\'); } String translated = buffer; File homeDir = getUserHome(); // Special character: ~ maps to the user's home directory if (translated.startsWith("~" + separator())) { translated = homeDir.getPath() + translated.substring(1); } else if (translated.startsWith("~")) { translated = homeDir.getParentFile().getAbsolutePath(); } else if (!(translated.startsWith(separator()))) { String cwd = getUserDir().getPath(); translated = cwd + separator() + translated; } File file = new File(translated); final File dir; if (translated.endsWith(separator())) { dir = file; } else { dir = file.getParentFile(); } File[] entries = dir == null ? new File[0] : dir.listFiles(); return matchFiles(buffer, translated, entries, candidates); }
public int complete(String buffer, final int cursor, final List<CharSequence> candidates) { // buffer can be null assert candidates != null; if (buffer == null) { buffer = ""; } if (OS_IS_WINDOWS) { buffer = buffer.replace('/', '\\'); } String translated = buffer; File homeDir = getUserHome(); // Special character: ~ maps to the user's home directory if (translated.startsWith("~" + separator())) { translated = homeDir.getPath() + translated.substring(1); } else if (translated.startsWith("~")) { translated = homeDir.getParentFile().getAbsolutePath(); } else if (!(translated.startsWith(separator()))) { String cwd = getUserDir().getAbsolutePath(); translated = cwd + separator() + translated; } File file = new File(translated); final File dir; if (translated.endsWith(separator())) { dir = file; } else { dir = file.getParentFile(); } File[] entries = dir == null ? new File[0] : dir.listFiles(); return matchFiles(buffer, translated, entries, candidates); }
diff --git a/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/StandardVMDebugger.java b/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/StandardVMDebugger.java index f5f6a009d..2d3bca05b 100644 --- a/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/StandardVMDebugger.java +++ b/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/StandardVMDebugger.java @@ -1,355 +1,359 @@ /******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.launching; import java.io.File; import java.io.IOException; import java.io.InterruptedIOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.IStatusHandler; import org.eclipse.debug.core.model.IProcess; import org.eclipse.debug.core.model.IStreamsProxy; import org.eclipse.jdi.Bootstrap; import org.eclipse.jdt.debug.core.JDIDebugModel; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jdt.launching.IVMInstall; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.launching.SocketUtil; import org.eclipse.jdt.launching.VMRunnerConfiguration; import com.sun.jdi.VirtualMachine; import com.sun.jdi.connect.Connector; import com.sun.jdi.connect.IllegalConnectorArgumentsException; import com.sun.jdi.connect.ListeningConnector; /** * A launcher for running Java main classes. Uses JDI to launch a vm in debug * mode. */ public class StandardVMDebugger extends StandardVMRunner { /** * Used to attach to a VM in a seperate thread, to allow for cancellation * and detect that the associated System process died before the connect * occurred. */ class ConnectRunnable implements Runnable { private VirtualMachine fVirtualMachine = null; private ListeningConnector fConnector = null; private Map fConnectionMap = null; private Exception fException = null; /** * Constructs a runnable to connect to a VM via the given connector * with the given connection arguments. * * @param connector * @param map */ public ConnectRunnable(ListeningConnector connector, Map map) { fConnector = connector; fConnectionMap = map; } public void run() { try { fVirtualMachine = fConnector.accept(fConnectionMap); } catch (IOException e) { fException = e; } catch (IllegalConnectorArgumentsException e) { fException = e; } } /** * Returns the VM that was attached to, or <code>null</code> if none. * * @return the VM that was attached to, or <code>null</code> if none */ public VirtualMachine getVirtualMachine() { return fVirtualMachine; } /** * Returns any exception that occurred while attaching, or <code>null</code>. * * @return IOException or IllegalConnectorArgumentsException */ public Exception getException() { return fException; } } /** * Creates a new launcher */ public StandardVMDebugger(IVMInstall vmInstance) { super(vmInstance); } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IVMRunner#run(org.eclipse.jdt.launching.VMRunnerConfiguration, org.eclipse.debug.core.ILaunch, org.eclipse.core.runtime.IProgressMonitor) */ public void run(VMRunnerConfiguration config, ILaunch launch, IProgressMonitor monitor) throws CoreException { if (monitor == null) { monitor = new NullProgressMonitor(); } IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1); subMonitor.beginTask(LaunchingMessages.StandardVMDebugger_Launching_VM____1, 4); subMonitor.subTask(LaunchingMessages.StandardVMDebugger_Finding_free_socket____2); int port= SocketUtil.findFreePort(); if (port == -1) { abort(LaunchingMessages.StandardVMDebugger_Could_not_find_a_free_socket_for_the_debugger_1, null, IJavaLaunchConfigurationConstants.ERR_NO_SOCKET_AVAILABLE); } subMonitor.worked(1); // check for cancellation if (monitor.isCanceled()) { return; } subMonitor.subTask(LaunchingMessages.StandardVMDebugger_Constructing_command_line____3); String program= constructProgramString(config); List arguments= new ArrayList(12); arguments.add(program); // VM args are the first thing after the java program so that users can specify // options like '-client' & '-server' which are required to be the first options String[] allVMArgs = combineVmArgs(config, fVMInstance); addArguments(allVMArgs, arguments); addBootClassPathArguments(arguments, config); String[] cp= config.getClassPath(); if (cp.length > 0) { arguments.add("-classpath"); //$NON-NLS-1$ arguments.add(convertClassPath(cp)); } double version = getJavaVersion(); if (version < 1.5) { arguments.add("-Xdebug"); //$NON-NLS-1$ arguments.add("-Xnoagent"); //$NON-NLS-1$ } //check if java 1.4 or greater if (version < 1.4) { arguments.add("-Djava.compiler=NONE"); //$NON-NLS-1$ } if (version < 1.5) { arguments.add("-Xrunjdwp:transport=dt_socket,suspend=y,address=localhost:" + port); //$NON-NLS-1$ } else { arguments.add("-agentlib:jdwp=transport=dt_socket,suspend=y,address=localhost:" + port); //$NON-NLS-1$ } arguments.add(config.getClassToLaunch()); addArguments(config.getProgramArguments(), arguments); String[] cmdLine= new String[arguments.size()]; arguments.toArray(cmdLine); String[] envp= config.getEnvironment(); // check for cancellation if (monitor.isCanceled()) { return; } subMonitor.worked(1); subMonitor.subTask(LaunchingMessages.StandardVMDebugger_Starting_virtual_machine____4); ListeningConnector connector= getConnector(); if (connector == null) { abort(LaunchingMessages.StandardVMDebugger_Couldn__t_find_an_appropriate_debug_connector_2, null, IJavaLaunchConfigurationConstants.ERR_CONNECTOR_NOT_AVAILABLE); } Map map= connector.defaultArguments(); specifyArguments(map, port); Process p= null; try { try { // check for cancellation if (monitor.isCanceled()) { return; } connector.startListening(map); File workingDir = getWorkingDir(config); p = exec(cmdLine, workingDir, envp); if (p == null) { return; } // check for cancellation if (monitor.isCanceled()) { p.destroy(); return; } IProcess process= newProcess(launch, p, renderProcessLabel(cmdLine), getDefaultProcessMap()); process.setAttribute(IProcess.ATTR_CMDLINE, renderCommandLine(cmdLine)); subMonitor.worked(1); subMonitor.subTask(LaunchingMessages.StandardVMDebugger_Establishing_debug_connection____5); boolean retry= false; do { try { ConnectRunnable runnable = new ConnectRunnable(connector, map); Thread connectThread = new Thread(runnable, "Listening Connector"); //$NON-NLS-1$ connectThread.setDaemon(true); connectThread.start(); while (connectThread.isAlive()) { if (monitor.isCanceled()) { - connector.stopListening(map); + try { + connector.stopListening(map); + } catch (IOException ioe) { + //expected + } p.destroy(); return; } try { p.exitValue(); // process has terminated - stop waiting for a connection try { connector.stopListening(map); } catch (IOException e) { // expected } checkErrorMessage(process); } catch (IllegalThreadStateException e) { // expected while process is alive } try { Thread.sleep(100); } catch (InterruptedException e) { } } Exception ex = runnable.getException(); - if (ex instanceof IllegalConnectorArgumentsException) { + if (ex instanceof IllegalConnectorArgumentsException) { throw (IllegalConnectorArgumentsException)ex; } if (ex instanceof InterruptedIOException) { throw (InterruptedIOException)ex; } if (ex instanceof IOException) { throw (IOException)ex; } VirtualMachine vm= runnable.getVirtualMachine(); if (vm != null) { JDIDebugModel.newDebugTarget(launch, vm, renderDebugTarget(config.getClassToLaunch(), port), process, true, false, config.isResumeOnStartup()); subMonitor.worked(1); subMonitor.done(); } return; } catch (InterruptedIOException e) { checkErrorMessage(process); // timeout, consult status handler if there is one IStatus status = new Status(IStatus.ERROR, LaunchingPlugin.getUniqueIdentifier(), IJavaLaunchConfigurationConstants.ERR_VM_CONNECT_TIMEOUT, "", e); //$NON-NLS-1$ IStatusHandler handler = DebugPlugin.getDefault().getStatusHandler(status); retry= false; if (handler == null) { // if there is no handler, throw the exception throw new CoreException(status); } Object result = handler.handleStatus(status, this); if (result instanceof Boolean) { retry = ((Boolean)result).booleanValue(); } } } while (retry); } finally { connector.stopListening(map); } } catch (IOException e) { abort(LaunchingMessages.StandardVMDebugger_Couldn__t_connect_to_VM_4, e, IJavaLaunchConfigurationConstants.ERR_CONNECTION_FAILED); } catch (IllegalConnectorArgumentsException e) { abort(LaunchingMessages.StandardVMDebugger_Couldn__t_connect_to_VM_5, e, IJavaLaunchConfigurationConstants.ERR_CONNECTION_FAILED); } if (p != null) { p.destroy(); } } private double getJavaVersion() { LibraryInfo libInfo = LaunchingPlugin.getLibraryInfo(fVMInstance.getInstallLocation().getAbsolutePath()); if (libInfo == null) { return 0D; } String version = libInfo.getVersion(); int index = version.indexOf("."); //$NON-NLS-1$ int nextIndex = version.indexOf(".", index+1); //$NON-NLS-1$ try { if (index > 0 && nextIndex>index) { return Double.parseDouble(version.substring(0,nextIndex)); } return Double.parseDouble(version); } catch (NumberFormatException e) { return 0D; } } protected void checkErrorMessage(IProcess process) throws CoreException { IStreamsProxy streamsProxy = process.getStreamsProxy(); if (streamsProxy != null) { String errorMessage= streamsProxy.getErrorStreamMonitor().getContents(); if (errorMessage.length() == 0) { errorMessage= streamsProxy.getOutputStreamMonitor().getContents(); } if (errorMessage.length() != 0) { abort(errorMessage, null, IJavaLaunchConfigurationConstants.ERR_VM_LAUNCH_ERROR); } } } protected void specifyArguments(Map map, int portNumber) { // XXX: Revisit - allows us to put a quote (") around the classpath Connector.IntegerArgument port= (Connector.IntegerArgument) map.get("port"); //$NON-NLS-1$ port.setValue(portNumber); Connector.IntegerArgument timeoutArg= (Connector.IntegerArgument) map.get("timeout"); //$NON-NLS-1$ if (timeoutArg != null) { int timeout = JavaRuntime.getPreferences().getInt(JavaRuntime.PREF_CONNECT_TIMEOUT); timeoutArg.setValue(timeout); } } protected ListeningConnector getConnector() { List connectors= Bootstrap.virtualMachineManager().listeningConnectors(); for (int i= 0; i < connectors.size(); i++) { ListeningConnector c= (ListeningConnector) connectors.get(i); if ("com.sun.jdi.SocketListen".equals(c.name())) //$NON-NLS-1$ return c; } return null; } }
false
true
public void run(VMRunnerConfiguration config, ILaunch launch, IProgressMonitor monitor) throws CoreException { if (monitor == null) { monitor = new NullProgressMonitor(); } IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1); subMonitor.beginTask(LaunchingMessages.StandardVMDebugger_Launching_VM____1, 4); subMonitor.subTask(LaunchingMessages.StandardVMDebugger_Finding_free_socket____2); int port= SocketUtil.findFreePort(); if (port == -1) { abort(LaunchingMessages.StandardVMDebugger_Could_not_find_a_free_socket_for_the_debugger_1, null, IJavaLaunchConfigurationConstants.ERR_NO_SOCKET_AVAILABLE); } subMonitor.worked(1); // check for cancellation if (monitor.isCanceled()) { return; } subMonitor.subTask(LaunchingMessages.StandardVMDebugger_Constructing_command_line____3); String program= constructProgramString(config); List arguments= new ArrayList(12); arguments.add(program); // VM args are the first thing after the java program so that users can specify // options like '-client' & '-server' which are required to be the first options String[] allVMArgs = combineVmArgs(config, fVMInstance); addArguments(allVMArgs, arguments); addBootClassPathArguments(arguments, config); String[] cp= config.getClassPath(); if (cp.length > 0) { arguments.add("-classpath"); //$NON-NLS-1$ arguments.add(convertClassPath(cp)); } double version = getJavaVersion(); if (version < 1.5) { arguments.add("-Xdebug"); //$NON-NLS-1$ arguments.add("-Xnoagent"); //$NON-NLS-1$ } //check if java 1.4 or greater if (version < 1.4) { arguments.add("-Djava.compiler=NONE"); //$NON-NLS-1$ } if (version < 1.5) { arguments.add("-Xrunjdwp:transport=dt_socket,suspend=y,address=localhost:" + port); //$NON-NLS-1$ } else { arguments.add("-agentlib:jdwp=transport=dt_socket,suspend=y,address=localhost:" + port); //$NON-NLS-1$ } arguments.add(config.getClassToLaunch()); addArguments(config.getProgramArguments(), arguments); String[] cmdLine= new String[arguments.size()]; arguments.toArray(cmdLine); String[] envp= config.getEnvironment(); // check for cancellation if (monitor.isCanceled()) { return; } subMonitor.worked(1); subMonitor.subTask(LaunchingMessages.StandardVMDebugger_Starting_virtual_machine____4); ListeningConnector connector= getConnector(); if (connector == null) { abort(LaunchingMessages.StandardVMDebugger_Couldn__t_find_an_appropriate_debug_connector_2, null, IJavaLaunchConfigurationConstants.ERR_CONNECTOR_NOT_AVAILABLE); } Map map= connector.defaultArguments(); specifyArguments(map, port); Process p= null; try { try { // check for cancellation if (monitor.isCanceled()) { return; } connector.startListening(map); File workingDir = getWorkingDir(config); p = exec(cmdLine, workingDir, envp); if (p == null) { return; } // check for cancellation if (monitor.isCanceled()) { p.destroy(); return; } IProcess process= newProcess(launch, p, renderProcessLabel(cmdLine), getDefaultProcessMap()); process.setAttribute(IProcess.ATTR_CMDLINE, renderCommandLine(cmdLine)); subMonitor.worked(1); subMonitor.subTask(LaunchingMessages.StandardVMDebugger_Establishing_debug_connection____5); boolean retry= false; do { try { ConnectRunnable runnable = new ConnectRunnable(connector, map); Thread connectThread = new Thread(runnable, "Listening Connector"); //$NON-NLS-1$ connectThread.setDaemon(true); connectThread.start(); while (connectThread.isAlive()) { if (monitor.isCanceled()) { connector.stopListening(map); p.destroy(); return; } try { p.exitValue(); // process has terminated - stop waiting for a connection try { connector.stopListening(map); } catch (IOException e) { // expected } checkErrorMessage(process); } catch (IllegalThreadStateException e) { // expected while process is alive } try { Thread.sleep(100); } catch (InterruptedException e) { } } Exception ex = runnable.getException(); if (ex instanceof IllegalConnectorArgumentsException) { throw (IllegalConnectorArgumentsException)ex; } if (ex instanceof InterruptedIOException) { throw (InterruptedIOException)ex; } if (ex instanceof IOException) { throw (IOException)ex; } VirtualMachine vm= runnable.getVirtualMachine(); if (vm != null) { JDIDebugModel.newDebugTarget(launch, vm, renderDebugTarget(config.getClassToLaunch(), port), process, true, false, config.isResumeOnStartup()); subMonitor.worked(1); subMonitor.done(); } return; } catch (InterruptedIOException e) { checkErrorMessage(process); // timeout, consult status handler if there is one IStatus status = new Status(IStatus.ERROR, LaunchingPlugin.getUniqueIdentifier(), IJavaLaunchConfigurationConstants.ERR_VM_CONNECT_TIMEOUT, "", e); //$NON-NLS-1$ IStatusHandler handler = DebugPlugin.getDefault().getStatusHandler(status); retry= false; if (handler == null) { // if there is no handler, throw the exception throw new CoreException(status); } Object result = handler.handleStatus(status, this); if (result instanceof Boolean) { retry = ((Boolean)result).booleanValue(); } } } while (retry); } finally { connector.stopListening(map); } } catch (IOException e) { abort(LaunchingMessages.StandardVMDebugger_Couldn__t_connect_to_VM_4, e, IJavaLaunchConfigurationConstants.ERR_CONNECTION_FAILED); } catch (IllegalConnectorArgumentsException e) { abort(LaunchingMessages.StandardVMDebugger_Couldn__t_connect_to_VM_5, e, IJavaLaunchConfigurationConstants.ERR_CONNECTION_FAILED); } if (p != null) { p.destroy(); } }
public void run(VMRunnerConfiguration config, ILaunch launch, IProgressMonitor monitor) throws CoreException { if (monitor == null) { monitor = new NullProgressMonitor(); } IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1); subMonitor.beginTask(LaunchingMessages.StandardVMDebugger_Launching_VM____1, 4); subMonitor.subTask(LaunchingMessages.StandardVMDebugger_Finding_free_socket____2); int port= SocketUtil.findFreePort(); if (port == -1) { abort(LaunchingMessages.StandardVMDebugger_Could_not_find_a_free_socket_for_the_debugger_1, null, IJavaLaunchConfigurationConstants.ERR_NO_SOCKET_AVAILABLE); } subMonitor.worked(1); // check for cancellation if (monitor.isCanceled()) { return; } subMonitor.subTask(LaunchingMessages.StandardVMDebugger_Constructing_command_line____3); String program= constructProgramString(config); List arguments= new ArrayList(12); arguments.add(program); // VM args are the first thing after the java program so that users can specify // options like '-client' & '-server' which are required to be the first options String[] allVMArgs = combineVmArgs(config, fVMInstance); addArguments(allVMArgs, arguments); addBootClassPathArguments(arguments, config); String[] cp= config.getClassPath(); if (cp.length > 0) { arguments.add("-classpath"); //$NON-NLS-1$ arguments.add(convertClassPath(cp)); } double version = getJavaVersion(); if (version < 1.5) { arguments.add("-Xdebug"); //$NON-NLS-1$ arguments.add("-Xnoagent"); //$NON-NLS-1$ } //check if java 1.4 or greater if (version < 1.4) { arguments.add("-Djava.compiler=NONE"); //$NON-NLS-1$ } if (version < 1.5) { arguments.add("-Xrunjdwp:transport=dt_socket,suspend=y,address=localhost:" + port); //$NON-NLS-1$ } else { arguments.add("-agentlib:jdwp=transport=dt_socket,suspend=y,address=localhost:" + port); //$NON-NLS-1$ } arguments.add(config.getClassToLaunch()); addArguments(config.getProgramArguments(), arguments); String[] cmdLine= new String[arguments.size()]; arguments.toArray(cmdLine); String[] envp= config.getEnvironment(); // check for cancellation if (monitor.isCanceled()) { return; } subMonitor.worked(1); subMonitor.subTask(LaunchingMessages.StandardVMDebugger_Starting_virtual_machine____4); ListeningConnector connector= getConnector(); if (connector == null) { abort(LaunchingMessages.StandardVMDebugger_Couldn__t_find_an_appropriate_debug_connector_2, null, IJavaLaunchConfigurationConstants.ERR_CONNECTOR_NOT_AVAILABLE); } Map map= connector.defaultArguments(); specifyArguments(map, port); Process p= null; try { try { // check for cancellation if (monitor.isCanceled()) { return; } connector.startListening(map); File workingDir = getWorkingDir(config); p = exec(cmdLine, workingDir, envp); if (p == null) { return; } // check for cancellation if (monitor.isCanceled()) { p.destroy(); return; } IProcess process= newProcess(launch, p, renderProcessLabel(cmdLine), getDefaultProcessMap()); process.setAttribute(IProcess.ATTR_CMDLINE, renderCommandLine(cmdLine)); subMonitor.worked(1); subMonitor.subTask(LaunchingMessages.StandardVMDebugger_Establishing_debug_connection____5); boolean retry= false; do { try { ConnectRunnable runnable = new ConnectRunnable(connector, map); Thread connectThread = new Thread(runnable, "Listening Connector"); //$NON-NLS-1$ connectThread.setDaemon(true); connectThread.start(); while (connectThread.isAlive()) { if (monitor.isCanceled()) { try { connector.stopListening(map); } catch (IOException ioe) { //expected } p.destroy(); return; } try { p.exitValue(); // process has terminated - stop waiting for a connection try { connector.stopListening(map); } catch (IOException e) { // expected } checkErrorMessage(process); } catch (IllegalThreadStateException e) { // expected while process is alive } try { Thread.sleep(100); } catch (InterruptedException e) { } } Exception ex = runnable.getException(); if (ex instanceof IllegalConnectorArgumentsException) { throw (IllegalConnectorArgumentsException)ex; } if (ex instanceof InterruptedIOException) { throw (InterruptedIOException)ex; } if (ex instanceof IOException) { throw (IOException)ex; } VirtualMachine vm= runnable.getVirtualMachine(); if (vm != null) { JDIDebugModel.newDebugTarget(launch, vm, renderDebugTarget(config.getClassToLaunch(), port), process, true, false, config.isResumeOnStartup()); subMonitor.worked(1); subMonitor.done(); } return; } catch (InterruptedIOException e) { checkErrorMessage(process); // timeout, consult status handler if there is one IStatus status = new Status(IStatus.ERROR, LaunchingPlugin.getUniqueIdentifier(), IJavaLaunchConfigurationConstants.ERR_VM_CONNECT_TIMEOUT, "", e); //$NON-NLS-1$ IStatusHandler handler = DebugPlugin.getDefault().getStatusHandler(status); retry= false; if (handler == null) { // if there is no handler, throw the exception throw new CoreException(status); } Object result = handler.handleStatus(status, this); if (result instanceof Boolean) { retry = ((Boolean)result).booleanValue(); } } } while (retry); } finally { connector.stopListening(map); } } catch (IOException e) { abort(LaunchingMessages.StandardVMDebugger_Couldn__t_connect_to_VM_4, e, IJavaLaunchConfigurationConstants.ERR_CONNECTION_FAILED); } catch (IllegalConnectorArgumentsException e) { abort(LaunchingMessages.StandardVMDebugger_Couldn__t_connect_to_VM_5, e, IJavaLaunchConfigurationConstants.ERR_CONNECTION_FAILED); } if (p != null) { p.destroy(); } }
diff --git a/crypto/src/org/bouncycastle/x509/X509AttributeCertStoreSelector.java b/crypto/src/org/bouncycastle/x509/X509AttributeCertStoreSelector.java index f3e96f6f..8ceb83e1 100644 --- a/crypto/src/org/bouncycastle/x509/X509AttributeCertStoreSelector.java +++ b/crypto/src/org/bouncycastle/x509/X509AttributeCertStoreSelector.java @@ -1,486 +1,486 @@ package org.bouncycastle.x509; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.Target; import org.bouncycastle.asn1.x509.TargetInformation; import org.bouncycastle.asn1.x509.Targets; import org.bouncycastle.asn1.x509.X509Extensions; import org.bouncycastle.util.Selector; import java.io.IOException; import java.math.BigInteger; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * This class is an <code>Selector</code> like implementation to select * attribute certificates from a given set of criteria. * * @see org.bouncycastle.x509.X509AttributeCertificate * @see org.bouncycastle.x509.X509Store */ public class X509AttributeCertStoreSelector implements Selector { // TODO: name constraints??? private AttributeCertificateHolder holder; private AttributeCertificateIssuer issuer; private BigInteger serialNumber; private Date attributeCertificateValid; private X509AttributeCertificate attributeCert; private Collection targetNames = new HashSet(); private Collection targetGroups = new HashSet(); public X509AttributeCertStoreSelector() { super(); } /** * Decides if the given attribute certificate should be selected. * * @param obj The attribute certificate which should be checked. * @return <code>true</code> if the attribute certificate can be selected, * <code>false</code> otherwise. */ public boolean match(Object obj) { if (!(obj instanceof X509AttributeCertificate)) { return false; } X509AttributeCertificate attrCert = (X509AttributeCertificate) obj; if (this.attributeCert != null) { if (!this.attributeCert.equals(attrCert)) { return false; } } if (serialNumber != null) { if (!attrCert.getSerialNumber().equals(serialNumber)) { return false; } } if (holder != null) { if (!attrCert.getHolder().equals(holder)) { return false; } } if (issuer != null) { if (!attrCert.getIssuer().equals(issuer)) { return false; } } if (attributeCertificateValid != null) { try { attrCert.checkValidity(attributeCertificateValid); } catch (CertificateExpiredException e) { return false; } catch (CertificateNotYetValidException e) { return false; } } if (!targetNames.isEmpty() || !targetGroups.isEmpty()) { byte[] targetInfoExt = attrCert .getExtensionValue(X509Extensions.TargetInformation.getId()); if (targetInfoExt != null) { TargetInformation targetinfo; try { targetinfo = TargetInformation .getInstance(new ASN1InputStream( ((DEROctetString) DEROctetString .fromByteArray(targetInfoExt)).getOctets()) .readObject()); } catch (IOException e) { return false; } catch (IllegalArgumentException e) { return false; } Targets[] targetss = targetinfo.getTargetsObjects(); if (!targetNames.isEmpty()) { boolean found = false; for (int i=0; i<targetss.length; i++) { Targets t = targetss[i]; Target[] targets = t.getTargets(); for (int j=0; j<targets.length; j++) { - if (targetNames.contains(targets[j] - .getTargetName())) + if (targetNames.contains(GeneralName.getInstance(targets[j] + .getTargetName()))) { found = true; break; } } } if (!found) { return false; } } if (!targetGroups.isEmpty()) { boolean found = false; for (int i=0; i<targetss.length; i++) { Targets t = targetss[i]; Target[] targets = t.getTargets(); for (int j=0; j<targets.length; j++) { - if (targetGroups.contains(targets[j] - .getTargetGroup())) + if (targetGroups.contains(GeneralName.getInstance(targets[j] + .getTargetGroup()))) { found = true; break; } } } if (!found) { return false; } } } } return true; } /** * Returns a clone of this object. * * @return the clone. */ public Object clone() { X509AttributeCertStoreSelector sel = new X509AttributeCertStoreSelector(); sel.attributeCert = attributeCert; sel.attributeCertificateValid = getAttributeCertificateValid(); sel.holder = holder; sel.issuer = issuer; sel.serialNumber = serialNumber; sel.targetGroups = getTargetGroups(); sel.targetNames = getTargetNames(); return sel; } /** * Returns the attribute certificate which must be matched. * * @return Returns the attribute certificate. */ public X509AttributeCertificate getAttributeCert() { return attributeCert; } /** * Set the attribute certificate to be matched. If <code>null</code> is * given any will do. * * @param attributeCert The attribute certificate to set. */ public void setAttributeCert(X509AttributeCertificate attributeCert) { this.attributeCert = attributeCert; } /** * Get the criteria for the validity. * * @return Returns the attributeCertificateValid. */ public Date getAttributeCertificateValid() { if (attributeCertificateValid != null) { return new Date(attributeCertificateValid.getTime()); } return null; } /** * Set the time, when the certificate must be valid. If <code>null</code> * is given any will do. * * @param attributeCertificateValid The attribute certificate validation * time to set. */ public void setAttributeCertificateValid(Date attributeCertificateValid) { if (attributeCertificateValid != null) { this.attributeCertificateValid = new Date(attributeCertificateValid .getTime()); } else { this.attributeCertificateValid = null; } } /** * Gets the holder. * * @return Returns the holder. */ public AttributeCertificateHolder getHolder() { return holder; } /** * Sets the holder. If <code>null</code> is given any will do. * * @param holder The holder to set. */ public void setHolder(AttributeCertificateHolder holder) { this.holder = holder; } /** * Returns the issuer criterion. * * @return Returns the issuer. */ public AttributeCertificateIssuer getIssuer() { return issuer; } /** * Sets the issuer the attribute certificate must have. If <code>null</code> * is given any will do. * * @param issuer The issuer to set. */ public void setIssuer(AttributeCertificateIssuer issuer) { this.issuer = issuer; } /** * Gets the serial number the attribute certificate must have. * * @return Returns the serialNumber. */ public BigInteger getSerialNumber() { return serialNumber; } /** * Sets the serial number the attribute certificate must have. If * <code>null</code> is given any will do. * * @param serialNumber The serialNumber to set. */ public void setSerialNumber(BigInteger serialNumber) { this.serialNumber = serialNumber; } /** * Adds a target name criterion for the attribute certificate to the target * information extension criteria. The <code>X509AttributeCertificate</code> * must contain at least one of the specified target names. * <p> * Each attribute certificate may contain a target information extension * limiting the servers where this attribute certificate can be used. If * this extension is not present, the attribute certificate is not targeted * and may be accepted by any server. * * @param name The name as a GeneralName (not <code>null</code>) */ public void addTargetName(GeneralName name) { targetNames.add(name); } /** * Adds a target name criterion for the attribute certificate to the target * information extension criteria. The <code>X509AttributeCertificate</code> * must contain at least one of the specified target names. * <p> * Each attribute certificate may contain a target information extension * limiting the servers where this attribute certificate can be used. If * this extension is not present, the attribute certificate is not targeted * and may be accepted by any server. * * @param name a byte array containing the name in ASN.1 DER encoded form of a GeneralName * @throws IOException if a parsing error occurs. */ public void addTargetName(byte[] name) throws IOException { addTargetName(GeneralName.getInstance(ASN1Object.fromByteArray(name))); } /** * Adds a collection with target names criteria. If <code>null</code> is * given any will do. * <p> * The collection consists of either GeneralName objects or byte[] arrays representing * DER encoded GeneralName structures. * * @param names A collection of target names. * @throws IOException if a parsing error occurs. * @see #addTargetName(byte[]) * @see #addTargetName(GeneralName) */ public void setTargetNames(Collection names) throws IOException { targetNames = extractGeneralNames(names); } /** * Gets the target names. The collection consists of <code>List</code>s * made up of an <code>Integer</code> in the first entry and a DER encoded * byte array or a <code>String</code> in the second entry. * <p> * The returned collection is immutable. * * @return The collection of target names * @see #setTargetNames(Collection) */ public Collection getTargetNames() { return Collections.unmodifiableCollection(targetNames); } /** * Adds a target group criterion for the attribute certificate to the target * information extension criteria. The <code>X509AttributeCertificate</code> * must contain at least one of the specified target groups. * <p> * Each attribute certificate may contain a target information extension * limiting the servers where this attribute certificate can be used. If * this extension is not present, the attribute certificate is not targeted * and may be accepted by any server. * * @param group The group as GeneralName form (not <code>null</code>) */ public void addTargetGroup(GeneralName group) { targetGroups.add(group); } /** * Adds a target group criterion for the attribute certificate to the target * information extension criteria. The <code>X509AttributeCertificate</code> * must contain at least one of the specified target groups. * <p> * Each attribute certificate may contain a target information extension * limiting the servers where this attribute certificate can be used. If * this extension is not present, the attribute certificate is not targeted * and may be accepted by any server. * * @param name a byte array containing the group in ASN.1 DER encoded form of a GeneralName * @throws IOException if a parsing error occurs. */ public void addTargetGroup(byte[] name) throws IOException { addTargetGroup(GeneralName.getInstance(ASN1Object.fromByteArray(name))); } /** * Adds a collection with target groups criteria. If <code>null</code> is * given any will do. * <p> * The collection consists of <code>GeneralName</code> objects or <code>byte[]</code representing DER * encoded GeneralNames. * * @param names A collection of target groups. * @throws IOException if a parsing error occurs. * @see #addTargetGroup(byte[]) * @see #addTargetGroup(GeneralName) */ public void setTargetGroups(Collection names) throws IOException { targetGroups = extractGeneralNames(names); } /** * Gets the target groups. The collection consists of <code>List</code>s * made up of an <code>Integer</code> in the first entry and a DER encoded * byte array or a <code>String</code> in the second entry. * <p> * The returned collection is immutable. * * @return The collection of target groups. * @see #setTargetGroups(Collection) */ public Collection getTargetGroups() { return Collections.unmodifiableCollection(targetGroups); } private Set extractGeneralNames(Collection names) throws IOException { if (names == null || names.isEmpty()) { return new HashSet(); } Set temp = new HashSet(); for (Iterator it = names.iterator(); it.hasNext();) { Object o = it.next(); if (o instanceof GeneralName) { temp.add(o); } else { temp.add(GeneralName.getInstance(ASN1Object.fromByteArray((byte[])o))); } } return temp; } }
false
true
public boolean match(Object obj) { if (!(obj instanceof X509AttributeCertificate)) { return false; } X509AttributeCertificate attrCert = (X509AttributeCertificate) obj; if (this.attributeCert != null) { if (!this.attributeCert.equals(attrCert)) { return false; } } if (serialNumber != null) { if (!attrCert.getSerialNumber().equals(serialNumber)) { return false; } } if (holder != null) { if (!attrCert.getHolder().equals(holder)) { return false; } } if (issuer != null) { if (!attrCert.getIssuer().equals(issuer)) { return false; } } if (attributeCertificateValid != null) { try { attrCert.checkValidity(attributeCertificateValid); } catch (CertificateExpiredException e) { return false; } catch (CertificateNotYetValidException e) { return false; } } if (!targetNames.isEmpty() || !targetGroups.isEmpty()) { byte[] targetInfoExt = attrCert .getExtensionValue(X509Extensions.TargetInformation.getId()); if (targetInfoExt != null) { TargetInformation targetinfo; try { targetinfo = TargetInformation .getInstance(new ASN1InputStream( ((DEROctetString) DEROctetString .fromByteArray(targetInfoExt)).getOctets()) .readObject()); } catch (IOException e) { return false; } catch (IllegalArgumentException e) { return false; } Targets[] targetss = targetinfo.getTargetsObjects(); if (!targetNames.isEmpty()) { boolean found = false; for (int i=0; i<targetss.length; i++) { Targets t = targetss[i]; Target[] targets = t.getTargets(); for (int j=0; j<targets.length; j++) { if (targetNames.contains(targets[j] .getTargetName())) { found = true; break; } } } if (!found) { return false; } } if (!targetGroups.isEmpty()) { boolean found = false; for (int i=0; i<targetss.length; i++) { Targets t = targetss[i]; Target[] targets = t.getTargets(); for (int j=0; j<targets.length; j++) { if (targetGroups.contains(targets[j] .getTargetGroup())) { found = true; break; } } } if (!found) { return false; } } } } return true; }
public boolean match(Object obj) { if (!(obj instanceof X509AttributeCertificate)) { return false; } X509AttributeCertificate attrCert = (X509AttributeCertificate) obj; if (this.attributeCert != null) { if (!this.attributeCert.equals(attrCert)) { return false; } } if (serialNumber != null) { if (!attrCert.getSerialNumber().equals(serialNumber)) { return false; } } if (holder != null) { if (!attrCert.getHolder().equals(holder)) { return false; } } if (issuer != null) { if (!attrCert.getIssuer().equals(issuer)) { return false; } } if (attributeCertificateValid != null) { try { attrCert.checkValidity(attributeCertificateValid); } catch (CertificateExpiredException e) { return false; } catch (CertificateNotYetValidException e) { return false; } } if (!targetNames.isEmpty() || !targetGroups.isEmpty()) { byte[] targetInfoExt = attrCert .getExtensionValue(X509Extensions.TargetInformation.getId()); if (targetInfoExt != null) { TargetInformation targetinfo; try { targetinfo = TargetInformation .getInstance(new ASN1InputStream( ((DEROctetString) DEROctetString .fromByteArray(targetInfoExt)).getOctets()) .readObject()); } catch (IOException e) { return false; } catch (IllegalArgumentException e) { return false; } Targets[] targetss = targetinfo.getTargetsObjects(); if (!targetNames.isEmpty()) { boolean found = false; for (int i=0; i<targetss.length; i++) { Targets t = targetss[i]; Target[] targets = t.getTargets(); for (int j=0; j<targets.length; j++) { if (targetNames.contains(GeneralName.getInstance(targets[j] .getTargetName()))) { found = true; break; } } } if (!found) { return false; } } if (!targetGroups.isEmpty()) { boolean found = false; for (int i=0; i<targetss.length; i++) { Targets t = targetss[i]; Target[] targets = t.getTargets(); for (int j=0; j<targets.length; j++) { if (targetGroups.contains(GeneralName.getInstance(targets[j] .getTargetGroup()))) { found = true; break; } } } if (!found) { return false; } } } } return true; }
diff --git a/src/main/java/hudson/plugins/ec2/ssh/EC2UnixLauncher.java b/src/main/java/hudson/plugins/ec2/ssh/EC2UnixLauncher.java index 511ee3b..c67c403 100644 --- a/src/main/java/hudson/plugins/ec2/ssh/EC2UnixLauncher.java +++ b/src/main/java/hudson/plugins/ec2/ssh/EC2UnixLauncher.java @@ -1,270 +1,272 @@ /* * The MIT License * * Copyright (c) 2004-, Kohsuke Kawaguchi, Sun Microsystems, Inc., and a number of other of contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.plugins.ec2.ssh; import hudson.model.Descriptor; import hudson.model.Hudson; import hudson.plugins.ec2.EC2ComputerLauncher; import hudson.plugins.ec2.EC2Cloud; import hudson.plugins.ec2.EC2Computer; import hudson.remoting.Channel; import hudson.remoting.Channel.Listener; import hudson.slaves.ComputerLauncher; import java.io.IOException; import java.io.PrintStream; import java.net.URL; import org.apache.commons.io.IOUtils; import com.amazonaws.AmazonClientException; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.KeyPair; import com.trilead.ssh2.Connection; import com.trilead.ssh2.SCPClient; import com.trilead.ssh2.ServerHostKeyVerifier; import com.trilead.ssh2.Session; /** * {@link ComputerLauncher} that connects to a Unix slave on EC2 by using SSH. * * @author Kohsuke Kawaguchi */ public class EC2UnixLauncher extends EC2ComputerLauncher { private final int FAILED=-1; private final int SAMEUSER=0; private final int RECONNECT=-2; protected String buildUpCommand(EC2Computer computer, String command) { if (!computer.getRemoteAdmin().equals("root")) { command = computer.getRootCommandPrefix() + " " + command; } return command; } @Override protected void launch(EC2Computer computer, PrintStream logger, Instance inst) throws IOException, AmazonClientException, InterruptedException { final Connection bootstrapConn; final Connection conn; Connection cleanupConn = null; // java's code path analysis for final doesn't work that well. boolean successful = false; try { bootstrapConn = connectToSsh(computer, logger); int bootstrapResult = bootstrap(bootstrapConn, computer, logger); if (bootstrapResult == FAILED) { logger.println("bootstrapresult failed"); return; // bootstrap closed for us. } else if (bootstrapResult == SAMEUSER) { cleanupConn = bootstrapConn; // take over the connection logger.println("take over connection"); } else { // connect fresh as ROOT logger.println("connect fresh as root"); cleanupConn = connectToSsh(computer, logger); KeyPair key = computer.getCloud().getKeyPair(); if (!cleanupConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), "")) { logger.println("Authentication failed"); return; // failed to connect as root. } } conn = cleanupConn; SCPClient scp = conn.createSCPClient(); String initScript = computer.getNode().initScript; if(initScript!=null && initScript.trim().length()>0 && conn.exec("test -e ~/.hudson-run-init", logger) !=0) { logger.println("Executing init script"); scp.put(initScript.getBytes("UTF-8"),"init.sh","/tmp","0700"); Session sess = conn.openSession(); sess.requestDumbPTY(); // so that the remote side bundles stdout and stderr sess.execCommand(buildUpCommand(computer, "/tmp/init.sh")); sess.getStdin().close(); // nothing to write here sess.getStderr().close(); // we are not supposed to get anything from stderr IOUtils.copy(sess.getStdout(),logger); int exitStatus = waitCompletion(sess); if (exitStatus!=0) { logger.println("init script failed: exit code="+exitStatus); return; } + sess.close(); // Needs a tty to run sudo. sess = conn.openSession(); sess.requestDumbPTY(); // so that the remote side bundles stdout and stderr sess.execCommand(buildUpCommand(computer, "touch ~/.hudson-run-init")); + sess.close(); } // TODO: parse the version number. maven-enforcer-plugin might help logger.println("Verifying that java exists"); if(conn.exec("java -fullversion", logger) !=0) { logger.println("Installing Java"); String jdk = "java1.6.0_12"; String path = "/hudson-ci/jdk/linux-i586/" + jdk + ".tgz"; URL url = computer.getCloud().buildPresignedURL(path); if(conn.exec("wget -nv -O /tmp/" + jdk + ".tgz '" + url + "'", logger) !=0) { logger.println("Failed to download Java"); return; } if(conn.exec(buildUpCommand(computer, "tar xz -C /usr -f /tmp/" + jdk + ".tgz"), logger) !=0) { logger.println("Failed to install Java"); return; } if(conn.exec(buildUpCommand(computer, "ln -s /usr/" + jdk + "/bin/java /bin/java"), logger) !=0) { logger.println("Failed to symlink Java"); return; } } // TODO: on Windows with ec2-sshd, this scp command ends up just putting slave.jar as c:\tmp // bug in ec2-sshd? logger.println("Copying slave.jar"); scp.put(Hudson.getInstance().getJnlpJars("slave.jar").readFully(), "slave.jar","/tmp"); String jvmopts = computer.getNode().jvmopts; String launchString = "java " + (jvmopts != null ? jvmopts : "") + " -jar /tmp/slave.jar"; logger.println("Launching slave agent: " + launchString); final Session sess = conn.openSession(); sess.execCommand(launchString); computer.setChannel(sess.getStdout(),sess.getStdin(),logger,new Listener() { @Override public void onClosed(Channel channel, IOException cause) { sess.close(); conn.close(); } }); successful = true; } finally { if(cleanupConn != null && !successful) cleanupConn.close(); } } private int bootstrap(Connection bootstrapConn, EC2Computer computer, PrintStream logger) throws IOException, InterruptedException, AmazonClientException { logger.println("bootstrap()" ); boolean closeBootstrap = true; try { int tries = 20; boolean isAuthenticated = false; logger.println("Getting keypair..." ); KeyPair key = computer.getCloud().getKeyPair(); logger.println("Using key: " + key.getKeyName() + "\n" + key.getKeyFingerprint() + "\n" + key.getKeyMaterial().substring(0, 160) ); while (tries-- > 0) { logger.println("Authenticating as " + computer.getRemoteAdmin()); isAuthenticated = bootstrapConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), ""); if (isAuthenticated) { break; } logger.println("Authentication failed. Trying again..."); Thread.sleep(10000); } if (!isAuthenticated) { logger.println("Authentication failed"); return FAILED; } closeBootstrap = false; return SAMEUSER; } finally { if (closeBootstrap) bootstrapConn.close(); } } private Connection connectToSsh(EC2Computer computer, PrintStream logger) throws AmazonClientException, InterruptedException { final long timeout = computer.getNode().getLaunchTimeoutInMillis(); final long startTime = System.currentTimeMillis(); while(true) { try { long waitTime = System.currentTimeMillis() - startTime; if ( waitTime > timeout ) { throw new AmazonClientException("Timed out after "+ (waitTime / 1000) + " seconds of waiting for ssh to become available. (maximum timeout configured is "+ (timeout / 1000) + ")" ); } Instance instance = computer.updateInstanceDescription(); String vpc_id = instance.getVpcId(); String host; if (computer.getNode().usePrivateDnsName) { host = instance.getPrivateDnsName(); } else { /* VPC hosts don't have public DNS names, so we need to use an IP address instead */ if (vpc_id == null || vpc_id.equals("")) { host = instance.getPublicDnsName(); } else { host = instance.getPrivateIpAddress(); } } if ("0.0.0.0".equals(host)) { logger.println("Invalid host 0.0.0.0, your host is most likely waiting for an ip address."); throw new IOException("goto sleep"); } int port = computer.getSshPort(); logger.println("Connecting to " + host + " on port " + port + ". "); Connection conn = new Connection(host, port); // currently OpenSolaris offers no way of verifying the host certificate, so just accept it blindly, // hoping that no man-in-the-middle attack is going on. conn.connect(new ServerHostKeyVerifier() { public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception { return true; } }); logger.println("Connected via SSH."); return conn; // successfully connected } catch (IOException e) { // keep retrying until SSH comes up logger.println("Waiting for SSH to come up. Sleeping 5."); Thread.sleep(5000); } } } private int waitCompletion(Session session) throws InterruptedException { // I noticed that the exit status delivery often gets delayed. Wait up to 1 sec. for( int i=0; i<10; i++ ) { Integer r = session.getExitStatus(); if(r!=null) return r; Thread.sleep(100); } return -1; } @Override public Descriptor<ComputerLauncher> getDescriptor() { throw new UnsupportedOperationException(); } }
false
true
protected void launch(EC2Computer computer, PrintStream logger, Instance inst) throws IOException, AmazonClientException, InterruptedException { final Connection bootstrapConn; final Connection conn; Connection cleanupConn = null; // java's code path analysis for final doesn't work that well. boolean successful = false; try { bootstrapConn = connectToSsh(computer, logger); int bootstrapResult = bootstrap(bootstrapConn, computer, logger); if (bootstrapResult == FAILED) { logger.println("bootstrapresult failed"); return; // bootstrap closed for us. } else if (bootstrapResult == SAMEUSER) { cleanupConn = bootstrapConn; // take over the connection logger.println("take over connection"); } else { // connect fresh as ROOT logger.println("connect fresh as root"); cleanupConn = connectToSsh(computer, logger); KeyPair key = computer.getCloud().getKeyPair(); if (!cleanupConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), "")) { logger.println("Authentication failed"); return; // failed to connect as root. } } conn = cleanupConn; SCPClient scp = conn.createSCPClient(); String initScript = computer.getNode().initScript; if(initScript!=null && initScript.trim().length()>0 && conn.exec("test -e ~/.hudson-run-init", logger) !=0) { logger.println("Executing init script"); scp.put(initScript.getBytes("UTF-8"),"init.sh","/tmp","0700"); Session sess = conn.openSession(); sess.requestDumbPTY(); // so that the remote side bundles stdout and stderr sess.execCommand(buildUpCommand(computer, "/tmp/init.sh")); sess.getStdin().close(); // nothing to write here sess.getStderr().close(); // we are not supposed to get anything from stderr IOUtils.copy(sess.getStdout(),logger); int exitStatus = waitCompletion(sess); if (exitStatus!=0) { logger.println("init script failed: exit code="+exitStatus); return; } // Needs a tty to run sudo. sess = conn.openSession(); sess.requestDumbPTY(); // so that the remote side bundles stdout and stderr sess.execCommand(buildUpCommand(computer, "touch ~/.hudson-run-init")); } // TODO: parse the version number. maven-enforcer-plugin might help logger.println("Verifying that java exists"); if(conn.exec("java -fullversion", logger) !=0) { logger.println("Installing Java"); String jdk = "java1.6.0_12"; String path = "/hudson-ci/jdk/linux-i586/" + jdk + ".tgz"; URL url = computer.getCloud().buildPresignedURL(path); if(conn.exec("wget -nv -O /tmp/" + jdk + ".tgz '" + url + "'", logger) !=0) { logger.println("Failed to download Java"); return; } if(conn.exec(buildUpCommand(computer, "tar xz -C /usr -f /tmp/" + jdk + ".tgz"), logger) !=0) { logger.println("Failed to install Java"); return; } if(conn.exec(buildUpCommand(computer, "ln -s /usr/" + jdk + "/bin/java /bin/java"), logger) !=0) { logger.println("Failed to symlink Java"); return; } } // TODO: on Windows with ec2-sshd, this scp command ends up just putting slave.jar as c:\tmp // bug in ec2-sshd? logger.println("Copying slave.jar"); scp.put(Hudson.getInstance().getJnlpJars("slave.jar").readFully(), "slave.jar","/tmp"); String jvmopts = computer.getNode().jvmopts; String launchString = "java " + (jvmopts != null ? jvmopts : "") + " -jar /tmp/slave.jar"; logger.println("Launching slave agent: " + launchString); final Session sess = conn.openSession(); sess.execCommand(launchString); computer.setChannel(sess.getStdout(),sess.getStdin(),logger,new Listener() { @Override public void onClosed(Channel channel, IOException cause) { sess.close(); conn.close(); } }); successful = true; } finally { if(cleanupConn != null && !successful) cleanupConn.close(); } }
protected void launch(EC2Computer computer, PrintStream logger, Instance inst) throws IOException, AmazonClientException, InterruptedException { final Connection bootstrapConn; final Connection conn; Connection cleanupConn = null; // java's code path analysis for final doesn't work that well. boolean successful = false; try { bootstrapConn = connectToSsh(computer, logger); int bootstrapResult = bootstrap(bootstrapConn, computer, logger); if (bootstrapResult == FAILED) { logger.println("bootstrapresult failed"); return; // bootstrap closed for us. } else if (bootstrapResult == SAMEUSER) { cleanupConn = bootstrapConn; // take over the connection logger.println("take over connection"); } else { // connect fresh as ROOT logger.println("connect fresh as root"); cleanupConn = connectToSsh(computer, logger); KeyPair key = computer.getCloud().getKeyPair(); if (!cleanupConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), "")) { logger.println("Authentication failed"); return; // failed to connect as root. } } conn = cleanupConn; SCPClient scp = conn.createSCPClient(); String initScript = computer.getNode().initScript; if(initScript!=null && initScript.trim().length()>0 && conn.exec("test -e ~/.hudson-run-init", logger) !=0) { logger.println("Executing init script"); scp.put(initScript.getBytes("UTF-8"),"init.sh","/tmp","0700"); Session sess = conn.openSession(); sess.requestDumbPTY(); // so that the remote side bundles stdout and stderr sess.execCommand(buildUpCommand(computer, "/tmp/init.sh")); sess.getStdin().close(); // nothing to write here sess.getStderr().close(); // we are not supposed to get anything from stderr IOUtils.copy(sess.getStdout(),logger); int exitStatus = waitCompletion(sess); if (exitStatus!=0) { logger.println("init script failed: exit code="+exitStatus); return; } sess.close(); // Needs a tty to run sudo. sess = conn.openSession(); sess.requestDumbPTY(); // so that the remote side bundles stdout and stderr sess.execCommand(buildUpCommand(computer, "touch ~/.hudson-run-init")); sess.close(); } // TODO: parse the version number. maven-enforcer-plugin might help logger.println("Verifying that java exists"); if(conn.exec("java -fullversion", logger) !=0) { logger.println("Installing Java"); String jdk = "java1.6.0_12"; String path = "/hudson-ci/jdk/linux-i586/" + jdk + ".tgz"; URL url = computer.getCloud().buildPresignedURL(path); if(conn.exec("wget -nv -O /tmp/" + jdk + ".tgz '" + url + "'", logger) !=0) { logger.println("Failed to download Java"); return; } if(conn.exec(buildUpCommand(computer, "tar xz -C /usr -f /tmp/" + jdk + ".tgz"), logger) !=0) { logger.println("Failed to install Java"); return; } if(conn.exec(buildUpCommand(computer, "ln -s /usr/" + jdk + "/bin/java /bin/java"), logger) !=0) { logger.println("Failed to symlink Java"); return; } } // TODO: on Windows with ec2-sshd, this scp command ends up just putting slave.jar as c:\tmp // bug in ec2-sshd? logger.println("Copying slave.jar"); scp.put(Hudson.getInstance().getJnlpJars("slave.jar").readFully(), "slave.jar","/tmp"); String jvmopts = computer.getNode().jvmopts; String launchString = "java " + (jvmopts != null ? jvmopts : "") + " -jar /tmp/slave.jar"; logger.println("Launching slave agent: " + launchString); final Session sess = conn.openSession(); sess.execCommand(launchString); computer.setChannel(sess.getStdout(),sess.getStdin(),logger,new Listener() { @Override public void onClosed(Channel channel, IOException cause) { sess.close(); conn.close(); } }); successful = true; } finally { if(cleanupConn != null && !successful) cleanupConn.close(); } }
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PreparedQuery.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PreparedQuery.java index da2236935..356b43b5a 100644 --- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PreparedQuery.java +++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PreparedQuery.java @@ -1,950 +1,950 @@ /* ************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation * ************************************************************************* */ package org.eclipse.birt.data.engine.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.core.data.DataType; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.IBaseQueryDefinition; import org.eclipse.birt.data.engine.api.IBaseTransform; import org.eclipse.birt.data.engine.api.IConditionalExpression; import org.eclipse.birt.data.engine.api.IGroupDefinition; import org.eclipse.birt.data.engine.api.IQueryResults; import org.eclipse.birt.data.engine.api.IResultMetaData; import org.eclipse.birt.data.engine.api.IScriptExpression; import org.eclipse.birt.data.engine.api.ISortDefinition; import org.eclipse.birt.data.engine.api.ISubqueryDefinition; import org.eclipse.birt.data.engine.api.querydefn.ComputedColumn; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.executor.ExpressionProcessorManager; import org.eclipse.birt.data.engine.i18n.ResourceConstants; import org.eclipse.birt.data.engine.impl.ExpressionCompiler.AggregateRegistry; import org.eclipse.birt.data.engine.odi.ICandidateQuery; import org.eclipse.birt.data.engine.odi.IDataSource; import org.eclipse.birt.data.engine.odi.IPreparedDSQuery; import org.eclipse.birt.data.engine.odi.IQuery; import org.eclipse.birt.data.engine.odi.IResultIterator; import org.eclipse.birt.data.engine.odi.IResultObjectEvent; import org.eclipse.birt.data.engine.script.JSOutputParams; import org.eclipse.birt.data.engine.script.JSRowObject; import org.eclipse.birt.data.engine.script.JSRows; import org.eclipse.birt.data.engine.script.OnFetchScriptHelper; import org.mozilla.javascript.Context; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.Scriptable; /** * Base class for a prepared query or subquery. */ abstract class PreparedQuery { private IBaseQueryDefinition queryDefn; private DataEngineImpl engine; private AggregateTable aggrTable; private Object appContext; // Map of Subquery name (String) to PreparedSubquery protected HashMap subQueryMap = new HashMap(); private boolean isCurrentGroupKeyComplexExpression; protected static Logger logger = Logger.getLogger( DataEngineImpl.class.getName( ) ); PreparedQuery( DataEngineImpl engine, IBaseQueryDefinition queryDefn ) throws DataException { logger.logp( Level.FINE, PreparedQuery.class.getName( ), "PreparedQuery", "PreparedQuery starts up." ); assert engine != null && queryDefn != null; this.engine = engine; this.queryDefn = queryDefn; this.aggrTable = new AggregateTable(this); logger.fine( "Start to prepare a PreparedQuery." ); prepare(); logger.fine( "Finished preparing the PreparedQuery." ); } /** Gets the IBaseQueryDefn instance which defines this query */ protected IBaseQueryDefinition getQueryDefn( ) { return queryDefn; } /** Gets the registry of all aggregate expression */ AggregateTable getAggrTable() { return aggrTable; } protected Object getAppContext() { return appContext; } protected void setAppContext( Object context ) { appContext = context; } /** Gets the appropriate subclass of the Executor */ protected abstract Executor newExecutor(); /** * Gets the main data source query. For a SubQuery, this returns the top-level * data source query that contains the SubQuery. For other queries, "this" * is returned */ abstract protected PreparedDataSourceQuery getDataSourceQuery(); private void prepare( ) throws DataException { // TODO - validation of static queryDefn Context cx = Context.enter(); try { // Prepare all groups; note that the report query iteself // is treated as a group (with group level 0 ) List groups = queryDefn.getGroups( ); IGroupDefinition group; //If there are group definitions that of invalid or duplicate group name ,then //throw exceptions. for ( int i = 0; i < groups.size( ); i++ ) { group = (IGroupDefinition) groups.get( i ); if ( group.getName( ) == null || group.getName( ).trim( ).length( ) == 0 ) continue; for ( int j = 0; j < groups.size( ); j++ ) { if ( group.getName( ) .equals( ( (IGroupDefinition) groups.get( j ) ).getName( ) == null ? "" : ( (IGroupDefinition) groups.get( j ) ).getName( ) ) && j != i ) throw new DataException( ResourceConstants.DUPLICATE_GROUP_NAME ); } } for ( int i = 0; i <= groups.size( ); i++ ) { // Group 0 IBaseTransform groupDefn; if ( i == 0 ) groupDefn = queryDefn; else { groupDefn = (IGroupDefinition) groups.get( i - 1 ); // Filter on group is not supported now, throw exception // TODO support filter on group in the future if ( groupDefn.getFilters( ).size( ) > 0 ) throw new DataException( ResourceConstants.UNSUPPORTED_FILTER_ON_GROUP ); } prepareGroup( groupDefn, i, cx ); } } finally { Context.exit(); } } /** * Return the QueryResults. But the execution of query would be deferred * @param outerResults If query is nested within another query, this is the outer query's query * result handle. * @param scope The ElementState object for the report item using the query; this acts as the * JS scope for evaluating script expressions. */ protected QueryResults doPrepare( IQueryResults outerResults, Scriptable scope ) throws DataException { if ( this.queryDefn == null ) { // we are closed DataException e = new DataException(ResourceConstants.PREPARED_QUERY_CLOSED); logger.logp( Level.WARNING, PreparedQuery.class.getName( ), "doPrepare", "PreparedQuery instance is closed.", e ); throw e; } Executor executor = newExecutor(); // pass the prepared query's pass thru context to its executor executor.setAppContext( this.getAppContext() ); //here prepare the execution. After the preparation the result metadata is available by //calling getResultClass, and the query is ready for execution. logger.finer( "Start to prepare the execution." ); executor.prepareExecution( outerResults, scope ); logger.finer( "Finish preparing the execution." ); return new QueryResults( getDataSourceQuery(), this, executor); } // Common code to extract the name of a column from a JS expression which is // in the form of "row.col". If expression is not in expected format, returns null private ColumnInfo getColInfoFromJSExpr( Context cx, String expr ) { int colIndex = -1; String colName = null; ExpressionCompiler compiler = engine.getExpressionCompiler( ); CompiledExpression ce = compiler.compile( expr, null, cx ); if ( ce instanceof ColumnReferenceExpression ) { ColumnReferenceExpression cre = ( (ColumnReferenceExpression) ce ); colIndex = cre.getColumnindex( ); colName = cre.getColumnName( ); } return new ColumnInfo( colIndex, colName ); } private void prepareGroup( IBaseTransform trans, int groupLevel, Context cx ) throws DataException { // prepare expressions appearing in this group prepareExpressions( trans.getAfterExpressions(), groupLevel, true, cx ); prepareExpressions( trans.getBeforeExpressions(), groupLevel, false, cx ); prepareExpressions( trans.getRowExpressions(), groupLevel, false, cx ); // Prepare subqueries appearing in this group Collection subQueries = trans.getSubqueries( ); Iterator subIt = subQueries.iterator( ); while ( subIt.hasNext( ) ) { ISubqueryDefinition subquery = (ISubqueryDefinition) subIt.next( ); PreparedSubquery pq = new PreparedSubquery( subquery, this, groupLevel ); subQueryMap.put( subquery.getName(), pq); } } /* Prepares all expressions in the given collection */ private void prepareExpressions( Collection expressions, int groupLevel, boolean afterGroup, Context cx ) { if ( expressions == null ) return; AggregateRegistry reg = this.aggrTable.getAggrRegistry( groupLevel, afterGroup, cx ); Iterator it = expressions.iterator(); while ( it.hasNext() ) { prepareExpression((IBaseExpression) it.next(), groupLevel, cx, reg); } } // Prepares one expression private void prepareExpression( IBaseExpression expr, int groupLevel, Context cx, AggregateRegistry reg ) { ExpressionCompiler compiler = this.engine.getExpressionCompiler(); if ( expr instanceof IScriptExpression ) { String exprText = ((IScriptExpression) expr).getText(); CompiledExpression handle = compiler.compile( exprText, reg, cx); expr.setHandle( handle ); } else if ( expr instanceof IConditionalExpression ) { // 3 sub expressions of the conditional expression should be prepared // individually IConditionalExpression ce = (IConditionalExpression) expr; prepareExpression( ce.getExpression(), groupLevel, cx, reg ); if ( ce.getOperand1() != null ) prepareExpression( ce.getOperand1(), groupLevel, cx, reg ); if ( ce.getOperand2() != null ) prepareExpression( ce.getOperand2(), groupLevel, cx, reg ); // No separate preparation is required for the conditional expression // Set itself as the compiled handle expr.setHandle( expr ); } else { // Should never get here assert false; } } /** * Convert IGroupDefn to IQuery.GroupSpec * @param cx * @param src * @return * @throws DataException */ protected IQuery.GroupSpec groupDefnToSpec( Context cx, IGroupDefinition src, String columnName, int index ) throws DataException { int groupIndex = -1; String groupKey = src.getKeyColumn(); if ( groupKey == null || groupKey.length() == 0 ) { // Group key expressed as expression; convert it to column name // TODO support key expression in the future by creating implicit // computed columns ColumnInfo groupKeyInfo = getColInfoFromJSExpr( cx, src.getKeyExpression( ) ); //getColInfoFromJSExpr( cx,src.getKeyExpression( ) ); groupIndex = groupKeyInfo.getColumnIndex( ); groupKey = groupKeyInfo.getColumnName(); isCurrentGroupKeyComplexExpression = false; } if ( groupKey == null && groupIndex < 0 ) { ColumnInfo groupKeyInfo = new ColumnInfo(index, columnName ); groupIndex = groupKeyInfo.getColumnIndex( ); groupKey = groupKeyInfo.getColumnName(); isCurrentGroupKeyComplexExpression = true; } IQuery.GroupSpec dest = new IQuery.GroupSpec( groupIndex, groupKey ); dest.setName( src.getName() ); dest.setInterval( src.getInterval()); dest.setIntervalRange( src.getIntervalRange()); dest.setIntervalStart( src.getIntervalStart()); dest.setSortDirection( src.getSortDirection()); return dest; } /** * Executes a subquery */ QueryResults execSubquery( IResultIterator iterator, String subQueryName, Scriptable scope ) throws DataException { assert subQueryName != null; assert scope != null; PreparedSubquery subquery = (PreparedSubquery) subQueryMap.get( subQueryName ); if ( subquery == null ) { DataException e = new DataException( ResourceConstants.SUBQUERY_NOT_FOUND, subQueryName ); logger.logp( Level.FINE, PreparedQuery.class.getName( ), "execSubquery", "Subquery name not found", e ); throw e; } return subquery.execute( iterator, scope ); } public DataEngineImpl getDataEngine() { return engine; } /** * Closes the prepared query. This instance can no longer be executed after it is closed * TODO: expose this method in the IPreparedQuery interface */ public void close() { queryDefn = null; this.aggrTable = null; this.engine = null; this.subQueryMap = null; logger.logp( Level.FINER, PreparedQuery.class.getName( ), "close", "Prepared query closed" ); // TODO: close all open QueryResults obtained from this PreparedQuery } /** * Finds a group given a text identifier of a group. Returns index of group found (1 = outermost * group, 2 = second level group etc.). The text identifier can be the group name, the group key * column name, or the group key expression text. Returns -1 if no matching group is found */ int getGroupIndex( String groupText ) { assert groupText != null; assert queryDefn != null; List groups = queryDefn.getGroups(); for ( int i = 0; i < groups.size(); i++) { IGroupDefinition group = (IGroupDefinition) groups.get(i); if ( groupText.equals( group.getName()) || groupText.equals( group.getKeyColumn() ) || groupText.equals( group.getKeyExpression()) ) { return i + 1; // Note that group index is 1-based } } return -1; } /** * Gets the group count defined in report query */ int getGroupCount() { assert queryDefn != null; return queryDefn.getGroups().size(); } /** * PreparedQuery.Executor: executes a prepared query and maintains execute-time data and result * set associated with an execution. * * A PreparedQuery can be executed multiple times. Each execute is performed by one instance of * the Executor. * * Each subclass of PreparedQuery is expected to have its own subclass of the Executor. */ abstract class Executor { protected IQuery odiQuery; protected IDataSource odiDataSource; protected DataSourceRuntime dataSource; protected DataSetRuntime dataSet; protected AggregateCalculator aggregates; protected IResultIterator odiResult; protected JSRowObject rowObject; protected JSRows rowsObject; protected JSOutputParams outputParamsJSObject; protected Scriptable scope; protected IQueryResults outerResults; private boolean isPrepared = false; private boolean isExecuted = false; private Object queryAppContext; /** * Overridden by subclass to create a new unopened odiDataSource given the data * source runtime definition */ abstract protected IDataSource createOdiDataSource( ) throws DataException; /** * Overridden by subclass to provide the actual DataSourceRuntime used for the query. */ abstract protected DataSourceRuntime findDataSource( ) throws DataException; /** * Overridden by subclass to create a new instance of data set runtime */ abstract protected DataSetRuntime newDataSetRuntime( ) throws DataException; /** * Overridden by sub class to create an emty instance of odi query */ abstract protected IQuery createOdiQuery( ) throws DataException; /** * Executes the ODI query to reproduce a ODI result set */ abstract protected IResultIterator executeOdiQuery( ) throws DataException; /** * Prepares the ODI query */ protected void prepareOdiQuery( ) throws DataException { } /** * Constructor */ public Executor( ) { } protected Object getAppContext() { return queryAppContext; } protected void setAppContext( Object context ) { queryAppContext = context; } /* * Prepare Executor so that it is ready to execute the query * */ private void prepareExecution( IQueryResults outerRts, Scriptable targetScope ) throws DataException { if(isPrepared)return; dataSource = findDataSource( ); if ( targetScope == null ) { if ( this.dataSource != null ) { dataSource.setScope( DataEngineImpl.createSubscope(engine.getSharedScope( )) ); this.scope = DataEngineImpl.createSubscope( this.dataSource.getScriptable( ) ); } else this.scope = DataEngineImpl.createSubscope( engine.getSharedScope( ) ); } else { if ( this.dataSource != null ) { dataSource.setScope( createSubscope (targetScope) ); this.scope = createSubscope( this.dataSource.getScriptable( ) ); } else this.scope = targetScope; } openDataSource( ); //this.scope = DataEngineImpl.createSubscope( this.dataSource.getScriptable()); this.outerResults = outerRts; // Create the data set runtime // Since data set runtime contains the execution result, a new data set // runtime is needed for each execute dataSet = newDataSetRuntime(); // Set up the Javascript "row" object; this is needed before executeOdiQuery // since filtering may need the object rowObject = new JSRowObject( dataSet ); this.scope.put( "row", this.scope, rowObject ); if ( dataSet != null ) { // Run beforeOpen script now so the script can modify the DataSetRuntime properties dataSet.beforeOpen(); } ExpressionProcessorManager.registerInstance(new ExpressionProcessor( null, null, scope, null )); // Let subclass create a new and empty intance of the appropriate odi IQuery odiQuery = createOdiQuery( ); populateOdiQuery( ); prepareOdiQuery( ); isPrepared = true; } /** * Creates a new child scope using given parent */ private Scriptable createSubscope( Scriptable parent ) { Context cx = Context.enter( ); try { Scriptable scope = cx.newObject( parent ); //scope.setPrototype( prototype ); scope.setParentScope( parent ); return scope; } catch ( JavaScriptException e ) { // Not expected; use provided scrope instead logger.logp( Level.WARNING, DataEngineImpl.class.getName( ), "createSubscope", "Failed to create sub scope", e ); return parent; } finally { Context.exit( ); } } public IResultMetaData getResultMetaData( ) throws DataException { assert odiQuery instanceof IPreparedDSQuery || odiQuery instanceof ICandidateQuery; if ( odiQuery instanceof IPreparedDSQuery ) { if ( ( (IPreparedDSQuery) odiQuery ).getResultClass( ) != null ) return new ResultMetaData( ( (IPreparedDSQuery) odiQuery ).getResultClass( ) ); else return null; } else { return new ResultMetaData( ( (ICandidateQuery) odiQuery ).getResultClass( ) ); } } public void execute() throws DataException { logger.logp( Level.FINER, PreparedQuery.Executor.class.getName( ), "execute", "Start to execute" ); if(this.isExecuted) return; // Set the Javascript "rows" object and bind it to our result rowsObject = new JSRows( this.outerResults, rowObject ); scope.put( "rows", scope, rowsObject ); outputParamsJSObject = new JSOutputParams( ); scope.put( "outputParams", scope, outputParamsJSObject ); // Execute the query odiResult = executeOdiQuery( ); // Bind the row object to the odi result set rowObject.setResultSet( odiResult, false ); // Calculate aggregate values aggregates = new AggregateCalculator( aggrTable, odiResult ); // Set up the internal JS _aggr_value object and bind it to the aggregate calc engine Scriptable aggrObj = aggregates.getJSAggrValueObject(); scope.put( ExpressionCompiler.AGGR_VALUE, scope, aggrObj ); Context cx = Context.enter(); try { // Calculate aggregate values aggregates.calculate(cx, scope); } finally { Context.exit(); } this.isExecuted = true; logger.logp( Level.FINER, PreparedQuery.Executor.class.getName( ), "execute", "Finish executing" ); } /** * Closes the executor; release all odi resources */ public void close() { if ( odiQuery == null ) { // already closed logger.logp( Level.FINER, PreparedQuery.Executor.class.getName( ), "close", "executor closed " ); return; } // Close the data set and associated odi query try { if ( dataSet != null ) dataSet.beforeClose(); } catch (DataException e ) { logger.logp( Level.FINE, PreparedQuery.Executor.class.getName( ), "close", e.getMessage( ), e ); } if ( odiResult != null ) odiResult.close(); odiQuery.close(); try { if ( dataSet != null ) { dataSet.close(); } } catch (DataException e ) { logger.logp( Level.FINE, PreparedQuery.Executor.class.getName( ), "close", e.getMessage( ), e ); } odiQuery = null; odiDataSource = null; aggregates = null; odiResult = null; rowObject = null; rowsObject = null; scope = null; isPrepared = false; isExecuted = false; // Note: reset dataSet and dataSource only after afterClose() is executed, since // the script may access these two objects if ( dataSet != null ) { try { dataSet.afterClose(); } catch (DataException e ) { logger.logp( Level.FINE, PreparedQuery.Executor.class.getName( ), "close", e.getMessage( ), e ); } dataSet = null; } dataSource = null; logger.logp( Level.FINER, PreparedQuery.Executor.class.getName( ), "close", "executor closed " ); } /** * Open the required DataSource. This method should be called after "dataSource" * is initialized by findDataSource() method. * @throws DataException */ protected void openDataSource( ) throws DataException { assert odiDataSource == null; // Open the underlying data source // dataSource = findDataSource( ); if ( dataSource != null ) { if ( ! dataSource.isOpen() ) { // Data source is not open; create an Odi Data Source and open it // We should run the beforeOpen script now to give it a chance to modify // runtime data source properties dataSource.beforeOpen(); // Let subclass create a new unopened odi data source odiDataSource = createOdiDataSource( ); // Passes thru the prepared query executor's // context to the new odi data source odiDataSource.setAppContext( getAppContext() ); // Open the odi data source dataSource.openOdiDataSource( odiDataSource ); dataSource.afterOpen(); } else { // Use existing odiDataSource created for the data source runtime odiDataSource = dataSource.getOdiDataSource(); // Passes thru the prepared query executor's // current context to existing data source odiDataSource.setAppContext( getAppContext() ); } } } /** * Populates odiQuery with this query's definitions */ protected void populateOdiQuery( ) throws DataException { assert odiQuery != null; assert scope != null; assert queryDefn != null; Context cx = Context.enter(); try { List ar = new ArrayList(); // Set grouping List groups = queryDefn.getGroups(); if ( groups != null && ! groups.isEmpty() ) { IQuery.GroupSpec[] groupSpecs = new IQuery.GroupSpec[ groups.size() ]; Iterator it = groups.iterator(); for ( int i = 0; it.hasNext(); i++ ) { IGroupDefinition src = (IGroupDefinition) it.next(); //TODO does the index of column significant? IQuery.GroupSpec dest = groupDefnToSpec(cx, src,"_{$TEMP_GROUP_"+i+"$}_", -1 ); groupSpecs[i] = dest; if(isCurrentGroupKeyComplexExpression) ar.add(new ComputedColumn( "_{$TEMP_GROUP_"+i+"$}_", src.getKeyExpression(), DataType.ANY_TYPE)); } odiQuery.setGrouping( Arrays.asList( groupSpecs)); } // Set sorting List sorts = queryDefn.getSorts(); if ( sorts != null && !sorts.isEmpty( ) ) { IQuery.SortSpec[] sortSpecs = new IQuery.SortSpec[ sorts.size() ]; Iterator it = sorts.iterator(); for ( int i = 0; it.hasNext(); i++ ) { ISortDefinition src = (ISortDefinition) it.next(); int sortIndex = -1; String sortKey = src.getColumn(); if ( sortKey == null || sortKey.length() == 0 ) { //Firstly try to treat sort key as a column reference expression ColumnInfo columnInfo = getColInfoFromJSExpr( cx, src.getExpression( ) ); sortIndex = columnInfo.getColumnIndex(); sortKey = columnInfo.getColumnName( ); } if ( sortKey == null && sortIndex < 0 ) { //If failed to treate sort key as a column reference expression //then treat it as a computed column expression ar.add(new ComputedColumn( "_{$TEMP_SORT_"+i+"$}_", src.getExpression(), DataType.ANY_TYPE)); sortIndex = -1; sortKey = String.valueOf("_{$TEMP_SORT_"+i+"$}_"); } IQuery.SortSpec dest = new IQuery.SortSpec( sortIndex, sortKey, src.getSortDirection( ) == ISortDefinition.SORT_ASC ); sortSpecs[i] = dest; } odiQuery.setOrdering( Arrays.asList( sortSpecs)); } List computedColumns = null; // set computed column event if ( dataSet != null ) { computedColumns = this.dataSet.getComputedColumns( ); if ( computedColumns != null ) { computedColumns.addAll( ar ); } } - if ( computedColumns != null || ar.size( ) > 0 ) + if ( (computedColumns != null && computedColumns.size() > 0)|| ar.size( ) > 0 ) { IResultObjectEvent objectEvent = new ComputedColumnHelper( ExpressionProcessorManager.getInstance( ) .getScope( ), this.rowObject, computedColumns == null ? ar : computedColumns ); odiQuery.addOnFetchEvent( objectEvent ); } // set Onfetch event - this should be added after computed column and before filtering if ( dataSet != null ) { String onFetchScript = dataSet.getOnFetchScript(); if ( onFetchScript != null && onFetchScript.length() > 0 ) { OnFetchScriptHelper event = new OnFetchScriptHelper( dataSet ); odiQuery.addOnFetchEvent( event ); } } // Set filtering assert rowObject != null; assert scope != null; // set filter event List mergedFilters = new ArrayList( ); if ( queryDefn.getFilters( ) != null ) { mergedFilters.addAll( queryDefn.getFilters( ) ); } if ( dataSet != null && dataSet.getFilters( ) != null ) { mergedFilters.addAll( dataSet.getFilters( ) ); } if ( mergedFilters.size() > 0 ) { IResultObjectEvent objectEvent = new FilterByRow( mergedFilters, ExpressionProcessorManager.getInstance().getScope(), rowObject ); odiQuery.addOnFetchEvent( objectEvent ); } // specify max rows the query should fetch odiQuery.setMaxRows( queryDefn.getMaxRows() ); } finally { Context.exit(); } } } /** * Simple wrapper of colum information, including * column index and column name. */ private static class ColumnInfo { private int columnIndex; private String columnName; ColumnInfo(int columnIndex, String columnName) { this.columnIndex = columnIndex; this.columnName = columnName; } public int getColumnIndex() { return columnIndex; } public String getColumnName() { return columnName; } } }
true
true
protected void populateOdiQuery( ) throws DataException { assert odiQuery != null; assert scope != null; assert queryDefn != null; Context cx = Context.enter(); try { List ar = new ArrayList(); // Set grouping List groups = queryDefn.getGroups(); if ( groups != null && ! groups.isEmpty() ) { IQuery.GroupSpec[] groupSpecs = new IQuery.GroupSpec[ groups.size() ]; Iterator it = groups.iterator(); for ( int i = 0; it.hasNext(); i++ ) { IGroupDefinition src = (IGroupDefinition) it.next(); //TODO does the index of column significant? IQuery.GroupSpec dest = groupDefnToSpec(cx, src,"_{$TEMP_GROUP_"+i+"$}_", -1 ); groupSpecs[i] = dest; if(isCurrentGroupKeyComplexExpression) ar.add(new ComputedColumn( "_{$TEMP_GROUP_"+i+"$}_", src.getKeyExpression(), DataType.ANY_TYPE)); } odiQuery.setGrouping( Arrays.asList( groupSpecs)); } // Set sorting List sorts = queryDefn.getSorts(); if ( sorts != null && !sorts.isEmpty( ) ) { IQuery.SortSpec[] sortSpecs = new IQuery.SortSpec[ sorts.size() ]; Iterator it = sorts.iterator(); for ( int i = 0; it.hasNext(); i++ ) { ISortDefinition src = (ISortDefinition) it.next(); int sortIndex = -1; String sortKey = src.getColumn(); if ( sortKey == null || sortKey.length() == 0 ) { //Firstly try to treat sort key as a column reference expression ColumnInfo columnInfo = getColInfoFromJSExpr( cx, src.getExpression( ) ); sortIndex = columnInfo.getColumnIndex(); sortKey = columnInfo.getColumnName( ); } if ( sortKey == null && sortIndex < 0 ) { //If failed to treate sort key as a column reference expression //then treat it as a computed column expression ar.add(new ComputedColumn( "_{$TEMP_SORT_"+i+"$}_", src.getExpression(), DataType.ANY_TYPE)); sortIndex = -1; sortKey = String.valueOf("_{$TEMP_SORT_"+i+"$}_"); } IQuery.SortSpec dest = new IQuery.SortSpec( sortIndex, sortKey, src.getSortDirection( ) == ISortDefinition.SORT_ASC ); sortSpecs[i] = dest; } odiQuery.setOrdering( Arrays.asList( sortSpecs)); } List computedColumns = null; // set computed column event if ( dataSet != null ) { computedColumns = this.dataSet.getComputedColumns( ); if ( computedColumns != null ) { computedColumns.addAll( ar ); } } if ( computedColumns != null || ar.size( ) > 0 ) { IResultObjectEvent objectEvent = new ComputedColumnHelper( ExpressionProcessorManager.getInstance( ) .getScope( ), this.rowObject, computedColumns == null ? ar : computedColumns ); odiQuery.addOnFetchEvent( objectEvent ); } // set Onfetch event - this should be added after computed column and before filtering if ( dataSet != null ) { String onFetchScript = dataSet.getOnFetchScript(); if ( onFetchScript != null && onFetchScript.length() > 0 ) { OnFetchScriptHelper event = new OnFetchScriptHelper( dataSet ); odiQuery.addOnFetchEvent( event ); } } // Set filtering assert rowObject != null; assert scope != null; // set filter event List mergedFilters = new ArrayList( ); if ( queryDefn.getFilters( ) != null ) { mergedFilters.addAll( queryDefn.getFilters( ) ); } if ( dataSet != null && dataSet.getFilters( ) != null ) { mergedFilters.addAll( dataSet.getFilters( ) ); } if ( mergedFilters.size() > 0 ) { IResultObjectEvent objectEvent = new FilterByRow( mergedFilters, ExpressionProcessorManager.getInstance().getScope(), rowObject ); odiQuery.addOnFetchEvent( objectEvent ); } // specify max rows the query should fetch odiQuery.setMaxRows( queryDefn.getMaxRows() ); } finally { Context.exit(); } }
protected void populateOdiQuery( ) throws DataException { assert odiQuery != null; assert scope != null; assert queryDefn != null; Context cx = Context.enter(); try { List ar = new ArrayList(); // Set grouping List groups = queryDefn.getGroups(); if ( groups != null && ! groups.isEmpty() ) { IQuery.GroupSpec[] groupSpecs = new IQuery.GroupSpec[ groups.size() ]; Iterator it = groups.iterator(); for ( int i = 0; it.hasNext(); i++ ) { IGroupDefinition src = (IGroupDefinition) it.next(); //TODO does the index of column significant? IQuery.GroupSpec dest = groupDefnToSpec(cx, src,"_{$TEMP_GROUP_"+i+"$}_", -1 ); groupSpecs[i] = dest; if(isCurrentGroupKeyComplexExpression) ar.add(new ComputedColumn( "_{$TEMP_GROUP_"+i+"$}_", src.getKeyExpression(), DataType.ANY_TYPE)); } odiQuery.setGrouping( Arrays.asList( groupSpecs)); } // Set sorting List sorts = queryDefn.getSorts(); if ( sorts != null && !sorts.isEmpty( ) ) { IQuery.SortSpec[] sortSpecs = new IQuery.SortSpec[ sorts.size() ]; Iterator it = sorts.iterator(); for ( int i = 0; it.hasNext(); i++ ) { ISortDefinition src = (ISortDefinition) it.next(); int sortIndex = -1; String sortKey = src.getColumn(); if ( sortKey == null || sortKey.length() == 0 ) { //Firstly try to treat sort key as a column reference expression ColumnInfo columnInfo = getColInfoFromJSExpr( cx, src.getExpression( ) ); sortIndex = columnInfo.getColumnIndex(); sortKey = columnInfo.getColumnName( ); } if ( sortKey == null && sortIndex < 0 ) { //If failed to treate sort key as a column reference expression //then treat it as a computed column expression ar.add(new ComputedColumn( "_{$TEMP_SORT_"+i+"$}_", src.getExpression(), DataType.ANY_TYPE)); sortIndex = -1; sortKey = String.valueOf("_{$TEMP_SORT_"+i+"$}_"); } IQuery.SortSpec dest = new IQuery.SortSpec( sortIndex, sortKey, src.getSortDirection( ) == ISortDefinition.SORT_ASC ); sortSpecs[i] = dest; } odiQuery.setOrdering( Arrays.asList( sortSpecs)); } List computedColumns = null; // set computed column event if ( dataSet != null ) { computedColumns = this.dataSet.getComputedColumns( ); if ( computedColumns != null ) { computedColumns.addAll( ar ); } } if ( (computedColumns != null && computedColumns.size() > 0)|| ar.size( ) > 0 ) { IResultObjectEvent objectEvent = new ComputedColumnHelper( ExpressionProcessorManager.getInstance( ) .getScope( ), this.rowObject, computedColumns == null ? ar : computedColumns ); odiQuery.addOnFetchEvent( objectEvent ); } // set Onfetch event - this should be added after computed column and before filtering if ( dataSet != null ) { String onFetchScript = dataSet.getOnFetchScript(); if ( onFetchScript != null && onFetchScript.length() > 0 ) { OnFetchScriptHelper event = new OnFetchScriptHelper( dataSet ); odiQuery.addOnFetchEvent( event ); } } // Set filtering assert rowObject != null; assert scope != null; // set filter event List mergedFilters = new ArrayList( ); if ( queryDefn.getFilters( ) != null ) { mergedFilters.addAll( queryDefn.getFilters( ) ); } if ( dataSet != null && dataSet.getFilters( ) != null ) { mergedFilters.addAll( dataSet.getFilters( ) ); } if ( mergedFilters.size() > 0 ) { IResultObjectEvent objectEvent = new FilterByRow( mergedFilters, ExpressionProcessorManager.getInstance().getScope(), rowObject ); odiQuery.addOnFetchEvent( objectEvent ); } // specify max rows the query should fetch odiQuery.setMaxRows( queryDefn.getMaxRows() ); } finally { Context.exit(); } }
diff --git a/src/edu/worcester/cs499summer2012/activity/AddTaskActivity.java b/src/edu/worcester/cs499summer2012/activity/AddTaskActivity.java index 8e34ad2..51838e2 100644 --- a/src/edu/worcester/cs499summer2012/activity/AddTaskActivity.java +++ b/src/edu/worcester/cs499summer2012/activity/AddTaskActivity.java @@ -1,492 +1,493 @@ /* * AddTaskActivity.java * * Copyright 2012 Jonathan Hasenzahl, James Celona, Dhimitraq Jorgji * * 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 edu.worcester.cs499summer2012.activity; import java.util.Calendar; import java.util.GregorianCalendar; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.DatePicker; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import edu.worcester.cs499summer2012.R; import edu.worcester.cs499summer2012.database.TasksDataSource; import edu.worcester.cs499summer2012.task.Task; /** * Activity for adding a new task. * @author Jonathan Hasenzahl * @author James Celona */ public class AddTaskActivity extends SherlockActivity implements OnCheckedChangeListener, OnClickListener, DialogInterface.OnClickListener { /************************************************************************** * Static fields and methods * **************************************************************************/ public final static int DEFAULT_HOUR = 12; public final static int DEFAULT_MINUTE = 0; public final static int DEFAULT_SECOND = 0; public final static int DEFAULT_MILLISECOND = 0; public final static String DEFAULT_INTERVAL = "1"; /************************************************************************** * Private fields * **************************************************************************/ // Intent to be returned private Intent intent; // UI elements private CheckBox has_due_date; private Button edit_due_date; private TextView due_date; private CheckBox has_final_due_date; private Button edit_final_due_date; private TextView final_due_date; private CheckBox has_repetition; private TextView repeats; private EditText repeat_interval; private Spinner repeat_type; private CheckBox stop_repeating; private Button edit_stop_repeating_date; private TextView stop_repeating_date; private DatePicker date_picker; private TimePicker time_picker; // Task properties that are modified by UI elements private Calendar due_date_cal; private Calendar final_due_date_cal; private Calendar stop_repeating_date_cal; private int selected_calendar; /************************************************************************** * Class methods * **************************************************************************/ /** * This method is called when the user clicks the OK button. A new task is * created based on user input. The task is added as an extra parcel to a * return intent, and the activity finishes. * @param view The view from which the user called this method */ public boolean addTask() { // Get task name - EditText name = (EditText) findViewById(R.id.edit_add_task_name); + EditText et_name = (EditText) findViewById(R.id.edit_add_task_name); + String name = et_name.getText().toString(); // If there is no task name, don't create the task if (name.equals("")) { Toast.makeText(this, "Task needs a name!", Toast.LENGTH_SHORT).show(); return false; } // Get completion status CheckBox is_completed = (CheckBox) findViewById(R.id.checkbox_already_completed); // Get task priority RadioGroup task_priority = (RadioGroup) findViewById(R.id.radiogroup_add_task_priority); int priority; switch (task_priority.getCheckedRadioButtonId()) { case R.id.radio_add_task_urgent: priority = Task.URGENT; break; case R.id.radio_add_task_trivial: priority = Task.TRIVIAL; break; case R.id.radio_add_task_normal: default: priority = Task.NORMAL; break; } // Get task category // TODO: Implement this int category = 0; // Get repeat interval int interval = 1; String interval_string = repeat_interval.getText().toString(); if (!interval_string.equals("")) { interval = Integer.parseInt(interval_string); if (interval == 0) interval = 1; } // Get task due date long due_date_ms = 0; if (has_due_date.isChecked()) due_date_ms = due_date_cal.getTimeInMillis(); // Get task final due date long final_due_date_ms = 0; if (has_final_due_date.isChecked()) final_due_date_ms = final_due_date_cal.getTimeInMillis(); // Get stop repeating date long stop_repeating_date_ms = 0; if (stop_repeating.isChecked()) stop_repeating_date_ms = stop_repeating_date_cal.getTimeInMillis(); // Get task notes EditText notes = (EditText) findViewById(R.id.edit_add_task_notes); // Create the task Task task = new Task( - name.getText().toString(), + name, is_completed.isChecked(), priority, category, has_due_date.isChecked(), has_final_due_date.isChecked(), has_repetition.isChecked(), stop_repeating.isChecked(), repeat_type.getSelectedItemPosition(), interval, GregorianCalendar.getInstance().getTimeInMillis(), due_date_ms, final_due_date_ms, stop_repeating_date_ms, notes.getText().toString()); // Assign the task a unique ID and store it in the database TasksDataSource tds = TasksDataSource.getInstance(this); task.setID(tds.getNextID()); tds.addTask(task); // Create the return intent and add the task ID intent = new Intent(this, MainActivity.class); intent.putExtra(Task.EXTRA_TASK_ID, task.getID()); return true; } /************************************************************************** * Overridden parent methods * **************************************************************************/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_task); // Initialize the fields that can be enabled/disabled or listened to has_due_date = (CheckBox) findViewById(R.id.checkbox_has_due_date); edit_due_date = (Button) findViewById(R.id.button_edit_due_date); due_date = (TextView) findViewById(R.id.text_add_task_due_date); has_final_due_date = (CheckBox) findViewById(R.id.checkbox_has_final_due_date); edit_final_due_date = (Button) findViewById(R.id.button_edit_final_due_date); final_due_date = (TextView) findViewById(R.id.text_add_task_final_due_date); has_repetition = (CheckBox) findViewById(R.id.checkbox_has_repetition); repeats = (TextView) findViewById(R.id.text_add_task_repeats); repeat_interval = (EditText) findViewById(R.id.edit_add_task_repeat_interval); repeat_type = (Spinner) findViewById(R.id.spinner_add_task_repeat_type); stop_repeating = (CheckBox) findViewById(R.id.checkbox_stop_repeating); edit_stop_repeating_date = (Button) findViewById(R.id.button_edit_stop_repeating_date); stop_repeating_date = (TextView) findViewById(R.id.text_add_task_stop_repeating_date); // Initialize calendars to default values due_date_cal = GregorianCalendar.getInstance(); due_date_cal.set(Calendar.HOUR_OF_DAY, DEFAULT_HOUR); due_date_cal.set(Calendar.MINUTE, DEFAULT_MINUTE); due_date_cal.set(Calendar.SECOND, DEFAULT_SECOND); due_date_cal.set(Calendar.MILLISECOND, DEFAULT_MILLISECOND); final_due_date_cal = GregorianCalendar.getInstance(); final_due_date_cal.set(Calendar.HOUR_OF_DAY, DEFAULT_HOUR); final_due_date_cal.set(Calendar.MINUTE, DEFAULT_MINUTE); final_due_date_cal.set(Calendar.SECOND, DEFAULT_SECOND); final_due_date_cal.set(Calendar.MILLISECOND, DEFAULT_MILLISECOND); stop_repeating_date_cal = GregorianCalendar.getInstance(); stop_repeating_date_cal.set(Calendar.HOUR_OF_DAY, DEFAULT_HOUR); stop_repeating_date_cal.set(Calendar.MINUTE, DEFAULT_MINUTE); stop_repeating_date_cal.set(Calendar.SECOND, DEFAULT_SECOND); stop_repeating_date_cal.set(Calendar.MILLISECOND, DEFAULT_MILLISECOND); // Set listeners has_due_date.setOnCheckedChangeListener(this); has_final_due_date.setOnCheckedChangeListener(this); has_repetition.setOnCheckedChangeListener(this); stop_repeating.setOnCheckedChangeListener(this); edit_due_date.setOnClickListener(this); edit_final_due_date.setOnClickListener(this); edit_stop_repeating_date.setOnClickListener(this); // Hide certain due date items to start edit_due_date.setVisibility(View.GONE); due_date.setVisibility(View.GONE); has_final_due_date.setVisibility(View.GONE); edit_final_due_date.setVisibility(View.GONE); final_due_date.setVisibility(View.GONE); has_repetition.setVisibility(View.GONE); repeats.setVisibility(View.GONE); repeat_interval.setVisibility(View.GONE); repeat_type.setVisibility(View.GONE); stop_repeating.setVisibility(View.GONE); edit_stop_repeating_date.setVisibility(View.GONE); stop_repeating_date.setVisibility(View.GONE); // Allow Action bar icon to act as a button getSupportActionBar().setHomeButtonEnabled(true); // Populate the repeat type spinner ArrayAdapter<CharSequence> repeat_type_adapter = ArrayAdapter.createFromResource(this, R.array.spinner_repeat_types, android.R.layout.simple_spinner_item); repeat_type_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); repeat_type.setAdapter(repeat_type_adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.activity_add_task, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: case R.id.menu_add_task_cancel: setResult(RESULT_CANCELED); finish(); return true; case R.id.menu_add_task_confirm: if (addTask()) { // Set the return result to OK and finish the activity setResult(RESULT_OK, intent); finish(); } return true; default: return super.onOptionsItemSelected(item); } } /************************************************************************** * Methods implementing OnCheckedChangedListener interface * **************************************************************************/ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { switch (buttonView.getId()) { case R.id.checkbox_has_due_date: if (isChecked) { // Make edit button, textview, and other checkboxes visible edit_due_date.setVisibility(View.VISIBLE); due_date.setVisibility(View.VISIBLE); due_date.setText(DateFormat.format("'Due:' MM/dd/yy 'at' h:mm AA", due_date_cal)); has_final_due_date.setVisibility(View.VISIBLE); has_repetition.setVisibility(View.VISIBLE); // Pop up date-time dialog as if user had clicked edit button onClick(edit_due_date); } else { // Hide edit button, textview, and other checkboxes edit_due_date.setVisibility(View.GONE); due_date.setVisibility(View.GONE); has_final_due_date.setVisibility(View.GONE); has_repetition.setVisibility(View.GONE); // Uncheck final due date and repetition boxes if (has_final_due_date.isChecked()) has_final_due_date.setChecked(false); if (has_repetition.isChecked()) has_repetition.setChecked(false); } break; case R.id.checkbox_has_final_due_date: if (isChecked) { // Make edit button and textview visible edit_final_due_date.setVisibility(View.VISIBLE); final_due_date.setVisibility(View.VISIBLE); final_due_date.setText(DateFormat.format("'Alarm:' MM/dd/yy 'at' h:mm AA", final_due_date_cal)); // Pop up date-time dialog as if user had clicked edit button onClick(edit_final_due_date); } else { // Hide edit button and textview edit_final_due_date.setVisibility(View.GONE); final_due_date.setVisibility(View.GONE); } break; case R.id.checkbox_has_repetition: if (isChecked) { // Make textview, edittext, spinner, and checkbox visible repeats.setVisibility(View.VISIBLE); repeat_interval.setVisibility(View.VISIBLE); repeat_interval.setText(DEFAULT_INTERVAL); repeat_type.setVisibility(View.VISIBLE); stop_repeating.setVisibility(View.VISIBLE); } else { // Hide textview, edittext, spinner, and checkbox repeats.setVisibility(View.GONE); repeat_interval.setVisibility(View.GONE); repeat_type.setVisibility(View.GONE); stop_repeating.setVisibility(View.GONE); // Uncheck stop repeating box if (stop_repeating.isChecked()) stop_repeating.setChecked(false); } break; case R.id.checkbox_stop_repeating: if (isChecked) { // Make edit button and textview visible edit_stop_repeating_date.setVisibility(View.VISIBLE); stop_repeating_date.setVisibility(View.VISIBLE); stop_repeating_date.setText(DateFormat.format("'Ends:' MM/dd/yy 'at' h:mm AA", stop_repeating_date_cal)); // Pop up date-time dialog as if user had clicked edit button onClick(edit_stop_repeating_date); } else { // Hide edit button and textview edit_stop_repeating_date.setVisibility(View.GONE); stop_repeating_date.setVisibility(View.GONE); } } } /************************************************************************** * Methods implementing OnClickListener interface * **************************************************************************/ @Override public void onClick(View v) { LayoutInflater li = LayoutInflater.from(this); View picker_view = li.inflate(R.layout.date_time_picker, null); date_picker = (DatePicker) picker_view.findViewById(R.id.dialog_date_picker); time_picker = (TimePicker) picker_view.findViewById(R.id.dialog_time_picker); switch (v.getId()) { case R.id.button_edit_due_date: selected_calendar = R.id.button_edit_due_date; date_picker.updateDate(due_date_cal.get(Calendar.YEAR), due_date_cal.get(Calendar.MONTH), due_date_cal.get(Calendar.DAY_OF_MONTH)); time_picker.setCurrentHour(due_date_cal.get(Calendar.HOUR_OF_DAY)); time_picker.setCurrentMinute(due_date_cal.get(Calendar.MINUTE)); break; case R.id.button_edit_final_due_date: selected_calendar = R.id.button_edit_final_due_date; date_picker.updateDate(final_due_date_cal.get(Calendar.YEAR), final_due_date_cal.get(Calendar.MONTH), final_due_date_cal.get(Calendar.DAY_OF_MONTH)); time_picker.setCurrentHour(final_due_date_cal.get(Calendar.HOUR_OF_DAY)); time_picker.setCurrentMinute(final_due_date_cal.get(Calendar.MINUTE)); break; case R.id.button_edit_stop_repeating_date: selected_calendar = R.id.button_edit_stop_repeating_date; date_picker.updateDate(stop_repeating_date_cal.get(Calendar.YEAR), stop_repeating_date_cal.get(Calendar.MONTH), stop_repeating_date_cal.get(Calendar.DAY_OF_MONTH)); time_picker.setCurrentHour(stop_repeating_date_cal.get(Calendar.HOUR_OF_DAY)); time_picker.setCurrentMinute(stop_repeating_date_cal.get(Calendar.MINUTE)); } AlertDialog.Builder picker_dialog = new AlertDialog.Builder(this); picker_dialog.setView(picker_view) .setTitle("Set date and time") .setCancelable(true) .setPositiveButton("Accept", this) .setNegativeButton("Cancel", this); picker_dialog.show(); } /************************************************************************** * Methods implementing DialogInterface.OnClickListener interface * **************************************************************************/ @Override public void onClick(DialogInterface dialog, int id) { if (id == DialogInterface.BUTTON_POSITIVE) { switch (selected_calendar) { case R.id.button_edit_due_date: due_date_cal.set(Calendar.YEAR, date_picker.getYear()); due_date_cal.set(Calendar.MONTH, date_picker.getMonth()); due_date_cal.set(Calendar.DAY_OF_MONTH, date_picker.getDayOfMonth()); due_date_cal.set(Calendar.HOUR_OF_DAY, time_picker.getCurrentHour()); due_date_cal.set(Calendar.MINUTE, time_picker.getCurrentMinute()); due_date.setText(DateFormat.format("'Due:' MM/dd/yy 'at' h:mm AA", due_date_cal)); break; case R.id.button_edit_final_due_date: final_due_date_cal.set(Calendar.YEAR, date_picker.getYear()); final_due_date_cal.set(Calendar.MONTH, date_picker.getMonth()); final_due_date_cal.set(Calendar.DAY_OF_MONTH, date_picker.getDayOfMonth()); final_due_date_cal.set(Calendar.HOUR_OF_DAY, time_picker.getCurrentHour()); final_due_date_cal.set(Calendar.MINUTE, time_picker.getCurrentMinute()); final_due_date.setText(DateFormat.format("'Alarm:' MM/dd/yy 'at' h:mm AA", final_due_date_cal)); break; case R.id.button_edit_stop_repeating_date: stop_repeating_date_cal.set(Calendar.YEAR, date_picker.getYear()); stop_repeating_date_cal.set(Calendar.MONTH, date_picker.getMonth()); stop_repeating_date_cal.set(Calendar.DAY_OF_MONTH, date_picker.getDayOfMonth()); stop_repeating_date_cal.set(Calendar.HOUR_OF_DAY, time_picker.getCurrentHour()); stop_repeating_date_cal.set(Calendar.MINUTE, time_picker.getCurrentMinute()); stop_repeating_date.setText(DateFormat.format("'Ends:' MM/dd/yy 'at' h:mm AA", stop_repeating_date_cal)); break; } } } }
false
true
public boolean addTask() { // Get task name EditText name = (EditText) findViewById(R.id.edit_add_task_name); // If there is no task name, don't create the task if (name.equals("")) { Toast.makeText(this, "Task needs a name!", Toast.LENGTH_SHORT).show(); return false; } // Get completion status CheckBox is_completed = (CheckBox) findViewById(R.id.checkbox_already_completed); // Get task priority RadioGroup task_priority = (RadioGroup) findViewById(R.id.radiogroup_add_task_priority); int priority; switch (task_priority.getCheckedRadioButtonId()) { case R.id.radio_add_task_urgent: priority = Task.URGENT; break; case R.id.radio_add_task_trivial: priority = Task.TRIVIAL; break; case R.id.radio_add_task_normal: default: priority = Task.NORMAL; break; } // Get task category // TODO: Implement this int category = 0; // Get repeat interval int interval = 1; String interval_string = repeat_interval.getText().toString(); if (!interval_string.equals("")) { interval = Integer.parseInt(interval_string); if (interval == 0) interval = 1; } // Get task due date long due_date_ms = 0; if (has_due_date.isChecked()) due_date_ms = due_date_cal.getTimeInMillis(); // Get task final due date long final_due_date_ms = 0; if (has_final_due_date.isChecked()) final_due_date_ms = final_due_date_cal.getTimeInMillis(); // Get stop repeating date long stop_repeating_date_ms = 0; if (stop_repeating.isChecked()) stop_repeating_date_ms = stop_repeating_date_cal.getTimeInMillis(); // Get task notes EditText notes = (EditText) findViewById(R.id.edit_add_task_notes); // Create the task Task task = new Task( name.getText().toString(), is_completed.isChecked(), priority, category, has_due_date.isChecked(), has_final_due_date.isChecked(), has_repetition.isChecked(), stop_repeating.isChecked(), repeat_type.getSelectedItemPosition(), interval, GregorianCalendar.getInstance().getTimeInMillis(), due_date_ms, final_due_date_ms, stop_repeating_date_ms, notes.getText().toString()); // Assign the task a unique ID and store it in the database TasksDataSource tds = TasksDataSource.getInstance(this); task.setID(tds.getNextID()); tds.addTask(task); // Create the return intent and add the task ID intent = new Intent(this, MainActivity.class); intent.putExtra(Task.EXTRA_TASK_ID, task.getID()); return true; }
public boolean addTask() { // Get task name EditText et_name = (EditText) findViewById(R.id.edit_add_task_name); String name = et_name.getText().toString(); // If there is no task name, don't create the task if (name.equals("")) { Toast.makeText(this, "Task needs a name!", Toast.LENGTH_SHORT).show(); return false; } // Get completion status CheckBox is_completed = (CheckBox) findViewById(R.id.checkbox_already_completed); // Get task priority RadioGroup task_priority = (RadioGroup) findViewById(R.id.radiogroup_add_task_priority); int priority; switch (task_priority.getCheckedRadioButtonId()) { case R.id.radio_add_task_urgent: priority = Task.URGENT; break; case R.id.radio_add_task_trivial: priority = Task.TRIVIAL; break; case R.id.radio_add_task_normal: default: priority = Task.NORMAL; break; } // Get task category // TODO: Implement this int category = 0; // Get repeat interval int interval = 1; String interval_string = repeat_interval.getText().toString(); if (!interval_string.equals("")) { interval = Integer.parseInt(interval_string); if (interval == 0) interval = 1; } // Get task due date long due_date_ms = 0; if (has_due_date.isChecked()) due_date_ms = due_date_cal.getTimeInMillis(); // Get task final due date long final_due_date_ms = 0; if (has_final_due_date.isChecked()) final_due_date_ms = final_due_date_cal.getTimeInMillis(); // Get stop repeating date long stop_repeating_date_ms = 0; if (stop_repeating.isChecked()) stop_repeating_date_ms = stop_repeating_date_cal.getTimeInMillis(); // Get task notes EditText notes = (EditText) findViewById(R.id.edit_add_task_notes); // Create the task Task task = new Task( name, is_completed.isChecked(), priority, category, has_due_date.isChecked(), has_final_due_date.isChecked(), has_repetition.isChecked(), stop_repeating.isChecked(), repeat_type.getSelectedItemPosition(), interval, GregorianCalendar.getInstance().getTimeInMillis(), due_date_ms, final_due_date_ms, stop_repeating_date_ms, notes.getText().toString()); // Assign the task a unique ID and store it in the database TasksDataSource tds = TasksDataSource.getInstance(this); task.setID(tds.getNextID()); tds.addTask(task); // Create the return intent and add the task ID intent = new Intent(this, MainActivity.class); intent.putExtra(Task.EXTRA_TASK_ID, task.getID()); return true; }
diff --git a/resources/creatable-modifiable-deletable-v3/src/java/org/wyona/yanel/impl/jelly/tags/CheckboxTag.java b/resources/creatable-modifiable-deletable-v3/src/java/org/wyona/yanel/impl/jelly/tags/CheckboxTag.java index f6d8892..df1551e 100644 --- a/resources/creatable-modifiable-deletable-v3/src/java/org/wyona/yanel/impl/jelly/tags/CheckboxTag.java +++ b/resources/creatable-modifiable-deletable-v3/src/java/org/wyona/yanel/impl/jelly/tags/CheckboxTag.java @@ -1,74 +1,77 @@ package org.wyona.yanel.impl.jelly.tags; import org.apache.commons.jelly.JellyTagException; import org.apache.commons.jelly.MissingAttributeException; import org.apache.commons.jelly.XMLOutput; import org.wyona.yanel.impl.jelly.InputItemWithManySelectableOptions; import org.wyona.yanel.impl.jelly.Option; import org.xml.sax.helpers.AttributesImpl; import org.apache.log4j.Logger; public class CheckboxTag extends YanelTag { private static Logger log = Logger.getLogger(CheckboxTag.class); private InputItemWithManySelectableOptions item = null; public void setItem(InputItemWithManySelectableOptions resourceInputItem) { this.item = resourceInputItem; } public void doTag(XMLOutput out) throws MissingAttributeException, JellyTagException { try { //TODO: where to put the id. Is it used? in a <div> which is around the inputs? Option[] selection = item.getOptions(); for (int i = 0; i < selection.length; i++) { AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute(XHTML_NAMESPACE, "", "type", "CDATA", "checkbox"); attributes.addAttribute(XHTML_NAMESPACE, "", "name", "CDATA", item.getName()); attributes.addAttribute(XHTML_NAMESPACE, "", "value", "CDATA", selection[i].getValue()); - if (isSelected(selection[i]) // checked upon creation - || selection[i].getValue().equals("true") // checked during filling out the form + if (isSelected(selection[i]) // checked during filling out the form + || selection[i].getValue().equals("true") // checked upon creation ) { + log.debug("Checked!"); attributes.addAttribute(XHTML_NAMESPACE, "", "checked", "CDATA", "checked"); + } else { + log.debug("NOT Checked!"); } out.startElement("input", attributes); out.writeCDATA(selection[i].getLabel()); out.endElement("input"); out.startElement("br"); out.endElement("br"); } // Add a single hidden field to make sure that the field is always // submitted, even when no option is checked. AttributesImpl hiddenAttributes = new AttributesImpl(); hiddenAttributes.addAttribute(XHTML_NAMESPACE, "", "type", "CDATA", "hidden"); hiddenAttributes.addAttribute(XHTML_NAMESPACE, "", "id", "CDATA", getId()); hiddenAttributes.addAttribute(XHTML_NAMESPACE, "", "name", "CDATA", item.getName()); hiddenAttributes.addAttribute(XHTML_NAMESPACE, "", "value", "CDATA", ""); out.startElement("input", hiddenAttributes); out.endElement("input"); addValidationMessage(item, out); } catch (Exception e) { log.error("Tag could not be rendered.", e); } } private boolean isSelected(Option vt) { Option[] selected = item.getValue(); for (int i = 0; i < selected.length; i++) { if (selected[i].equals(vt)) return true; } return false; } }
false
true
public void doTag(XMLOutput out) throws MissingAttributeException, JellyTagException { try { //TODO: where to put the id. Is it used? in a <div> which is around the inputs? Option[] selection = item.getOptions(); for (int i = 0; i < selection.length; i++) { AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute(XHTML_NAMESPACE, "", "type", "CDATA", "checkbox"); attributes.addAttribute(XHTML_NAMESPACE, "", "name", "CDATA", item.getName()); attributes.addAttribute(XHTML_NAMESPACE, "", "value", "CDATA", selection[i].getValue()); if (isSelected(selection[i]) // checked upon creation || selection[i].getValue().equals("true") // checked during filling out the form ) { attributes.addAttribute(XHTML_NAMESPACE, "", "checked", "CDATA", "checked"); } out.startElement("input", attributes); out.writeCDATA(selection[i].getLabel()); out.endElement("input"); out.startElement("br"); out.endElement("br"); } // Add a single hidden field to make sure that the field is always // submitted, even when no option is checked. AttributesImpl hiddenAttributes = new AttributesImpl(); hiddenAttributes.addAttribute(XHTML_NAMESPACE, "", "type", "CDATA", "hidden"); hiddenAttributes.addAttribute(XHTML_NAMESPACE, "", "id", "CDATA", getId()); hiddenAttributes.addAttribute(XHTML_NAMESPACE, "", "name", "CDATA", item.getName()); hiddenAttributes.addAttribute(XHTML_NAMESPACE, "", "value", "CDATA", ""); out.startElement("input", hiddenAttributes); out.endElement("input"); addValidationMessage(item, out); } catch (Exception e) { log.error("Tag could not be rendered.", e); } }
public void doTag(XMLOutput out) throws MissingAttributeException, JellyTagException { try { //TODO: where to put the id. Is it used? in a <div> which is around the inputs? Option[] selection = item.getOptions(); for (int i = 0; i < selection.length; i++) { AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute(XHTML_NAMESPACE, "", "type", "CDATA", "checkbox"); attributes.addAttribute(XHTML_NAMESPACE, "", "name", "CDATA", item.getName()); attributes.addAttribute(XHTML_NAMESPACE, "", "value", "CDATA", selection[i].getValue()); if (isSelected(selection[i]) // checked during filling out the form || selection[i].getValue().equals("true") // checked upon creation ) { log.debug("Checked!"); attributes.addAttribute(XHTML_NAMESPACE, "", "checked", "CDATA", "checked"); } else { log.debug("NOT Checked!"); } out.startElement("input", attributes); out.writeCDATA(selection[i].getLabel()); out.endElement("input"); out.startElement("br"); out.endElement("br"); } // Add a single hidden field to make sure that the field is always // submitted, even when no option is checked. AttributesImpl hiddenAttributes = new AttributesImpl(); hiddenAttributes.addAttribute(XHTML_NAMESPACE, "", "type", "CDATA", "hidden"); hiddenAttributes.addAttribute(XHTML_NAMESPACE, "", "id", "CDATA", getId()); hiddenAttributes.addAttribute(XHTML_NAMESPACE, "", "name", "CDATA", item.getName()); hiddenAttributes.addAttribute(XHTML_NAMESPACE, "", "value", "CDATA", ""); out.startElement("input", hiddenAttributes); out.endElement("input"); addValidationMessage(item, out); } catch (Exception e) { log.error("Tag could not be rendered.", e); } }
diff --git a/src/test/java/com/openshift/express/internal/client/test/CartridgeTest.java b/src/test/java/com/openshift/express/internal/client/test/CartridgeTest.java index 55b3335..aa5194e 100644 --- a/src/test/java/com/openshift/express/internal/client/test/CartridgeTest.java +++ b/src/test/java/com/openshift/express/internal/client/test/CartridgeTest.java @@ -1,119 +1,119 @@ /******************************************************************************* * Copyright (c) 2007 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 com.openshift.express.internal.client.test; import static com.openshift.express.internal.client.test.utils.CartridgeAsserts.assertThatContainsCartridge; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URLEncoder; import java.util.List; import org.junit.Test; import com.openshift.express.client.Cartridge; import com.openshift.express.client.ICartridge; import com.openshift.express.client.OpenShiftException; import com.openshift.express.internal.client.request.ListCartridgesRequest; import com.openshift.express.internal.client.request.OpenShiftEnvelopeFactory; import com.openshift.express.internal.client.request.marshalling.ListCartridgesRequestJsonMarshaller; import com.openshift.express.internal.client.response.OpenShiftResponse; import com.openshift.express.internal.client.response.unmarshalling.JsonSanitizer; import com.openshift.express.internal.client.response.unmarshalling.ListCartridgesResponseUnmarshaller; import com.openshift.express.internal.client.test.fakes.CartridgeResponseFake; /** * @author André Dietisheim */ public class CartridgeTest { private static final String USERNAME = "[email protected]"; private static final String PASSWORD = "1q2w3e"; @Test public void canMarshallListCartridgesRequest() throws Exception { String expectedRequestString = "password=" + PASSWORD + "&json_data=%7B%22rhlogin%22+%3A+%22" + URLEncoder.encode(USERNAME, "UTF-8") + "%22%2C+%22debug%22+%3A+%22true%22%2C+%22cart_type%22+%3A+%22standalone%22%7D"; String listCartridgeRequest = new ListCartridgesRequestJsonMarshaller().marshall( new ListCartridgesRequest(USERNAME, true)); String effectiveRequest = new OpenShiftEnvelopeFactory(PASSWORD, null, null, listCartridgeRequest).createString(); assertEquals(expectedRequestString, effectiveRequest); } @Test public void canUnmarshallCartridgeListResponse() throws OpenShiftException { String cartridgeListResponse = "{" + "\"messages\":\"\"," + "\"debug\":\"\"," + "\"data\":" - + "\"{\\\"carts\\\":[\\\"perl-5.10\\\",\\\"jbossas-7.0\\\",\\\"wsgi-3.2\\\",\\\"rack-1.1\\\",\\\"php-5.3\\\"]}\"," + + "\"{\\\"carts\\\":[\\\"perl-5.10\\\",\\\"jbossas-7.0\\\",\\\"python-2.6\\\",\\\"ruby-1.8\\\",\\\"wsgi-3.2\\\",\\\"rack-1.1\\\",\\\"php-5.3\\\"]}\"," + "\"api\":\"1.1.1\"," + "\"api_c\":[\"placeholder\"]," + "\"result\":null," + "\"broker\":\"1.1.1\"," + "\"broker_c\":[" + "\"namespace\"," + "\"rhlogin\"," + "\"ssh\"," + "\"app_uuid\"," + "\"debug\"," + "\"alter\"," + "\"cartridge\"," + "\"cart_type\"," + "\"action\"," + "\"app_name\"," + "\"api" + "\"]," + "\"exit_code\":0}"; cartridgeListResponse = JsonSanitizer.sanitize(cartridgeListResponse); OpenShiftResponse<List<ICartridge>> response = new ListCartridgesResponseUnmarshaller().unmarshall(cartridgeListResponse); assertEquals("", response.getMessages()); assertEquals(false, response.isDebug()); List<ICartridge> cartridges = response.getOpenShiftObject(); - assertEquals(5, cartridges.size()); + assertEquals(7, cartridges.size()); assertThatContainsCartridge("perl-5.10", cartridges); assertThatContainsCartridge("jbossas-7.0", cartridges); assertThatContainsCartridge("python-2.6", cartridges); assertThatContainsCartridge("ruby-1.8", cartridges); assertThatContainsCartridge("php-5.3", cartridges); assertEquals(null, response.getResult()); assertEquals(0, response.getExitCode()); } @Test public void canUnmarshallApplicationResponse() throws OpenShiftException { String response = JsonSanitizer.sanitize(CartridgeResponseFake.RESPONSE); OpenShiftResponse<List<ICartridge>> openshiftResponse = new ListCartridgesResponseUnmarshaller().unmarshall(response); List<ICartridge> cartridges = openshiftResponse.getOpenShiftObject(); assertNotNull(cartridges); assertThatContainsCartridge(CartridgeResponseFake.CARTRIDGE_JBOSSAS70, cartridges); assertThatContainsCartridge(CartridgeResponseFake.CARTRIDGE_PERL5, cartridges); assertThatContainsCartridge(CartridgeResponseFake.CARTRIDGE_PHP53, cartridges); assertThatContainsCartridge(CartridgeResponseFake.CARTRIDGE_RACK11, cartridges); assertThatContainsCartridge(CartridgeResponseFake.CARTRIDGE_WSGI32, cartridges); } @Test public void cartridgeEqualsOtherCartridgeWithSameName() { assertEquals(new Cartridge("redhat"), new Cartridge("redhat")); assertEquals(ICartridge.JBOSSAS_7, new Cartridge(ICartridge.JBOSSAS_7.getName())); assertTrue(!new Cartridge("redhat").equals(new Cartridge("jboss"))); } }
false
true
public void canUnmarshallCartridgeListResponse() throws OpenShiftException { String cartridgeListResponse = "{" + "\"messages\":\"\"," + "\"debug\":\"\"," + "\"data\":" + "\"{\\\"carts\\\":[\\\"perl-5.10\\\",\\\"jbossas-7.0\\\",\\\"wsgi-3.2\\\",\\\"rack-1.1\\\",\\\"php-5.3\\\"]}\"," + "\"api\":\"1.1.1\"," + "\"api_c\":[\"placeholder\"]," + "\"result\":null," + "\"broker\":\"1.1.1\"," + "\"broker_c\":[" + "\"namespace\"," + "\"rhlogin\"," + "\"ssh\"," + "\"app_uuid\"," + "\"debug\"," + "\"alter\"," + "\"cartridge\"," + "\"cart_type\"," + "\"action\"," + "\"app_name\"," + "\"api" + "\"]," + "\"exit_code\":0}"; cartridgeListResponse = JsonSanitizer.sanitize(cartridgeListResponse); OpenShiftResponse<List<ICartridge>> response = new ListCartridgesResponseUnmarshaller().unmarshall(cartridgeListResponse); assertEquals("", response.getMessages()); assertEquals(false, response.isDebug()); List<ICartridge> cartridges = response.getOpenShiftObject(); assertEquals(5, cartridges.size()); assertThatContainsCartridge("perl-5.10", cartridges); assertThatContainsCartridge("jbossas-7.0", cartridges); assertThatContainsCartridge("python-2.6", cartridges); assertThatContainsCartridge("ruby-1.8", cartridges); assertThatContainsCartridge("php-5.3", cartridges); assertEquals(null, response.getResult()); assertEquals(0, response.getExitCode()); }
public void canUnmarshallCartridgeListResponse() throws OpenShiftException { String cartridgeListResponse = "{" + "\"messages\":\"\"," + "\"debug\":\"\"," + "\"data\":" + "\"{\\\"carts\\\":[\\\"perl-5.10\\\",\\\"jbossas-7.0\\\",\\\"python-2.6\\\",\\\"ruby-1.8\\\",\\\"wsgi-3.2\\\",\\\"rack-1.1\\\",\\\"php-5.3\\\"]}\"," + "\"api\":\"1.1.1\"," + "\"api_c\":[\"placeholder\"]," + "\"result\":null," + "\"broker\":\"1.1.1\"," + "\"broker_c\":[" + "\"namespace\"," + "\"rhlogin\"," + "\"ssh\"," + "\"app_uuid\"," + "\"debug\"," + "\"alter\"," + "\"cartridge\"," + "\"cart_type\"," + "\"action\"," + "\"app_name\"," + "\"api" + "\"]," + "\"exit_code\":0}"; cartridgeListResponse = JsonSanitizer.sanitize(cartridgeListResponse); OpenShiftResponse<List<ICartridge>> response = new ListCartridgesResponseUnmarshaller().unmarshall(cartridgeListResponse); assertEquals("", response.getMessages()); assertEquals(false, response.isDebug()); List<ICartridge> cartridges = response.getOpenShiftObject(); assertEquals(7, cartridges.size()); assertThatContainsCartridge("perl-5.10", cartridges); assertThatContainsCartridge("jbossas-7.0", cartridges); assertThatContainsCartridge("python-2.6", cartridges); assertThatContainsCartridge("ruby-1.8", cartridges); assertThatContainsCartridge("php-5.3", cartridges); assertEquals(null, response.getResult()); assertEquals(0, response.getExitCode()); }
diff --git a/src/test/java/com/tngtech/configbuilder/ConfigBuilderTest.java b/src/test/java/com/tngtech/configbuilder/ConfigBuilderTest.java index bd75d3c..1706f59 100644 --- a/src/test/java/com/tngtech/configbuilder/ConfigBuilderTest.java +++ b/src/test/java/com/tngtech/configbuilder/ConfigBuilderTest.java @@ -1,107 +1,107 @@ package com.tngtech.configbuilder; import com.tngtech.configbuilder.annotationprocessors.AnnotationProcessor; import com.tngtech.propertyloader.PropertyLoader; import com.tngtech.propertyloader.impl.PropertyLocation; import com.tngtech.propertyloader.impl.PropertySuffix; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.lang.reflect.Field; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class ConfigBuilderTest { private ConfigBuilder<Config> configBuilder; private Properties properties; @Mock private AnnotationProcessor annotationProcessor; @Mock private ConfigBuilderContext builderContext; @Mock private MiscFactory miscFactory; @Mock private PropertyLoader propertyLoader; @Mock private PropertySuffix propertySuffix; @Mock private PropertyLocation propertyLocation; @Before public void setUp(){ configBuilder = new ConfigBuilder<>(annotationProcessor, builderContext, miscFactory); properties = new Properties(); when(builderContext.getPropertyLoader()).thenReturn(propertyLoader); when(miscFactory.createPropertyLoader()).thenReturn(propertyLoader); when(propertyLoader.getSuffixes()).thenReturn(propertySuffix); when(propertyLoader.getLocations()).thenReturn(propertyLocation); when(propertyLocation.atDefaultLocations()).thenReturn(propertyLocation); when(propertySuffix.addDefaultConfig()).thenReturn(propertySuffix); } @Test public void testWithCommandLineArguments() throws ParseException { String[] args = new String[]{"-u", "Mueller"}; Options options = mock(Options.class); when(miscFactory.createOptions()).thenReturn(options); CommandLineParser parser = mock(CommandLineParser.class); when(miscFactory.createCommandLineParser()).thenReturn(parser); CommandLine commandLine = mock(CommandLine.class); when(parser.parse(options, args)).thenReturn(commandLine); configBuilder.forClass(Config.class).withCommandLineArgs(args); - verify(options).addOption("u", true, ""); - verify(options).addOption("p", true, ""); + verify(options).addOption("u", "user", true, ""); + verify(options).addOption("p", "pidFixFactory", true, ""); verify(builderContext).setCommandLineArgs(commandLine); } @Test public void testThatForClassSetsClassToConfigBuilderAndReturnsConfigBuilder(){ assertEquals(configBuilder, configBuilder.forClass(Config.class)); assertEquals(configBuilder.getConfigClass(), Config.class); } @Test public void testThatForClassGetsFields(){ Field[] configFields = Config.class.getDeclaredFields(); configBuilder.forClass(Config.class); for(Field field : configFields) { assertTrue(configBuilder.getFields().contains(field)); } } @Test public void testThatForClassLoadsProperties(){ } }
true
true
public void testWithCommandLineArguments() throws ParseException { String[] args = new String[]{"-u", "Mueller"}; Options options = mock(Options.class); when(miscFactory.createOptions()).thenReturn(options); CommandLineParser parser = mock(CommandLineParser.class); when(miscFactory.createCommandLineParser()).thenReturn(parser); CommandLine commandLine = mock(CommandLine.class); when(parser.parse(options, args)).thenReturn(commandLine); configBuilder.forClass(Config.class).withCommandLineArgs(args); verify(options).addOption("u", true, ""); verify(options).addOption("p", true, ""); verify(builderContext).setCommandLineArgs(commandLine); }
public void testWithCommandLineArguments() throws ParseException { String[] args = new String[]{"-u", "Mueller"}; Options options = mock(Options.class); when(miscFactory.createOptions()).thenReturn(options); CommandLineParser parser = mock(CommandLineParser.class); when(miscFactory.createCommandLineParser()).thenReturn(parser); CommandLine commandLine = mock(CommandLine.class); when(parser.parse(options, args)).thenReturn(commandLine); configBuilder.forClass(Config.class).withCommandLineArgs(args); verify(options).addOption("u", "user", true, ""); verify(options).addOption("p", "pidFixFactory", true, ""); verify(builderContext).setCommandLineArgs(commandLine); }
diff --git a/ps3mediaserver/net/pms/network/HTTPServer.java b/ps3mediaserver/net/pms/network/HTTPServer.java index d4bcad4b..41b60d47 100644 --- a/ps3mediaserver/net/pms/network/HTTPServer.java +++ b/ps3mediaserver/net/pms/network/HTTPServer.java @@ -1,170 +1,170 @@ /* * PS3 Media Server, for streaming any medias to your PS3. * Copyright (C) 2008 A.Brochard * * 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; version 2 * of the License only. * * 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. */ package net.pms.network; import java.io.IOException; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.ServerSocketChannel; import java.util.ArrayList; import java.util.Enumeration; import net.pms.PMS; public class HTTPServer implements Runnable { private ArrayList<String> ips; private int port; private String hostName; private ServerSocketChannel serverSocketChannel; private ServerSocket serverSocket; private boolean stop; private Thread runnable; private InetAddress iafinal = null; public InetAddress getIafinal() { return iafinal; } private NetworkInterface ni = null; public NetworkInterface getNi() { return ni; } public HTTPServer(int port) { this.port = port; ips = new ArrayList<String>(); } public boolean start() throws IOException { Enumeration<NetworkInterface> enm = NetworkInterface.getNetworkInterfaces(); InetAddress ia = null; boolean found = false; while (enm.hasMoreElements()) { ni = enm.nextElement(); PMS.info("Scanning network interface " + ni.getDisplayName()); - if (!ni.isLoopback() && !ni.getDisplayName().toLowerCase().contains("vmware")) { + if (!ni.isLoopback() && ni.getDisplayName() != null && !ni.getDisplayName().toLowerCase().contains("vmware")) { Enumeration<InetAddress> addrs = ni.getInetAddresses(); while (addrs.hasMoreElements()) { ia = addrs.nextElement(); if (!(ia instanceof Inet6Address) && !ia.isLoopbackAddress()) { found = true; iafinal = ia; break; } } } if (found) break; } hostName = PMS.get().getHostname(); SocketAddress address = null; if (hostName != null && hostName.length() > 0) { PMS.minimal("Using forced address " + hostName); address = new InetSocketAddress(hostName, port); } else if (iafinal != null) { PMS.minimal("Using address " + iafinal + " found on network interface: " + ni.toString().trim().replace('\n', ' ')); address = new InetSocketAddress(iafinal, port); } else { PMS.minimal("Using localhost address"); address = new InetSocketAddress(port); } PMS.minimal("Created socket: " + address); serverSocketChannel = ServerSocketChannel.open(); serverSocket = serverSocketChannel.socket(); serverSocket.setReuseAddress(true); serverSocket.bind(address); if (hostName == null && iafinal !=null) hostName = iafinal.getHostAddress(); else if (hostName == null) hostName = InetAddress.getLocalHost().getHostAddress(); runnable = new Thread(this); runnable.setDaemon(false); runnable.start(); return true; } public void stop() { PMS.info( "Stopping server on host " + hostName + " and port " + port + "..."); runnable.interrupt(); runnable = null; try { serverSocket.close(); serverSocketChannel.close(); } catch (IOException e) {} } public void run() { PMS.minimal( "Starting DLNA Server on host " + hostName + " and port " + port + "..."); while (!stop) { try { Socket socket = serverSocket.accept(); String ip = socket.getInetAddress().getHostAddress(); if (!ips.contains(ip)) { ips.add(ip); PMS.minimal("Receiving a request from: " + ip); } RequestHandler request = new RequestHandler(socket); Thread thread = new Thread(request); thread.start(); } catch (ClosedByInterruptException e) { stop = true; } catch (IOException e) { e.printStackTrace(); } finally { try { if (stop && serverSocket != null) serverSocket.close(); if (stop && serverSocketChannel != null) serverSocketChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } } public String getURL() { return "http://" + hostName + ":" + port; } public String getHost() { return hostName; } public int getPort() { return port; } }
true
true
public boolean start() throws IOException { Enumeration<NetworkInterface> enm = NetworkInterface.getNetworkInterfaces(); InetAddress ia = null; boolean found = false; while (enm.hasMoreElements()) { ni = enm.nextElement(); PMS.info("Scanning network interface " + ni.getDisplayName()); if (!ni.isLoopback() && !ni.getDisplayName().toLowerCase().contains("vmware")) { Enumeration<InetAddress> addrs = ni.getInetAddresses(); while (addrs.hasMoreElements()) { ia = addrs.nextElement(); if (!(ia instanceof Inet6Address) && !ia.isLoopbackAddress()) { found = true; iafinal = ia; break; } } } if (found) break; } hostName = PMS.get().getHostname(); SocketAddress address = null; if (hostName != null && hostName.length() > 0) { PMS.minimal("Using forced address " + hostName); address = new InetSocketAddress(hostName, port); } else if (iafinal != null) { PMS.minimal("Using address " + iafinal + " found on network interface: " + ni.toString().trim().replace('\n', ' ')); address = new InetSocketAddress(iafinal, port); } else { PMS.minimal("Using localhost address"); address = new InetSocketAddress(port); } PMS.minimal("Created socket: " + address); serverSocketChannel = ServerSocketChannel.open(); serverSocket = serverSocketChannel.socket(); serverSocket.setReuseAddress(true); serverSocket.bind(address); if (hostName == null && iafinal !=null) hostName = iafinal.getHostAddress(); else if (hostName == null) hostName = InetAddress.getLocalHost().getHostAddress(); runnable = new Thread(this); runnable.setDaemon(false); runnable.start(); return true; }
public boolean start() throws IOException { Enumeration<NetworkInterface> enm = NetworkInterface.getNetworkInterfaces(); InetAddress ia = null; boolean found = false; while (enm.hasMoreElements()) { ni = enm.nextElement(); PMS.info("Scanning network interface " + ni.getDisplayName()); if (!ni.isLoopback() && ni.getDisplayName() != null && !ni.getDisplayName().toLowerCase().contains("vmware")) { Enumeration<InetAddress> addrs = ni.getInetAddresses(); while (addrs.hasMoreElements()) { ia = addrs.nextElement(); if (!(ia instanceof Inet6Address) && !ia.isLoopbackAddress()) { found = true; iafinal = ia; break; } } } if (found) break; } hostName = PMS.get().getHostname(); SocketAddress address = null; if (hostName != null && hostName.length() > 0) { PMS.minimal("Using forced address " + hostName); address = new InetSocketAddress(hostName, port); } else if (iafinal != null) { PMS.minimal("Using address " + iafinal + " found on network interface: " + ni.toString().trim().replace('\n', ' ')); address = new InetSocketAddress(iafinal, port); } else { PMS.minimal("Using localhost address"); address = new InetSocketAddress(port); } PMS.minimal("Created socket: " + address); serverSocketChannel = ServerSocketChannel.open(); serverSocket = serverSocketChannel.socket(); serverSocket.setReuseAddress(true); serverSocket.bind(address); if (hostName == null && iafinal !=null) hostName = iafinal.getHostAddress(); else if (hostName == null) hostName = InetAddress.getLocalHost().getHostAddress(); runnable = new Thread(this); runnable.setDaemon(false); runnable.start(); return true; }
diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/CachedManifest.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/CachedManifest.java index 2b5e86ec..2a26afca 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/CachedManifest.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/CachedManifest.java @@ -1,99 +1,117 @@ /******************************************************************************* * Copyright (c) 2003, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.core.runtime.internal.adaptor; import java.util.Dictionary; import java.util.Enumeration; import org.eclipse.osgi.framework.adaptor.BundleData; import org.eclipse.osgi.framework.adaptor.FrameworkAdaptor; import org.eclipse.osgi.framework.internal.core.Constants; import org.eclipse.osgi.framework.log.FrameworkLogEntry; import org.eclipse.osgi.util.NLS; import org.osgi.framework.*; /** * Internal class. */ public class CachedManifest extends Dictionary { private Dictionary manifest = null; private EclipseStorageHook storageHook; public CachedManifest(EclipseStorageHook storageHook) { this.storageHook = storageHook; } public Dictionary getManifest() { if (manifest == null) try { manifest = storageHook.createCachedManifest(true); } catch (BundleException e) { final String message = NLS.bind(EclipseAdaptorMsg.ECLIPSE_CACHEDMANIFEST_UNEXPECTED_EXCEPTION, storageHook.getBaseData().getLocation()); FrameworkLogEntry entry = new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.ERROR, 0, message, 0, e, null); storageHook.getAdaptor().getFrameworkLog().log(entry); return null; } return manifest; } public int size() { //TODO: getManifest may return null return getManifest().size(); } public boolean isEmpty() { return size() == 0; } public Enumeration elements() { //TODO: getManifest may return null return getManifest().elements(); } public Enumeration keys() { //TODO: getManifest may return null return getManifest().keys(); } public Object get(Object key) { if (manifest != null) return manifest.get(key); String keyString = (String) key; if (Constants.BUNDLE_VERSION.equalsIgnoreCase(keyString)) { Version result = storageHook.getBaseData().getVersion(); return result == null ? null : result.toString(); } if (Constants.PLUGIN_CLASS.equalsIgnoreCase(keyString)) return storageHook.getPluginClass(); if (Constants.BUNDLE_SYMBOLICNAME.equalsIgnoreCase(keyString)) { if ((storageHook.getBaseData().getType() & BundleData.TYPE_SINGLETON) == 0) return storageHook.getBaseData().getSymbolicName(); return storageHook.getBaseData().getSymbolicName() + ';' + Constants.SINGLETON_DIRECTIVE + ":=true"; //$NON-NLS-1$ } if (Constants.BUDDY_LOADER.equalsIgnoreCase(keyString)) return storageHook.getBuddyList(); if (Constants.REGISTERED_POLICY.equalsIgnoreCase(keyString)) return storageHook.getRegisteredBuddyList(); + if (Constants.BUNDLE_ACTIVATOR.equalsIgnoreCase(keyString)) + return storageHook.getBaseData().getActivator(); + if (Constants.ECLIPSE_LAZYSTART.equals(keyString) || Constants.ECLIPSE_AUTOSTART.equals(keyString)) { + if (!storageHook.isAutoStartable()) + return null; + if (storageHook.getAutoStartExceptions() == null) + return Boolean.TRUE.toString(); + StringBuffer result = new StringBuffer(Boolean.TRUE.toString()); + result.append(";").append(Constants.ECLIPSE_LAZYSTART_EXCEPTIONS).append("=\""); //$NON-NLS-1$ //$NON-NLS-2$ + String[] exceptions = storageHook.getAutoStartExceptions(); + for (int i = 0; i < exceptions.length; i++) { + if (i > 0) + result.append(","); //$NON-NLS-1$ + result.append(exceptions[i]); + } + result.append("\""); //$NON-NLS-1$ + return result.toString(); + } Dictionary result = getManifest(); return result == null ? null : result.get(key); } public Object remove(Object key) { //TODO: getManifest may return null return getManifest().remove(key); } public Object put(Object key, Object value) { //TODO: getManifest may return null return getManifest().put(key, value); } }
true
true
public Object get(Object key) { if (manifest != null) return manifest.get(key); String keyString = (String) key; if (Constants.BUNDLE_VERSION.equalsIgnoreCase(keyString)) { Version result = storageHook.getBaseData().getVersion(); return result == null ? null : result.toString(); } if (Constants.PLUGIN_CLASS.equalsIgnoreCase(keyString)) return storageHook.getPluginClass(); if (Constants.BUNDLE_SYMBOLICNAME.equalsIgnoreCase(keyString)) { if ((storageHook.getBaseData().getType() & BundleData.TYPE_SINGLETON) == 0) return storageHook.getBaseData().getSymbolicName(); return storageHook.getBaseData().getSymbolicName() + ';' + Constants.SINGLETON_DIRECTIVE + ":=true"; //$NON-NLS-1$ } if (Constants.BUDDY_LOADER.equalsIgnoreCase(keyString)) return storageHook.getBuddyList(); if (Constants.REGISTERED_POLICY.equalsIgnoreCase(keyString)) return storageHook.getRegisteredBuddyList(); Dictionary result = getManifest(); return result == null ? null : result.get(key); }
public Object get(Object key) { if (manifest != null) return manifest.get(key); String keyString = (String) key; if (Constants.BUNDLE_VERSION.equalsIgnoreCase(keyString)) { Version result = storageHook.getBaseData().getVersion(); return result == null ? null : result.toString(); } if (Constants.PLUGIN_CLASS.equalsIgnoreCase(keyString)) return storageHook.getPluginClass(); if (Constants.BUNDLE_SYMBOLICNAME.equalsIgnoreCase(keyString)) { if ((storageHook.getBaseData().getType() & BundleData.TYPE_SINGLETON) == 0) return storageHook.getBaseData().getSymbolicName(); return storageHook.getBaseData().getSymbolicName() + ';' + Constants.SINGLETON_DIRECTIVE + ":=true"; //$NON-NLS-1$ } if (Constants.BUDDY_LOADER.equalsIgnoreCase(keyString)) return storageHook.getBuddyList(); if (Constants.REGISTERED_POLICY.equalsIgnoreCase(keyString)) return storageHook.getRegisteredBuddyList(); if (Constants.BUNDLE_ACTIVATOR.equalsIgnoreCase(keyString)) return storageHook.getBaseData().getActivator(); if (Constants.ECLIPSE_LAZYSTART.equals(keyString) || Constants.ECLIPSE_AUTOSTART.equals(keyString)) { if (!storageHook.isAutoStartable()) return null; if (storageHook.getAutoStartExceptions() == null) return Boolean.TRUE.toString(); StringBuffer result = new StringBuffer(Boolean.TRUE.toString()); result.append(";").append(Constants.ECLIPSE_LAZYSTART_EXCEPTIONS).append("=\""); //$NON-NLS-1$ //$NON-NLS-2$ String[] exceptions = storageHook.getAutoStartExceptions(); for (int i = 0; i < exceptions.length; i++) { if (i > 0) result.append(","); //$NON-NLS-1$ result.append(exceptions[i]); } result.append("\""); //$NON-NLS-1$ return result.toString(); } Dictionary result = getManifest(); return result == null ? null : result.get(key); }
diff --git a/pa1/java/src/cs224n/wordaligner/IBM2CR.java b/pa1/java/src/cs224n/wordaligner/IBM2CR.java index 489a77e..fb8f64f 100644 --- a/pa1/java/src/cs224n/wordaligner/IBM2CR.java +++ b/pa1/java/src/cs224n/wordaligner/IBM2CR.java @@ -1,215 +1,215 @@ package cs224n.wordaligner; import cs224n.util.*; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; /** * IBM2CR models the problem * * @author Francois Chaubard */ public class IBM2CR implements WordAligner { // Count of sentence pairs that contain source and target words private CounterMap<String,String> target_source_t; // t(ei|fj) private CounterMap<Integer,Integer> source_target_d; // d(i|j) // Count of source words appearing in the training set //private Counter<String> source_count; @Override public Alignment align(SentencePair sentencePair) { Alignment alignment = new Alignment(); int numSourceWords = sentencePair.getSourceWords().size(); int numTargetWords = sentencePair.getTargetWords().size(); for (int targetIdx = 0; targetIdx < numTargetWords; targetIdx++) { String target = sentencePair.getTargetWords().get(targetIdx); //Find source word with maximum alignment likelihood double currentMax = 0; int maxSourceIdx = 0; for (int srcIndex = 0; srcIndex < numSourceWords; srcIndex++) { String source = sentencePair.getSourceWords().get(srcIndex); double ai = source_target_d.getCount(srcIndex,targetIdx) * target_source_t.getCount(target,source); if (currentMax < ai){ currentMax = ai; maxSourceIdx = srcIndex; } } alignment.addPredictedAlignment(targetIdx, maxSourceIdx); } return alignment; } @Override public void train(List<SentencePair> trainingPairs) { //Test params int S=5; //num iterations double lambda=0.001; //regularization double gamma=0.5; //step size int B=100; //batch size int numSentences = trainingPairs.size(); //Initalize counters target_source_t= new CounterMap<String,String>(); // t(ei|fj) source_target_d= new CounterMap<Integer,Integer>(); // d(i|j) //HashSet<String> source_dict = new HashSet<String>(); //HashSet<String> target_dict = new HashSet<String>(); HashMap<String,Set<String>> target_D = new HashMap<String,Set<String>>(); // c(f|e) int M=0; int L=0; System.out.printf("Starting init for Model 2 Convex \n" ); // Find M, L, E, F, and D(e) for(SentencePair pair : trainingPairs){ // add to target sentence? it says to do so ... but doesnt make sense - pair.targetWords.add(NULL_WORD); + pair.sourceWords.add(NULL_WORD); int numSourceWords = pair.getSourceWords().size(); int numTargetWords = pair.getTargetWords().size(); M=Math.max(numTargetWords, M); L=Math.max(numSourceWords, L); for (int targetIdx = 0; targetIdx < numTargetWords; targetIdx++) { String target = pair.getTargetWords().get(targetIdx); Set<String> set = new HashSet<String>(); target_D.put(target , set); for (int srcIndex = 0; srcIndex < numSourceWords; srcIndex++) { String source = pair.getSourceWords().get(srcIndex); //source_dict.add(source); //target_dict.add(target); target_D.get(target).add(source); } } } // init t and d /*for(SentencePair pair : trainingPairs){ int numSourceWords = pair.getSourceWords().size(); int numTargetWords = pair.getTargetWords().size(); for (int targetIdx = 0; targetIdx < numTargetWords; targetIdx++) { String target = pair.getTargetWords().get(targetIdx); for (int srcIndex = 0; srcIndex < numSourceWords; srcIndex++) { String source = pair.getSourceWords().get(srcIndex); target_source_t.setCount(target, source, 1.0/target_D.get(target).size() ); source_target_d.setCount(srcIndex, targetIdx, 1.0/(1+L)); } } }*/ // init t for(SentencePair pair : trainingPairs){ for (String source : pair.getSourceWords()) { for (String target : pair.getTargetWords()) { target_source_t.setCount(target, source, 1.0/target_D.get(target).size() ); } } } // init d for (int targetIdx = 0; targetIdx < M; targetIdx++) { for (int srcIndex = 0; srcIndex < L; srcIndex++) { source_target_d.setCount(srcIndex, targetIdx, 1.0/(1+L)); } } System.out.printf("Finished init for Model 2 Convex \n" ); int K=(int) Math.floor( numSentences/B ); for (int s = 1; s < S; s++) { for (int b = 1; b < K; b++) { int mk =0; int lk =0; CounterMap<String,String> target_source_alpha = new CounterMap<String,String>(); // a(ei|fj) CounterMap<Integer,Integer> source_target_beta= new CounterMap<Integer,Integer>(); // Beta(i|j) int sentence_begin=b*K-K; for (int sentenceIdx = sentence_begin; sentenceIdx < (sentence_begin+K); sentenceIdx++) { SentencePair pair = trainingPairs.get(sentenceIdx); int numSourceWords = pair.getSourceWords().size(); int numTargetWords = pair.getTargetWords().size(); mk=Math.max(numTargetWords, mk); lk=Math.max(numSourceWords, lk); for (int targetIdx = 0; targetIdx < numTargetWords; targetIdx++) { String target = pair.getTargetWords().get(targetIdx); for (int srcIndex = 0; srcIndex < numSourceWords; srcIndex++) { String source = pair.getSourceWords().get(srcIndex); double R_denominator = 0; double Q_denominator = 0; for (int targ = 0; targ < numTargetWords; targ++){ R_denominator += target_source_t.getCount( pair.getTargetWords().get(targ),source); Q_denominator += Math.min(target_source_t.getCount( pair.getTargetWords().get(targ),source) , source_target_d.getCount(srcIndex,targ)); } double R = 1.0 / (2*(lambda + R_denominator)); double Q = 1.0/ (2*(lambda + Q_denominator)); target_source_alpha.incrementCount(target, source, R); if(target_source_t.getCount(target,source) <= source_target_d.getCount(srcIndex, targetIdx) ){ target_source_alpha.incrementCount(target, source, Q); }else{ source_target_beta.incrementCount(srcIndex, targetIdx,Q); } }//source words }//target words }// subset of sentences // increment t sentence_begin=b*K-K; for (int sentenceIdx = sentence_begin; sentenceIdx < (sentence_begin+K); sentenceIdx++) { SentencePair pair = trainingPairs.get(sentenceIdx); // add to target sentence? it says to do so ... but doesnt make sense pair.targetWords.add(NULL_WORD); int numSourceWords = pair.getSourceWords().size(); int numTargetWords = pair.getTargetWords().size(); for (int targetIdx = 0; targetIdx < numTargetWords; targetIdx++) { String target = pair.getTargetWords().get(targetIdx); Set<String> set = new HashSet<String>(); target_D.put(target , set); for (int srcIndex = 0; srcIndex < numSourceWords; srcIndex++) { String source = pair.getSourceWords().get(srcIndex); target_source_t.setCount(target, source, target_source_t.getCount(target, source)*Math.exp(gamma*target_source_alpha.getCount(target,source) /B) ); source_target_d.setCount(srcIndex, targetIdx, source_target_d.getCount(srcIndex, targetIdx)*Math.exp(gamma*source_target_beta.getCount(srcIndex,targetIdx) /B) ); } } } target_source_t = Counters.conditionalNormalize(target_source_t); source_target_d = Counters.conditionalNormalize(source_target_d); System.out.printf("step=%d b=%d\n",s,b); }// subset }//iterations System.out.printf("Finished training Model 2 Convex \n" ); } }
true
true
public void train(List<SentencePair> trainingPairs) { //Test params int S=5; //num iterations double lambda=0.001; //regularization double gamma=0.5; //step size int B=100; //batch size int numSentences = trainingPairs.size(); //Initalize counters target_source_t= new CounterMap<String,String>(); // t(ei|fj) source_target_d= new CounterMap<Integer,Integer>(); // d(i|j) //HashSet<String> source_dict = new HashSet<String>(); //HashSet<String> target_dict = new HashSet<String>(); HashMap<String,Set<String>> target_D = new HashMap<String,Set<String>>(); // c(f|e) int M=0; int L=0; System.out.printf("Starting init for Model 2 Convex \n" ); // Find M, L, E, F, and D(e) for(SentencePair pair : trainingPairs){ // add to target sentence? it says to do so ... but doesnt make sense pair.targetWords.add(NULL_WORD); int numSourceWords = pair.getSourceWords().size(); int numTargetWords = pair.getTargetWords().size(); M=Math.max(numTargetWords, M); L=Math.max(numSourceWords, L); for (int targetIdx = 0; targetIdx < numTargetWords; targetIdx++) { String target = pair.getTargetWords().get(targetIdx); Set<String> set = new HashSet<String>(); target_D.put(target , set); for (int srcIndex = 0; srcIndex < numSourceWords; srcIndex++) { String source = pair.getSourceWords().get(srcIndex); //source_dict.add(source); //target_dict.add(target); target_D.get(target).add(source); } } } // init t and d /*for(SentencePair pair : trainingPairs){ int numSourceWords = pair.getSourceWords().size(); int numTargetWords = pair.getTargetWords().size(); for (int targetIdx = 0; targetIdx < numTargetWords; targetIdx++) { String target = pair.getTargetWords().get(targetIdx); for (int srcIndex = 0; srcIndex < numSourceWords; srcIndex++) { String source = pair.getSourceWords().get(srcIndex); target_source_t.setCount(target, source, 1.0/target_D.get(target).size() ); source_target_d.setCount(srcIndex, targetIdx, 1.0/(1+L)); } } }*/
public void train(List<SentencePair> trainingPairs) { //Test params int S=5; //num iterations double lambda=0.001; //regularization double gamma=0.5; //step size int B=100; //batch size int numSentences = trainingPairs.size(); //Initalize counters target_source_t= new CounterMap<String,String>(); // t(ei|fj) source_target_d= new CounterMap<Integer,Integer>(); // d(i|j) //HashSet<String> source_dict = new HashSet<String>(); //HashSet<String> target_dict = new HashSet<String>(); HashMap<String,Set<String>> target_D = new HashMap<String,Set<String>>(); // c(f|e) int M=0; int L=0; System.out.printf("Starting init for Model 2 Convex \n" ); // Find M, L, E, F, and D(e) for(SentencePair pair : trainingPairs){ // add to target sentence? it says to do so ... but doesnt make sense pair.sourceWords.add(NULL_WORD); int numSourceWords = pair.getSourceWords().size(); int numTargetWords = pair.getTargetWords().size(); M=Math.max(numTargetWords, M); L=Math.max(numSourceWords, L); for (int targetIdx = 0; targetIdx < numTargetWords; targetIdx++) { String target = pair.getTargetWords().get(targetIdx); Set<String> set = new HashSet<String>(); target_D.put(target , set); for (int srcIndex = 0; srcIndex < numSourceWords; srcIndex++) { String source = pair.getSourceWords().get(srcIndex); //source_dict.add(source); //target_dict.add(target); target_D.get(target).add(source); } } } // init t and d /*for(SentencePair pair : trainingPairs){ int numSourceWords = pair.getSourceWords().size(); int numTargetWords = pair.getTargetWords().size(); for (int targetIdx = 0; targetIdx < numTargetWords; targetIdx++) { String target = pair.getTargetWords().get(targetIdx); for (int srcIndex = 0; srcIndex < numSourceWords; srcIndex++) { String source = pair.getSourceWords().get(srcIndex); target_source_t.setCount(target, source, 1.0/target_D.get(target).size() ); source_target_d.setCount(srcIndex, targetIdx, 1.0/(1+L)); } } }*/
diff --git a/Client2D/src/com/pi/client/database/webfiles/GraphicsLoader.java b/Client2D/src/com/pi/client/database/webfiles/GraphicsLoader.java index 0a193ff..a30454f 100644 --- a/Client2D/src/com/pi/client/database/webfiles/GraphicsLoader.java +++ b/Client2D/src/com/pi/client/database/webfiles/GraphicsLoader.java @@ -1,183 +1,183 @@ package com.pi.client.database.webfiles; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; import com.pi.client.Client; import com.pi.client.constants.Constants; import com.pi.client.database.Paths; import com.pi.common.contants.NetworkConstants; /** * Fetches and updates the graphics from the server. * * @author Westin * */ public final class GraphicsLoader { /** * Gets a map of the current graphical versions from a file. * * @param filelistCurrent the file path * @return a map of the graphics ID to the version. * @throws IOException if there is a file read exception */ private static Map<Integer, Float> getCurrentVersions( final File filelistCurrent) throws IOException { HashMap<Integer, Float> currentVersions = new HashMap<Integer, Float>(); if (filelistCurrent.exists()) { BufferedReader reader = new BufferedReader(new FileReader( filelistCurrent)); while (reader.ready()) { String[] line = reader.readLine().split("\t"); String cleanedName = line[0]; for (String s : Paths.IMAGE_FILES) { cleanedName = cleanedName.replace("." + s, ""); } try { Integer name = Integer.valueOf(cleanedName); float ver; ver = Float.valueOf(line[1]); if (Paths.getGraphicsFile(name) != null) { currentVersions.put(name, ver); } } catch (Exception e) { continue; } } reader.close(); } return currentVersions; } /** * Updates the graphical files from the graphics server designated in * {@link Constants#GRAPHICS_URL}. * * @see Constants#GRAPHICS_URL * @see Constants#GRAPHICS_FILELIST * @param client the client instance */ public static void load(final Client client) { if (Constants.GRAPHICS_FILELIST == null) { return; } try { File filelistNew = new File(Paths.getGraphicsDirectory(), "filelist_new"); File filelistCurrent = new File(Paths.getGraphicsDirectory(), "filelist"); client.getLog().info("Downloading filelist..."); download(new URL(Constants.GRAPHICS_FILELIST), filelistNew); Map<Integer, Float> currentVersions = getCurrentVersions(filelistCurrent); BufferedReader reader = new BufferedReader(new FileReader( filelistNew)); while (reader.ready()) { String[] line = reader.readLine().split("\t"); String rawName = line[0]; String cleanedName = rawName; for (String s : Paths.IMAGE_FILES) { cleanedName = cleanedName.replace("." + s, ""); } Integer name = Integer.valueOf(cleanedName); float ver; try { ver = Float.valueOf(line[1]); } catch (Exception e) { client.getLog().printStackTrace(e); continue; } Float cVer = currentVersions.get(name); if (cVer == null || cVer.floatValue() < ver) { client.getLog() .info(name + " is outdated. Upgrading to version " + ver); try { File dest = new File( Paths.getGraphicsDirectory(), rawName); if (!dest.exists()) { dest.createNewFile(); } download(new URL(Constants.GRAPHICS_URL - + name), dest); + + rawName), dest); } catch (IOException e) { client.getLog().printStackTrace(e); } } } reader.close(); filelistCurrent.delete(); filelistNew.renameTo(filelistCurrent); client.getLog().info( "Finished checking graphic versions!"); } catch (NumberFormatException e) { client.getLog() .severe("There appears to be a number format error server side! Please report this."); } catch (Exception e) { client.getLog().printStackTrace(e); client.getLog().info( "Failed to check for graphical updates!"); } } /** * Downloads the contents of a URL to the provided File. * * @param url the source URL * @param dest the destination File * @throws IOException if there are problems in downloading the file */ private static void download(final URL url, final File dest) throws IOException { BufferedInputStream in = null; FileOutputStream fout = null; File f = new File(dest.getAbsolutePath() + ".part"); f.createNewFile(); try { in = new BufferedInputStream(url.openStream()); fout = new FileOutputStream(f); byte[] data = new byte[NetworkConstants.DOWNLOAD_CACHE_SIZE]; int count; while ((count = in.read(data, 0, NetworkConstants.DOWNLOAD_CACHE_SIZE)) != -1) { fout.write(data, 0, count); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } dest.delete(); f.renameTo(dest); } /** * Overridden to not allow instances of this class to be produced. */ private GraphicsLoader() { } }
true
true
public static void load(final Client client) { if (Constants.GRAPHICS_FILELIST == null) { return; } try { File filelistNew = new File(Paths.getGraphicsDirectory(), "filelist_new"); File filelistCurrent = new File(Paths.getGraphicsDirectory(), "filelist"); client.getLog().info("Downloading filelist..."); download(new URL(Constants.GRAPHICS_FILELIST), filelistNew); Map<Integer, Float> currentVersions = getCurrentVersions(filelistCurrent); BufferedReader reader = new BufferedReader(new FileReader( filelistNew)); while (reader.ready()) { String[] line = reader.readLine().split("\t"); String rawName = line[0]; String cleanedName = rawName; for (String s : Paths.IMAGE_FILES) { cleanedName = cleanedName.replace("." + s, ""); } Integer name = Integer.valueOf(cleanedName); float ver; try { ver = Float.valueOf(line[1]); } catch (Exception e) { client.getLog().printStackTrace(e); continue; } Float cVer = currentVersions.get(name); if (cVer == null || cVer.floatValue() < ver) { client.getLog() .info(name + " is outdated. Upgrading to version " + ver); try { File dest = new File( Paths.getGraphicsDirectory(), rawName); if (!dest.exists()) { dest.createNewFile(); } download(new URL(Constants.GRAPHICS_URL + name), dest); } catch (IOException e) { client.getLog().printStackTrace(e); } } } reader.close(); filelistCurrent.delete(); filelistNew.renameTo(filelistCurrent); client.getLog().info( "Finished checking graphic versions!"); } catch (NumberFormatException e) { client.getLog() .severe("There appears to be a number format error server side! Please report this."); } catch (Exception e) { client.getLog().printStackTrace(e); client.getLog().info( "Failed to check for graphical updates!"); } }
public static void load(final Client client) { if (Constants.GRAPHICS_FILELIST == null) { return; } try { File filelistNew = new File(Paths.getGraphicsDirectory(), "filelist_new"); File filelistCurrent = new File(Paths.getGraphicsDirectory(), "filelist"); client.getLog().info("Downloading filelist..."); download(new URL(Constants.GRAPHICS_FILELIST), filelistNew); Map<Integer, Float> currentVersions = getCurrentVersions(filelistCurrent); BufferedReader reader = new BufferedReader(new FileReader( filelistNew)); while (reader.ready()) { String[] line = reader.readLine().split("\t"); String rawName = line[0]; String cleanedName = rawName; for (String s : Paths.IMAGE_FILES) { cleanedName = cleanedName.replace("." + s, ""); } Integer name = Integer.valueOf(cleanedName); float ver; try { ver = Float.valueOf(line[1]); } catch (Exception e) { client.getLog().printStackTrace(e); continue; } Float cVer = currentVersions.get(name); if (cVer == null || cVer.floatValue() < ver) { client.getLog() .info(name + " is outdated. Upgrading to version " + ver); try { File dest = new File( Paths.getGraphicsDirectory(), rawName); if (!dest.exists()) { dest.createNewFile(); } download(new URL(Constants.GRAPHICS_URL + rawName), dest); } catch (IOException e) { client.getLog().printStackTrace(e); } } } reader.close(); filelistCurrent.delete(); filelistNew.renameTo(filelistCurrent); client.getLog().info( "Finished checking graphic versions!"); } catch (NumberFormatException e) { client.getLog() .severe("There appears to be a number format error server side! Please report this."); } catch (Exception e) { client.getLog().printStackTrace(e); client.getLog().info( "Failed to check for graphical updates!"); } }
diff --git a/japi-checker/src/main/java/com/googlecode/japi/checker/Difference.java b/japi-checker/src/main/java/com/googlecode/japi/checker/Difference.java index 30797c8..b0bbbd8 100644 --- a/japi-checker/src/main/java/com/googlecode/japi/checker/Difference.java +++ b/japi-checker/src/main/java/com/googlecode/japi/checker/Difference.java @@ -1,81 +1,86 @@ package com.googlecode.japi.checker; import com.googlecode.japi.checker.model.ClassData; import com.googlecode.japi.checker.model.JavaItem; import com.googlecode.japi.checker.model.MethodData; /** * * @author Tomas Rohovsky * */ public class Difference { private DifferenceType differenceType; private JavaItem referenceItem; private JavaItem newItem; private String[] args; private String source; protected Difference() { } public Difference(JavaItem referenceItem, JavaItem newItem, DifferenceType differenceType) { this.setReferenceItem(referenceItem); this.newItem = newItem; this.differenceType = differenceType; } public Difference(JavaItem referenceItem, JavaItem newItem, DifferenceType differenceType, Object...args) { this(referenceItem, newItem, differenceType); // objects to strings String[] stringArgs = new String[args.length]; for (int i = 0; i < args.length; i++) { - stringArgs[i] = args[i].toString(); + // TODO quickly fixed to prevent null exception, which occur when field's value is changed to null + if (args[i] != null) { + stringArgs[i] = args[i].toString(); + } else { + stringArgs[i] = "null"; + } } this.args = stringArgs; } public DifferenceType getDifferenceType() { return differenceType; } // unfortunately this setter is needed, because Hibernate is not able to set source protected void setReferenceItem(JavaItem referenceItem) { this.referenceItem = referenceItem; this.source = (referenceItem.getOwner() == null ? ((ClassData)referenceItem).getFilename() : referenceItem.getOwner().getFilename()); } public JavaItem getReferenceItem() { return referenceItem; } public JavaItem getNewItem() { return newItem; } public String[] getArgs() { return args; } public String getSource() { return source; } public String getMessage() { return String.format(differenceType.getMessagePattern(), (Object[])args); } public String getEffect() { return String.format(differenceType.getMessagePattern(), (Object[])args); } public Integer getLine() { if (newItem instanceof MethodData) { Integer lineNumber = ((MethodData)newItem).getLineNumber(); return lineNumber; } return null; } }
true
true
public Difference(JavaItem referenceItem, JavaItem newItem, DifferenceType differenceType, Object...args) { this(referenceItem, newItem, differenceType); // objects to strings String[] stringArgs = new String[args.length]; for (int i = 0; i < args.length; i++) { stringArgs[i] = args[i].toString(); } this.args = stringArgs; }
public Difference(JavaItem referenceItem, JavaItem newItem, DifferenceType differenceType, Object...args) { this(referenceItem, newItem, differenceType); // objects to strings String[] stringArgs = new String[args.length]; for (int i = 0; i < args.length; i++) { // TODO quickly fixed to prevent null exception, which occur when field's value is changed to null if (args[i] != null) { stringArgs[i] = args[i].toString(); } else { stringArgs[i] = "null"; } } this.args = stringArgs; }
diff --git a/SeriesGuide/src/com/battlelancer/seriesguide/appwidget/AppWidget.java b/SeriesGuide/src/com/battlelancer/seriesguide/appwidget/AppWidget.java index 133d87632..52b07f659 100644 --- a/SeriesGuide/src/com/battlelancer/seriesguide/appwidget/AppWidget.java +++ b/SeriesGuide/src/com/battlelancer/seriesguide/appwidget/AppWidget.java @@ -1,210 +1,210 @@ /* * Copyright (C) 2011 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.R; import com.battlelancer.seriesguide.SeriesDatabase; import com.battlelancer.seriesguide.SeriesGuideApplication; import com.battlelancer.seriesguide.SeriesGuideData; import com.battlelancer.seriesguide.provider.SeriesContract.Episodes; import com.battlelancer.seriesguide.provider.SeriesContract.Shows; import com.battlelancer.seriesguide.ui.ShowsActivity; import com.battlelancer.seriesguide.ui.UpcomingRecentActivity; import com.battlelancer.thetvdbapi.ImageCache; import android.app.IntentService; 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.database.Cursor; import android.graphics.Bitmap; import android.preference.PreferenceManager; import android.widget.RemoteViews; public class AppWidget extends AppWidgetProvider { public static final String REFRESH = "com.battlelancer.seriesguide.appwidget.REFRESH"; private static final String LIMIT = "2"; private static final int LAYOUT = R.layout.appwidget; private static final int ITEMLAYOUT = R.layout.appwidget_item; @Override public void onReceive(Context context, Intent intent) { if (REFRESH.equals(intent.getAction())) { context.startService(createUpdateIntent(context)); } else { super.onReceive(context, intent); } } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { context.startService(createUpdateIntent(context)); } /** * Creates an intent which must include the update service class to start. * * @param context * @return */ public Intent createUpdateIntent(Context context) { Intent i = new Intent(context, UpdateService.class); return i; } public static class UpdateService extends IntentService { public UpdateService() { super("appwidget.AppWidget$UpdateService"); } @Override public void onCreate() { super.onCreate(); } @Override public void onHandleIntent(Intent intent) { ComponentName me = new ComponentName(this, AppWidget.class); AppWidgetManager mgr = AppWidgetManager.getInstance(this); Intent i = new Intent(this, AppWidget.class); mgr.updateAppWidget(me, buildUpdate(this, LIMIT, LAYOUT, ITEMLAYOUT, i)); } protected RemoteViews buildUpdate(Context context, String limit, int layout, int itemLayout, Intent updateIntent) { final ImageCache imageCache = ((SeriesGuideApplication) getApplication()) .getImageCache(); // Get the layout for the App Widget, remove existing views // RemoteViews views = new RemoteViews(context.getPackageName(), // layout); final RemoteViews views = new RemoteViews(context.getPackageName(), layout); views.removeAllViews(R.id.LinearLayoutWidget); // get upcoming shows (name and next episode text) final Cursor upcomingEpisodes = SeriesDatabase.getUpcomingEpisodes(context); if (upcomingEpisodes == null || upcomingEpisodes.getCount() == 0) { // no next episodes exist RemoteViews item = new RemoteViews(context.getPackageName(), itemLayout); item.setTextViewText(R.id.textViewWidgetShow, context.getString(R.string.no_nextepisode)); item.setTextViewText(R.id.textViewWidgetEpisode, ""); item.setTextViewText(R.id.widgetAirtime, ""); item.setTextViewText(R.id.widgetNetwork, ""); views.addView(R.id.LinearLayoutWidget, item); } else { String value; Bitmap poster; int viewsToAdd = Integer.valueOf(limit); while (upcomingEpisodes.moveToNext() && viewsToAdd != 0) { viewsToAdd--; RemoteViews item = new RemoteViews(context.getPackageName(), itemLayout); // upcoming episode String season = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Episodes.SEASON)); String number = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Episodes.NUMBER)); String title = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Episodes.TITLE)); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); item.setTextViewText(R.id.textViewWidgetEpisode, SeriesGuideData.getNextEpisodeString(prefs, season, number, title)); // add relative airdate long airtime = upcomingEpisodes.getLong(upcomingEpisodes .getColumnIndexOrThrow(Shows.AIRSTIME)); value = SeriesGuideData.parseDateToLocalRelative( upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Episodes.FIRSTAIRED)), airtime, context); item.setTextViewText(R.id.widgetAirtime, value); // add airtime and network (if any) value = ""; if (airtime != -1) { value = SeriesGuideData.parseMillisecondsToTime(airtime, null, getApplicationContext())[0]; } String network = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Shows.NETWORK)); if (network.length() != 0) { value += " " + network; } item.setTextViewText(R.id.widgetNetwork, value); // show name value = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Shows.TITLE)); item.setTextViewText(R.id.textViewWidgetShow, value); if (layout != R.layout.appwidget) { // show poster value = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Shows.POSTER)); poster = null; if (value.length() != 0) { poster = imageCache.getThumb(value, false); if (poster != null) { item.setImageViewBitmap(R.id.widgetPoster, poster); } } } views.addView(R.id.LinearLayoutWidget, item); } } if (upcomingEpisodes != null) { upcomingEpisodes.close(); } // Create an Intent to launch Upcoming Intent intent = new Intent(context, UpcomingRecentActivity.class); - intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); views.setOnClickPendingIntent(R.id.LinearLayoutWidget, pendingIntent); if (layout != R.layout.appwidget) { // Create an Intent to launch SeriesGuide Intent i = new Intent(context, ShowsActivity.class); - i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); pendingIntent = PendingIntent.getActivity(context, 0, i, 0); views.setOnClickPendingIntent(R.id.widgetShowlistButton, pendingIntent); } // Create an intent to update the widget updateIntent.setAction(REFRESH); PendingIntent pi = PendingIntent.getBroadcast(context, 0, updateIntent, 0); views.setOnClickPendingIntent(R.id.ImageButtonWidget, pi); return views; } } }
false
true
protected RemoteViews buildUpdate(Context context, String limit, int layout, int itemLayout, Intent updateIntent) { final ImageCache imageCache = ((SeriesGuideApplication) getApplication()) .getImageCache(); // Get the layout for the App Widget, remove existing views // RemoteViews views = new RemoteViews(context.getPackageName(), // layout); final RemoteViews views = new RemoteViews(context.getPackageName(), layout); views.removeAllViews(R.id.LinearLayoutWidget); // get upcoming shows (name and next episode text) final Cursor upcomingEpisodes = SeriesDatabase.getUpcomingEpisodes(context); if (upcomingEpisodes == null || upcomingEpisodes.getCount() == 0) { // no next episodes exist RemoteViews item = new RemoteViews(context.getPackageName(), itemLayout); item.setTextViewText(R.id.textViewWidgetShow, context.getString(R.string.no_nextepisode)); item.setTextViewText(R.id.textViewWidgetEpisode, ""); item.setTextViewText(R.id.widgetAirtime, ""); item.setTextViewText(R.id.widgetNetwork, ""); views.addView(R.id.LinearLayoutWidget, item); } else { String value; Bitmap poster; int viewsToAdd = Integer.valueOf(limit); while (upcomingEpisodes.moveToNext() && viewsToAdd != 0) { viewsToAdd--; RemoteViews item = new RemoteViews(context.getPackageName(), itemLayout); // upcoming episode String season = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Episodes.SEASON)); String number = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Episodes.NUMBER)); String title = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Episodes.TITLE)); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); item.setTextViewText(R.id.textViewWidgetEpisode, SeriesGuideData.getNextEpisodeString(prefs, season, number, title)); // add relative airdate long airtime = upcomingEpisodes.getLong(upcomingEpisodes .getColumnIndexOrThrow(Shows.AIRSTIME)); value = SeriesGuideData.parseDateToLocalRelative( upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Episodes.FIRSTAIRED)), airtime, context); item.setTextViewText(R.id.widgetAirtime, value); // add airtime and network (if any) value = ""; if (airtime != -1) { value = SeriesGuideData.parseMillisecondsToTime(airtime, null, getApplicationContext())[0]; } String network = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Shows.NETWORK)); if (network.length() != 0) { value += " " + network; } item.setTextViewText(R.id.widgetNetwork, value); // show name value = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Shows.TITLE)); item.setTextViewText(R.id.textViewWidgetShow, value); if (layout != R.layout.appwidget) { // show poster value = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Shows.POSTER)); poster = null; if (value.length() != 0) { poster = imageCache.getThumb(value, false); if (poster != null) { item.setImageViewBitmap(R.id.widgetPoster, poster); } } } views.addView(R.id.LinearLayoutWidget, item); } } if (upcomingEpisodes != null) { upcomingEpisodes.close(); } // Create an Intent to launch Upcoming Intent intent = new Intent(context, UpcomingRecentActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); views.setOnClickPendingIntent(R.id.LinearLayoutWidget, pendingIntent); if (layout != R.layout.appwidget) { // Create an Intent to launch SeriesGuide Intent i = new Intent(context, ShowsActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pendingIntent = PendingIntent.getActivity(context, 0, i, 0); views.setOnClickPendingIntent(R.id.widgetShowlistButton, pendingIntent); } // Create an intent to update the widget updateIntent.setAction(REFRESH); PendingIntent pi = PendingIntent.getBroadcast(context, 0, updateIntent, 0); views.setOnClickPendingIntent(R.id.ImageButtonWidget, pi); return views; }
protected RemoteViews buildUpdate(Context context, String limit, int layout, int itemLayout, Intent updateIntent) { final ImageCache imageCache = ((SeriesGuideApplication) getApplication()) .getImageCache(); // Get the layout for the App Widget, remove existing views // RemoteViews views = new RemoteViews(context.getPackageName(), // layout); final RemoteViews views = new RemoteViews(context.getPackageName(), layout); views.removeAllViews(R.id.LinearLayoutWidget); // get upcoming shows (name and next episode text) final Cursor upcomingEpisodes = SeriesDatabase.getUpcomingEpisodes(context); if (upcomingEpisodes == null || upcomingEpisodes.getCount() == 0) { // no next episodes exist RemoteViews item = new RemoteViews(context.getPackageName(), itemLayout); item.setTextViewText(R.id.textViewWidgetShow, context.getString(R.string.no_nextepisode)); item.setTextViewText(R.id.textViewWidgetEpisode, ""); item.setTextViewText(R.id.widgetAirtime, ""); item.setTextViewText(R.id.widgetNetwork, ""); views.addView(R.id.LinearLayoutWidget, item); } else { String value; Bitmap poster; int viewsToAdd = Integer.valueOf(limit); while (upcomingEpisodes.moveToNext() && viewsToAdd != 0) { viewsToAdd--; RemoteViews item = new RemoteViews(context.getPackageName(), itemLayout); // upcoming episode String season = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Episodes.SEASON)); String number = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Episodes.NUMBER)); String title = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Episodes.TITLE)); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); item.setTextViewText(R.id.textViewWidgetEpisode, SeriesGuideData.getNextEpisodeString(prefs, season, number, title)); // add relative airdate long airtime = upcomingEpisodes.getLong(upcomingEpisodes .getColumnIndexOrThrow(Shows.AIRSTIME)); value = SeriesGuideData.parseDateToLocalRelative( upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Episodes.FIRSTAIRED)), airtime, context); item.setTextViewText(R.id.widgetAirtime, value); // add airtime and network (if any) value = ""; if (airtime != -1) { value = SeriesGuideData.parseMillisecondsToTime(airtime, null, getApplicationContext())[0]; } String network = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Shows.NETWORK)); if (network.length() != 0) { value += " " + network; } item.setTextViewText(R.id.widgetNetwork, value); // show name value = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Shows.TITLE)); item.setTextViewText(R.id.textViewWidgetShow, value); if (layout != R.layout.appwidget) { // show poster value = upcomingEpisodes.getString(upcomingEpisodes .getColumnIndexOrThrow(Shows.POSTER)); poster = null; if (value.length() != 0) { poster = imageCache.getThumb(value, false); if (poster != null) { item.setImageViewBitmap(R.id.widgetPoster, poster); } } } views.addView(R.id.LinearLayoutWidget, item); } } if (upcomingEpisodes != null) { upcomingEpisodes.close(); } // Create an Intent to launch Upcoming Intent intent = new Intent(context, UpcomingRecentActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); views.setOnClickPendingIntent(R.id.LinearLayoutWidget, pendingIntent); if (layout != R.layout.appwidget) { // Create an Intent to launch SeriesGuide Intent i = new Intent(context, ShowsActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); pendingIntent = PendingIntent.getActivity(context, 0, i, 0); views.setOnClickPendingIntent(R.id.widgetShowlistButton, pendingIntent); } // Create an intent to update the widget updateIntent.setAction(REFRESH); PendingIntent pi = PendingIntent.getBroadcast(context, 0, updateIntent, 0); views.setOnClickPendingIntent(R.id.ImageButtonWidget, pi); return views; }
diff --git a/src/syslogDaemon.java b/src/syslogDaemon.java index 2fb41c4..cd1cb36 100644 --- a/src/syslogDaemon.java +++ b/src/syslogDaemon.java @@ -1,111 +1,112 @@ import com.sleepycat.je.*; import java.net.DatagramSocket; import java.net.DatagramPacket; import java.net.InetAddress; import java.util.Date; import java.io.File; import java.nio.ByteBuffer; /* * This file is part of syslogUnity. * * syslogUnity 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. * * syslogUnity 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 syslogUnity. If not, see <http://www.gnu.org/licenses/>. */ public class syslogDaemon { public static void main(String[] args) throws Exception { new syslogDaemon().getEntries(); } private void getEntries() throws Exception { - final File dbEnvDir = new File("queueDB/"); + final File dbEnvDir = new File("/var/lib/syslogUnity/queueDB/"); int BUFFER_SIZE = 1024; DatagramSocket syslog = new DatagramSocket(514); DatagramPacket logEntry = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE); EnvironmentConfig envConfig = new EnvironmentConfig(); envConfig.setTransactional(true); envConfig.setAllowCreate(true); envConfig.setCacheSize(20971520); envConfig.setSharedCache(true); final Environment env = new Environment(dbEnvDir, envConfig); DatabaseConfig config = new DatabaseConfig(); config.setAllowCreate(true); final Database queue = env.openDatabase(null, "logQueue", config); final Cursor cursor; cursor = queue.openCursor(null, null); LongEntry lastRecNoDbt = new LongEntry(); - cursor.getLast(lastRecNoDbt, null, null); + DatabaseEntry throwaway = new DatabaseEntry(); + cursor.getLast(lastRecNoDbt, throwaway, null); long currentRecNo = lastRecNoDbt.getLong() + 1; cursor.close(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { queue.close(); env.close(); System.out.print("Closed DB Gracefully...\n"); } catch (Exception dbe) { System.out.print("Caught SIGINT, couldn't close queueDB successfully\n"); } } }); while (true) { syslog.receive(logEntry); InetAddress logHost = logEntry.getAddress(); String logLine = new String(logEntry.getData(), 0, logEntry.getLength()); doStuff(logLine, logHost, queue, currentRecNo); currentRecNo++; } } void doStuff(String logLine, InetAddress logHost, Database queue, long currentRecNo) { Date logDate = new Date(); String logPriority = ""; int i; for (i = 0; i <= logLine.length(); i++) { if (logLine.charAt(i) == '>') break; if (logLine.charAt(i) != '<') logPriority = logPriority + logLine.charAt(i); } String logData = logLine.substring(i + 1, logLine.length()); String dateEpoch = Long.toString(logDate.getTime()); String insertRecord = dateEpoch.concat("##FD##"). concat(logPriority).concat("##FD##"). concat(logHost.getHostAddress()).concat("##FD##"). concat(logData); byte[] k = ByteBuffer.allocate(8).putLong(currentRecNo).array(); byte[] d = insertRecord.getBytes(); DatabaseEntry kdbt = new DatabaseEntry(k); kdbt.setSize(8); DatabaseEntry ddbt = new DatabaseEntry(d, 0, d.length); ddbt.setSize(d.length); try { queue.put(null, kdbt, ddbt); } catch (Exception dbe) { System.out.print("Couldn't add record to database\n"); } } }
false
true
private void getEntries() throws Exception { final File dbEnvDir = new File("queueDB/"); int BUFFER_SIZE = 1024; DatagramSocket syslog = new DatagramSocket(514); DatagramPacket logEntry = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE); EnvironmentConfig envConfig = new EnvironmentConfig(); envConfig.setTransactional(true); envConfig.setAllowCreate(true); envConfig.setCacheSize(20971520); envConfig.setSharedCache(true); final Environment env = new Environment(dbEnvDir, envConfig); DatabaseConfig config = new DatabaseConfig(); config.setAllowCreate(true); final Database queue = env.openDatabase(null, "logQueue", config); final Cursor cursor; cursor = queue.openCursor(null, null); LongEntry lastRecNoDbt = new LongEntry(); cursor.getLast(lastRecNoDbt, null, null); long currentRecNo = lastRecNoDbt.getLong() + 1; cursor.close(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { queue.close(); env.close(); System.out.print("Closed DB Gracefully...\n"); } catch (Exception dbe) { System.out.print("Caught SIGINT, couldn't close queueDB successfully\n"); } } }); while (true) { syslog.receive(logEntry); InetAddress logHost = logEntry.getAddress(); String logLine = new String(logEntry.getData(), 0, logEntry.getLength()); doStuff(logLine, logHost, queue, currentRecNo); currentRecNo++; } }
private void getEntries() throws Exception { final File dbEnvDir = new File("/var/lib/syslogUnity/queueDB/"); int BUFFER_SIZE = 1024; DatagramSocket syslog = new DatagramSocket(514); DatagramPacket logEntry = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE); EnvironmentConfig envConfig = new EnvironmentConfig(); envConfig.setTransactional(true); envConfig.setAllowCreate(true); envConfig.setCacheSize(20971520); envConfig.setSharedCache(true); final Environment env = new Environment(dbEnvDir, envConfig); DatabaseConfig config = new DatabaseConfig(); config.setAllowCreate(true); final Database queue = env.openDatabase(null, "logQueue", config); final Cursor cursor; cursor = queue.openCursor(null, null); LongEntry lastRecNoDbt = new LongEntry(); DatabaseEntry throwaway = new DatabaseEntry(); cursor.getLast(lastRecNoDbt, throwaway, null); long currentRecNo = lastRecNoDbt.getLong() + 1; cursor.close(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { queue.close(); env.close(); System.out.print("Closed DB Gracefully...\n"); } catch (Exception dbe) { System.out.print("Caught SIGINT, couldn't close queueDB successfully\n"); } } }); while (true) { syslog.receive(logEntry); InetAddress logHost = logEntry.getAddress(); String logLine = new String(logEntry.getData(), 0, logEntry.getLength()); doStuff(logLine, logHost, queue, currentRecNo); currentRecNo++; } }
diff --git a/src/xhl/core/validator/ValidatorLanguage.java b/src/xhl/core/validator/ValidatorLanguage.java index 59e74d3..5612ac2 100644 --- a/src/xhl/core/validator/ValidatorLanguage.java +++ b/src/xhl/core/validator/ValidatorLanguage.java @@ -1,122 +1,122 @@ package xhl.core.validator; import java.util.List; import xhl.core.GenericModule; import xhl.core.Language; import xhl.core.Module; import xhl.core.elements.Block; import xhl.core.elements.Symbol; import xhl.core.validator.ElementSchema.DefSpec; import xhl.core.validator.ElementSchema.ParamSpec; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Lists.newArrayList; public class ValidatorLanguage extends GenericModule implements Language { private ElementSchema currentElement; private final Schema schema = new Schema(); @Function(evaluateArgs = false) public void element(Symbol name, Block blk) { currentElement = new ElementSchema(name); schema.put(currentElement); evaluator.eval(blk); } @Function public void params(List<ParamSpec> args) { currentElement.setParams(args); } @Function(evaluateArgs = false) public ParamSpec val(Symbol type) { return ParamSpec.val(new Type(type)); } @Function(evaluateArgs = false) public ParamSpec sym(Symbol type) { return ParamSpec.sym(new Type(type)); } @Function public ParamSpec variadic(ParamSpec param) { return ParamSpec.variadic(param); } @Function public ParamSpec block(ParamSpec param) { return ParamSpec.block(param); } @Function(evaluateArgs = false) public void type(Symbol type) { currentElement.setType(new Type(type)); } @Function public void defines(double arg, @Symbolic Symbol type) { checkArgument(arg % 1 == 0); DefSpec def = new DefSpec((int) arg, new Type(type)); currentElement.addDefine(def); } @Function public void defines_forward(double arg, @Symbolic Symbol type) { checkArgument(arg % 1 == 0); DefSpec def = new DefSpec((int) arg, new Type(type), true); currentElement.addDefine(def); } @Override public Module[] getModules() { return new Module[] { this }; } @Override public Schema getSchema() { Schema langSchema = new Schema(); ElementSchema element = new ElementSchema(new Symbol("element")); element.setParams(newArrayList(ParamSpec.sym(new Type("Symbol")), - ParamSpec.block(ParamSpec.sym(new Type("Block"))))); + ParamSpec.block(ParamSpec.val(new Type("Block"))))); element.setType(new Type("Symbol")); langSchema.put(element); ElementSchema params = new ElementSchema(new Symbol("params")); params.setParams(newArrayList(ParamSpec.val(Type.List))); params.setType(new Type("Parameters")); langSchema.put(params); ElementSchema val = new ElementSchema(new Symbol("val")); val.setParams(newArrayList(ParamSpec.sym(Type.Symbol))); val.setType(new Type("Parameter")); langSchema.put(val); ElementSchema sym = new ElementSchema(new Symbol("sym")); sym.setParams(newArrayList(ParamSpec.sym(Type.Symbol))); sym.setType(new Type("Parameter")); langSchema.put(sym); ElementSchema variadic = new ElementSchema(new Symbol("variadic")); variadic.setParams(newArrayList(ParamSpec.val(new Type("Parameter")))); variadic.setType(new Type("Parameter")); langSchema.put(variadic); ElementSchema block = new ElementSchema(new Symbol("block")); block.setParams(newArrayList(ParamSpec.val(new Type("Parameter")))); block.setType(new Type("Parameter")); langSchema.put(block); ElementSchema type = new ElementSchema(new Symbol("type")); type.setParams(newArrayList(ParamSpec.sym(new Type("Symbol")))); type.setType(new Type("Type")); langSchema.put(type); ElementSchema defines = new ElementSchema(new Symbol("defines")); defines.setParams(newArrayList(ParamSpec.val(new Type("Number")), ParamSpec.sym(new Type("Symbol")))); defines.setType(new Type("Define")); langSchema.put(defines); ElementSchema defines_forward = new ElementSchema(new Symbol("defines_forward")); defines_forward.setParams(newArrayList(ParamSpec.val(new Type("Number")), ParamSpec.sym(new Type("Symbol")))); defines_forward.setType(new Type("Define")); langSchema.put(defines_forward); return langSchema; } public Schema getReadedSchema() { return schema; } }
true
true
public Schema getSchema() { Schema langSchema = new Schema(); ElementSchema element = new ElementSchema(new Symbol("element")); element.setParams(newArrayList(ParamSpec.sym(new Type("Symbol")), ParamSpec.block(ParamSpec.sym(new Type("Block"))))); element.setType(new Type("Symbol")); langSchema.put(element); ElementSchema params = new ElementSchema(new Symbol("params")); params.setParams(newArrayList(ParamSpec.val(Type.List))); params.setType(new Type("Parameters")); langSchema.put(params); ElementSchema val = new ElementSchema(new Symbol("val")); val.setParams(newArrayList(ParamSpec.sym(Type.Symbol))); val.setType(new Type("Parameter")); langSchema.put(val); ElementSchema sym = new ElementSchema(new Symbol("sym")); sym.setParams(newArrayList(ParamSpec.sym(Type.Symbol))); sym.setType(new Type("Parameter")); langSchema.put(sym); ElementSchema variadic = new ElementSchema(new Symbol("variadic")); variadic.setParams(newArrayList(ParamSpec.val(new Type("Parameter")))); variadic.setType(new Type("Parameter")); langSchema.put(variadic); ElementSchema block = new ElementSchema(new Symbol("block")); block.setParams(newArrayList(ParamSpec.val(new Type("Parameter")))); block.setType(new Type("Parameter")); langSchema.put(block); ElementSchema type = new ElementSchema(new Symbol("type")); type.setParams(newArrayList(ParamSpec.sym(new Type("Symbol")))); type.setType(new Type("Type")); langSchema.put(type); ElementSchema defines = new ElementSchema(new Symbol("defines")); defines.setParams(newArrayList(ParamSpec.val(new Type("Number")), ParamSpec.sym(new Type("Symbol")))); defines.setType(new Type("Define")); langSchema.put(defines); ElementSchema defines_forward = new ElementSchema(new Symbol("defines_forward")); defines_forward.setParams(newArrayList(ParamSpec.val(new Type("Number")), ParamSpec.sym(new Type("Symbol")))); defines_forward.setType(new Type("Define")); langSchema.put(defines_forward); return langSchema; }
public Schema getSchema() { Schema langSchema = new Schema(); ElementSchema element = new ElementSchema(new Symbol("element")); element.setParams(newArrayList(ParamSpec.sym(new Type("Symbol")), ParamSpec.block(ParamSpec.val(new Type("Block"))))); element.setType(new Type("Symbol")); langSchema.put(element); ElementSchema params = new ElementSchema(new Symbol("params")); params.setParams(newArrayList(ParamSpec.val(Type.List))); params.setType(new Type("Parameters")); langSchema.put(params); ElementSchema val = new ElementSchema(new Symbol("val")); val.setParams(newArrayList(ParamSpec.sym(Type.Symbol))); val.setType(new Type("Parameter")); langSchema.put(val); ElementSchema sym = new ElementSchema(new Symbol("sym")); sym.setParams(newArrayList(ParamSpec.sym(Type.Symbol))); sym.setType(new Type("Parameter")); langSchema.put(sym); ElementSchema variadic = new ElementSchema(new Symbol("variadic")); variadic.setParams(newArrayList(ParamSpec.val(new Type("Parameter")))); variadic.setType(new Type("Parameter")); langSchema.put(variadic); ElementSchema block = new ElementSchema(new Symbol("block")); block.setParams(newArrayList(ParamSpec.val(new Type("Parameter")))); block.setType(new Type("Parameter")); langSchema.put(block); ElementSchema type = new ElementSchema(new Symbol("type")); type.setParams(newArrayList(ParamSpec.sym(new Type("Symbol")))); type.setType(new Type("Type")); langSchema.put(type); ElementSchema defines = new ElementSchema(new Symbol("defines")); defines.setParams(newArrayList(ParamSpec.val(new Type("Number")), ParamSpec.sym(new Type("Symbol")))); defines.setType(new Type("Define")); langSchema.put(defines); ElementSchema defines_forward = new ElementSchema(new Symbol("defines_forward")); defines_forward.setParams(newArrayList(ParamSpec.val(new Type("Number")), ParamSpec.sym(new Type("Symbol")))); defines_forward.setType(new Type("Define")); langSchema.put(defines_forward); return langSchema; }
diff --git a/components/I18n/src/main/java/org/dejava/component/i18n/source/processor/impl/GetterConstraintEntryProcessor.java b/components/I18n/src/main/java/org/dejava/component/i18n/source/processor/impl/GetterConstraintEntryProcessor.java index 9f6ad3c26..fcadc8c05 100644 --- a/components/I18n/src/main/java/org/dejava/component/i18n/source/processor/impl/GetterConstraintEntryProcessor.java +++ b/components/I18n/src/main/java/org/dejava/component/i18n/source/processor/impl/GetterConstraintEntryProcessor.java @@ -1,53 +1,53 @@ package org.dejava.component.i18n.source.processor.impl; import java.util.LinkedHashSet; import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.validation.Constraint; import org.dejava.component.i18n.source.processor.MessageSourceEntryProcessor; import org.dejava.component.reflection.MethodMirror; /** * Processes a class and retrieves entries for getter constraints. */ public class GetterConstraintEntryProcessor implements MessageSourceEntryProcessor { /** * @see org.dejava.component.i18n.source.processor.MessageSourceEntryProcessor#processClass(javax.lang.model.element.TypeElement, * javax.lang.model.element.TypeElement) */ @Override public Set<String> processClass(final TypeElement originalClass, final TypeElement currentClass) { // Creates an entry set. final Set<String> entries = new LinkedHashSet<>(); // For each enclosed elements of the class. for (final Element currentClassElement : currentClass.getEnclosedElements()) { - // If the element is a public final field. + // If the element is a method. if (currentClassElement.getKind() == ElementKind.METHOD) { // If the name is from a getter. if (MethodMirror.isGetter(currentClassElement.getSimpleName().toString())) { // For each annotation in the field. for (final AnnotationMirror currentAnnotation : currentClassElement .getAnnotationMirrors()) { // If the annotation is a constraint. - if (currentAnnotation.getClass().getAnnotation(Constraint.class) != null) { + if (currentAnnotation.getAnnotationType().asElement().getAnnotation(Constraint.class) != null) { // Adds the current field annotation name to the entry set. entries.add(originalClass.getSimpleName().toString() + '.' + MethodMirror.getFieldName(currentClassElement.getSimpleName() .toString()) + "." + currentAnnotation.getAnnotationType().asElement().getSimpleName()); } } } } } // Returns he retrieved entries. return entries; } }
false
true
public Set<String> processClass(final TypeElement originalClass, final TypeElement currentClass) { // Creates an entry set. final Set<String> entries = new LinkedHashSet<>(); // For each enclosed elements of the class. for (final Element currentClassElement : currentClass.getEnclosedElements()) { // If the element is a public final field. if (currentClassElement.getKind() == ElementKind.METHOD) { // If the name is from a getter. if (MethodMirror.isGetter(currentClassElement.getSimpleName().toString())) { // For each annotation in the field. for (final AnnotationMirror currentAnnotation : currentClassElement .getAnnotationMirrors()) { // If the annotation is a constraint. if (currentAnnotation.getClass().getAnnotation(Constraint.class) != null) { // Adds the current field annotation name to the entry set. entries.add(originalClass.getSimpleName().toString() + '.' + MethodMirror.getFieldName(currentClassElement.getSimpleName() .toString()) + "." + currentAnnotation.getAnnotationType().asElement().getSimpleName()); } } } } } // Returns he retrieved entries. return entries; }
public Set<String> processClass(final TypeElement originalClass, final TypeElement currentClass) { // Creates an entry set. final Set<String> entries = new LinkedHashSet<>(); // For each enclosed elements of the class. for (final Element currentClassElement : currentClass.getEnclosedElements()) { // If the element is a method. if (currentClassElement.getKind() == ElementKind.METHOD) { // If the name is from a getter. if (MethodMirror.isGetter(currentClassElement.getSimpleName().toString())) { // For each annotation in the field. for (final AnnotationMirror currentAnnotation : currentClassElement .getAnnotationMirrors()) { // If the annotation is a constraint. if (currentAnnotation.getAnnotationType().asElement().getAnnotation(Constraint.class) != null) { // Adds the current field annotation name to the entry set. entries.add(originalClass.getSimpleName().toString() + '.' + MethodMirror.getFieldName(currentClassElement.getSimpleName() .toString()) + "." + currentAnnotation.getAnnotationType().asElement().getSimpleName()); } } } } } // Returns he retrieved entries. return entries; }
diff --git a/core/src/test/java/dk/cubing/liveresults/utilities/CsvConverterTest.java b/core/src/test/java/dk/cubing/liveresults/utilities/CsvConverterTest.java index 4035a68..885ea91 100644 --- a/core/src/test/java/dk/cubing/liveresults/utilities/CsvConverterTest.java +++ b/core/src/test/java/dk/cubing/liveresults/utilities/CsvConverterTest.java @@ -1,76 +1,76 @@ /** * Copyright (C) 2009 Mads Mohr Christensen, <[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 dk.cubing.liveresults.utilities; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import java.io.StringReader; import java.io.StringWriter; public class CsvConverterTest { private CsvConverter conv; @Before public void setUp() throws Exception { conv = new CsvConverter(); } @Test public void testCompTool2Wca() throws Exception { String s = "Name,country,WCA ID,birthday,sex,,2,3,bts,ni,oh,py\n" + "Mads Mohr Christensen,Denmark,2007CHRI02,1978-03-13,m,,1,1,1,1,1,1\n"; String expected = "Status,Name,Country,WCA ID,Birth Date,Gender,,333,222,333oh,pyram,333ni,333bts,Email,Guests,IP\n" + "a,Mads Mohr Christensen,Denmark,2007CHRI02,1978-3-13,m,,1,1,1,1,1,1,,,127.0.0.1\n"; StringWriter sw = new StringWriter(); conv.compTool2Wca(new StringReader(s), sw); assertEquals(expected, sw.toString()); } @Test public void testWca2CompTool() throws Exception { String s = "Status,Name,Country,WCA ID,Birth Date,Gender,,222,333,333bts,333ni,333oh,pyram,Email,Guests,IP\n" + "a,Mads Mohr Christensen,Denmark,2007CHRI02,1978-3-13,m,,1,1,1,1,1,1,,,127.0.0.1\n"; String expected = "Name,country,WCA ID,birthday,sex,,3,2,oh,py,ni,bts\n" + "Mads Mohr Christensen,Denmark,2007CHRI02,1978-03-13,m,,1,1,1,1,1,1\n"; StringWriter sw = new StringWriter(); conv.wca2CompTool(new StringReader(s), sw); assertEquals(expected, sw.toString()); } @Test public void testCompTool2WcaAllEvents() throws Exception { String s = "Name,country,WCA ID,birthday,sex,,2,3,3b,4,4b,5,5b,6,7,cl,fm,ft,m,mbf,mm,mx,oh,py,s1\n" + "Mads Mohr Christensen,Denmark,2007CHRI02,1978-03-13,m,,1,1,1,1,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0\n" + - "Anders J�rgensen,Denmark,2009JORG01,1961-09-09,m,,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0\n"; + "Anders Jørgensen,Denmark,2009JORG01,1961-09-09,m,,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0\n"; String expected = "Status,Name,Country,WCA ID,Birth Date,Gender,,333,444,777,222,333bf,333oh,333fm,333ft,minx,pyram,sq1,clock,666,magic,mmagic,444bf,555bf,333mbf,Email,Guests,IP\n" + "a,Mads Mohr Christensen,Denmark,2007CHRI02,1978-3-13,m,,1,1,0,1,1,1,1,0,1,1,0,1,0,0,0,0,0,0,,,127.0.0.1\n" + - "a,Anders J�rgensen,Denmark,2009JORG01,1961-9-09,m,,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,,,127.0.0.1\n"; + "a,Anders Jørgensen,Denmark,2009JORG01,1961-9-09,m,,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,,,127.0.0.1\n"; StringWriter sw = new StringWriter(); conv.compTool2Wca(new StringReader(s), sw); assertEquals(expected, sw.toString()); } }
false
true
public void testCompTool2WcaAllEvents() throws Exception { String s = "Name,country,WCA ID,birthday,sex,,2,3,3b,4,4b,5,5b,6,7,cl,fm,ft,m,mbf,mm,mx,oh,py,s1\n" + "Mads Mohr Christensen,Denmark,2007CHRI02,1978-03-13,m,,1,1,1,1,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0\n" + "Anders J�rgensen,Denmark,2009JORG01,1961-09-09,m,,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0\n"; String expected = "Status,Name,Country,WCA ID,Birth Date,Gender,,333,444,777,222,333bf,333oh,333fm,333ft,minx,pyram,sq1,clock,666,magic,mmagic,444bf,555bf,333mbf,Email,Guests,IP\n" + "a,Mads Mohr Christensen,Denmark,2007CHRI02,1978-3-13,m,,1,1,0,1,1,1,1,0,1,1,0,1,0,0,0,0,0,0,,,127.0.0.1\n" + "a,Anders J�rgensen,Denmark,2009JORG01,1961-9-09,m,,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,,,127.0.0.1\n"; StringWriter sw = new StringWriter(); conv.compTool2Wca(new StringReader(s), sw); assertEquals(expected, sw.toString()); }
public void testCompTool2WcaAllEvents() throws Exception { String s = "Name,country,WCA ID,birthday,sex,,2,3,3b,4,4b,5,5b,6,7,cl,fm,ft,m,mbf,mm,mx,oh,py,s1\n" + "Mads Mohr Christensen,Denmark,2007CHRI02,1978-03-13,m,,1,1,1,1,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0\n" + "Anders Jørgensen,Denmark,2009JORG01,1961-09-09,m,,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0\n"; String expected = "Status,Name,Country,WCA ID,Birth Date,Gender,,333,444,777,222,333bf,333oh,333fm,333ft,minx,pyram,sq1,clock,666,magic,mmagic,444bf,555bf,333mbf,Email,Guests,IP\n" + "a,Mads Mohr Christensen,Denmark,2007CHRI02,1978-3-13,m,,1,1,0,1,1,1,1,0,1,1,0,1,0,0,0,0,0,0,,,127.0.0.1\n" + "a,Anders Jørgensen,Denmark,2009JORG01,1961-9-09,m,,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,,,127.0.0.1\n"; StringWriter sw = new StringWriter(); conv.compTool2Wca(new StringReader(s), sw); assertEquals(expected, sw.toString()); }
diff --git a/common/abo/pipes/PipeLiquidsBalance.java b/common/abo/pipes/PipeLiquidsBalance.java index f7c9ff1..ba9482d 100644 --- a/common/abo/pipes/PipeLiquidsBalance.java +++ b/common/abo/pipes/PipeLiquidsBalance.java @@ -1,207 +1,207 @@ /** * Copyright (C) 2011-2012 Flow86 * * AdditionalBuildcraftObjects is open-source. * * It is distributed under the terms of my Open Source License. * It grants rights to read, modify, compile or run the code. * It does *NOT* grant the right to redistribute this software or its * modifications in any form, binary or source, except if expressively * granted by the copyright holder. */ package abo.pipes; import java.util.LinkedList; import net.minecraft.src.TileEntity; import buildcraft.api.core.Orientations; import buildcraft.api.liquids.ILiquidTank; import buildcraft.api.liquids.ITankContainer; import buildcraft.api.liquids.LiquidStack; import buildcraft.transport.PipeTransportLiquids; import buildcraft.transport.TileGenericPipe; import buildcraft.transport.pipes.PipeLogicStone; /** * @author Flow86 * */ class Neighbor { public Neighbor(ITankContainer container, Orientations orientation) { c = container; o = orientation; } public int getLiquidId() { LiquidStack liquid = getTank().getLiquid(); return liquid != null ? liquid.itemID : 0; } public int getLiquidCapacity() { return getTank().getCapacity(); } public int getLiquidAmount() { LiquidStack liquid = getTank().getLiquid(); return liquid != null ? liquid.amount : 0; } public ILiquidTank getTank() { try { return c.getTanks()[o.reverse().ordinal()]; } catch (ArrayIndexOutOfBoundsException e) { try { return c.getTanks()[0]; } catch (ArrayIndexOutOfBoundsException f) { return null; } } } public ITankContainer getTankEntity() { return c; } public Orientations getOrientation() { return o; } private final ITankContainer c; private final Orientations o; } /** * A Pipe to balance/even tanks * * * @author Flow86 * */ public class PipeLiquidsBalance extends ABOPipe { private final int blockTexture = 5 * 16 + 0; public PipeLiquidsBalance(int itemID) { super(new PipeTransportLiquids(), new PipeLogicStone(), itemID); ((PipeTransportLiquids) transport).flowRate = 160; ((PipeTransportLiquids) transport).travelDelay = 1; } @Override public int getTextureIndex(Orientations direction) { return blockTexture; } @Override public int getTextureIndexForItem() { return blockTexture; } @Override public void updateEntity() { super.updateEntity(); doWork(); } @Override public boolean isPipeConnected(TileEntity tile) { if (tile == null || !(tile instanceof ITankContainer) || tile instanceof TileGenericPipe) return false; return super.isPipeConnected(tile); } public void doWork() { LinkedList<Neighbor> neighbors = new LinkedList<Neighbor>(); for (Orientations o : Orientations.dirs()) { TileEntity tile = container.tileBuffer[o.ordinal()].getTile(); - if (tile == null || !(tile instanceof ITankContainer)) + if (tile == null || tile instanceof TileGenericPipe || !(tile instanceof ITankContainer)) continue; Neighbor neighbor = new Neighbor((ITankContainer) tile, o); neighbors.add(neighbor); } PipeTransportLiquids ltransport = (PipeTransportLiquids) transport; int liquidID = 0; int liquidAmount = 0; int liquidCapacity = 0; int liquidNeighbors = 0; for (ILiquidTank tank : ltransport.getTanks()) { LiquidStack liquid = tank.getLiquid(); if (liquid != null) liquidAmount += liquid.amount; } LiquidStack liquid = ltransport.getTanks()[Orientations.Unknown.ordinal()].getLiquid(); if (liquid != null && liquid.amount > 0) liquidID = liquid.itemID; if (liquidID == 0) { for (Neighbor neighbor : neighbors) { if (neighbor == null) continue; liquidID = neighbor.getLiquidId(); if (liquidID != 0) break; } } for (Neighbor neighbor : neighbors) { if (neighbor == null) continue; if (liquidID == neighbor.getLiquidId() || neighbor.getLiquidId() == 0) { liquidAmount += neighbor.getLiquidAmount(); liquidCapacity += neighbor.getLiquidCapacity(); liquidNeighbors++; } } // should never happen ... if (liquidCapacity == 0 || liquidNeighbors == 0) return; int liquidAverage = liquidAmount / liquidNeighbors; for (Neighbor neighbor : neighbors) { int liquidToExtract = neighbor.getLiquidAmount() - liquidAverage; if (liquidToExtract > 1) { // drain tank (read available liquid) LiquidStack liquidExtracted = neighbor.getTankEntity().drain(neighbor.getOrientation(), liquidToExtract > ltransport.flowRate ? ltransport.flowRate : liquidToExtract, false); if (liquidExtracted != null) { // fill pipe int filled = ltransport.fill(neighbor.getOrientation(), liquidExtracted, true); if (filled != 0) { // really drain tank liquidExtracted = neighbor.getTankEntity().drain(neighbor.getOrientation(), filled, true); } } } else if (liquidToExtract < 1) { // drain pipe (read available liquid) LiquidStack liquidExtracted = ltransport.drain(neighbor.getOrientation().reverse(), liquidToExtract > ltransport.flowRate ? ltransport.flowRate : liquidToExtract, false); if (liquidExtracted != null) { // fill tank int filled = neighbor.getTankEntity().fill(neighbor.getOrientation().reverse(), liquidExtracted, true); if (filled != 0) { // really drain pipe liquidExtracted = ltransport.drain(neighbor.getOrientation().reverse(), filled, true); } } } } } }
true
true
public void doWork() { LinkedList<Neighbor> neighbors = new LinkedList<Neighbor>(); for (Orientations o : Orientations.dirs()) { TileEntity tile = container.tileBuffer[o.ordinal()].getTile(); if (tile == null || !(tile instanceof ITankContainer)) continue; Neighbor neighbor = new Neighbor((ITankContainer) tile, o); neighbors.add(neighbor); } PipeTransportLiquids ltransport = (PipeTransportLiquids) transport; int liquidID = 0; int liquidAmount = 0; int liquidCapacity = 0; int liquidNeighbors = 0; for (ILiquidTank tank : ltransport.getTanks()) { LiquidStack liquid = tank.getLiquid(); if (liquid != null) liquidAmount += liquid.amount; } LiquidStack liquid = ltransport.getTanks()[Orientations.Unknown.ordinal()].getLiquid(); if (liquid != null && liquid.amount > 0) liquidID = liquid.itemID; if (liquidID == 0) { for (Neighbor neighbor : neighbors) { if (neighbor == null) continue; liquidID = neighbor.getLiquidId(); if (liquidID != 0) break; } } for (Neighbor neighbor : neighbors) { if (neighbor == null) continue; if (liquidID == neighbor.getLiquidId() || neighbor.getLiquidId() == 0) { liquidAmount += neighbor.getLiquidAmount(); liquidCapacity += neighbor.getLiquidCapacity(); liquidNeighbors++; } } // should never happen ... if (liquidCapacity == 0 || liquidNeighbors == 0) return; int liquidAverage = liquidAmount / liquidNeighbors; for (Neighbor neighbor : neighbors) { int liquidToExtract = neighbor.getLiquidAmount() - liquidAverage; if (liquidToExtract > 1) { // drain tank (read available liquid) LiquidStack liquidExtracted = neighbor.getTankEntity().drain(neighbor.getOrientation(), liquidToExtract > ltransport.flowRate ? ltransport.flowRate : liquidToExtract, false); if (liquidExtracted != null) { // fill pipe int filled = ltransport.fill(neighbor.getOrientation(), liquidExtracted, true); if (filled != 0) { // really drain tank liquidExtracted = neighbor.getTankEntity().drain(neighbor.getOrientation(), filled, true); } } } else if (liquidToExtract < 1) { // drain pipe (read available liquid) LiquidStack liquidExtracted = ltransport.drain(neighbor.getOrientation().reverse(), liquidToExtract > ltransport.flowRate ? ltransport.flowRate : liquidToExtract, false); if (liquidExtracted != null) { // fill tank int filled = neighbor.getTankEntity().fill(neighbor.getOrientation().reverse(), liquidExtracted, true); if (filled != 0) { // really drain pipe liquidExtracted = ltransport.drain(neighbor.getOrientation().reverse(), filled, true); } } } } }
public void doWork() { LinkedList<Neighbor> neighbors = new LinkedList<Neighbor>(); for (Orientations o : Orientations.dirs()) { TileEntity tile = container.tileBuffer[o.ordinal()].getTile(); if (tile == null || tile instanceof TileGenericPipe || !(tile instanceof ITankContainer)) continue; Neighbor neighbor = new Neighbor((ITankContainer) tile, o); neighbors.add(neighbor); } PipeTransportLiquids ltransport = (PipeTransportLiquids) transport; int liquidID = 0; int liquidAmount = 0; int liquidCapacity = 0; int liquidNeighbors = 0; for (ILiquidTank tank : ltransport.getTanks()) { LiquidStack liquid = tank.getLiquid(); if (liquid != null) liquidAmount += liquid.amount; } LiquidStack liquid = ltransport.getTanks()[Orientations.Unknown.ordinal()].getLiquid(); if (liquid != null && liquid.amount > 0) liquidID = liquid.itemID; if (liquidID == 0) { for (Neighbor neighbor : neighbors) { if (neighbor == null) continue; liquidID = neighbor.getLiquidId(); if (liquidID != 0) break; } } for (Neighbor neighbor : neighbors) { if (neighbor == null) continue; if (liquidID == neighbor.getLiquidId() || neighbor.getLiquidId() == 0) { liquidAmount += neighbor.getLiquidAmount(); liquidCapacity += neighbor.getLiquidCapacity(); liquidNeighbors++; } } // should never happen ... if (liquidCapacity == 0 || liquidNeighbors == 0) return; int liquidAverage = liquidAmount / liquidNeighbors; for (Neighbor neighbor : neighbors) { int liquidToExtract = neighbor.getLiquidAmount() - liquidAverage; if (liquidToExtract > 1) { // drain tank (read available liquid) LiquidStack liquidExtracted = neighbor.getTankEntity().drain(neighbor.getOrientation(), liquidToExtract > ltransport.flowRate ? ltransport.flowRate : liquidToExtract, false); if (liquidExtracted != null) { // fill pipe int filled = ltransport.fill(neighbor.getOrientation(), liquidExtracted, true); if (filled != 0) { // really drain tank liquidExtracted = neighbor.getTankEntity().drain(neighbor.getOrientation(), filled, true); } } } else if (liquidToExtract < 1) { // drain pipe (read available liquid) LiquidStack liquidExtracted = ltransport.drain(neighbor.getOrientation().reverse(), liquidToExtract > ltransport.flowRate ? ltransport.flowRate : liquidToExtract, false); if (liquidExtracted != null) { // fill tank int filled = neighbor.getTankEntity().fill(neighbor.getOrientation().reverse(), liquidExtracted, true); if (filled != 0) { // really drain pipe liquidExtracted = ltransport.drain(neighbor.getOrientation().reverse(), filled, true); } } } } }