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/test-harness/projects/concept/flex-touchstone/todolist/todolist-java/src/main/java/org/sonatype/flexmojos/todolist/business/TodoServiceImpl.java b/test-harness/projects/concept/flex-touchstone/todolist/todolist-java/src/main/java/org/sonatype/flexmojos/todolist/business/TodoServiceImpl.java index 35f8da5c..bc17f3ce 100644 --- a/test-harness/projects/concept/flex-touchstone/todolist/todolist-java/src/main/java/org/sonatype/flexmojos/todolist/business/TodoServiceImpl.java +++ b/test-harness/projects/concept/flex-touchstone/todolist/todolist-java/src/main/java/org/sonatype/flexmojos/todolist/business/TodoServiceImpl.java @@ -1,53 +1,56 @@ /** * Copyright 2008 Marvin Herman Froeder * 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.sonatype.flexmojos.todolist.business; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.sonatype.flexmojos.todolist.domain.TodoItem; public class TodoServiceImpl implements TodoService { private static Map<String, TodoItem> items = new HashMap<String, TodoItem>(); public TodoItem save( TodoItem item ) throws Exception { - item.setId( Long.toHexString( System.nanoTime() ) ); + if ( item.getId() == null || item.getId().length() == 0 ) + { + item.setId( Long.toHexString( System.nanoTime() ) ); + } items.put( item.getId(), item ); return item; } public void remove( TodoItem item ) throws Exception { items.remove( item.getId() ); } public TodoItem findById( TodoItem item ) throws Exception { return items.get( item.getId() ); } public Collection<TodoItem> getList() throws Exception { return items.values(); } }
true
true
public TodoItem save( TodoItem item ) throws Exception { item.setId( Long.toHexString( System.nanoTime() ) ); items.put( item.getId(), item ); return item; }
public TodoItem save( TodoItem item ) throws Exception { if ( item.getId() == null || item.getId().length() == 0 ) { item.setId( Long.toHexString( System.nanoTime() ) ); } items.put( item.getId(), item ); return item; }
diff --git a/src/test/java/com/github/ukrainiantolatin/UkrainianToLatinTest.java b/src/test/java/com/github/ukrainiantolatin/UkrainianToLatinTest.java index dbabd08..8e77d3a 100644 --- a/src/test/java/com/github/ukrainiantolatin/UkrainianToLatinTest.java +++ b/src/test/java/com/github/ukrainiantolatin/UkrainianToLatinTest.java @@ -1,47 +1,47 @@ /* * $Id$ * * Copyright (c) 2012 Valentyn Kolesnikov * * 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.github.ukrainiantolatin; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * UkrainianToLatin unit test. * * @author Valentyn Kolesnikov * @version $Revision$ $Date$ */ public class UkrainianToLatinTest { /** * Checks string converter. */ @Test public void generateLat() { assertEquals("", UkrainianToLatin.generateLat("")); assertEquals("abvhd", UkrainianToLatin.generateLat("абвгд")); assertEquals("abvhd kh", UkrainianToLatin.generateLat("абвгд х")); assertEquals("abvhd kh yulia", UkrainianToLatin.generateLat("абвгд х юля")); assertEquals("yizhak", UkrainianToLatin.generateLat("їжак")); assertEquals("yizhak-siryi", UkrainianToLatin.generateLat("їжак-сірий")); - assertEquals("Rozghon", UkrainianToLatin.generateLat("Розгон")); - assertEquals("Zghorany", UkrainianToLatin.generateLat("Згорани")); - assertEquals("Zghorany'", UkrainianToLatin.generateLat("Згорани'")); - assertEquals("Zghorany'", UkrainianToLatin.generateLat("Згорани’")); + assertEquals("Rozhon", UkrainianToLatin.generateLat("Розгон")); + assertEquals("Zhorany", UkrainianToLatin.generateLat("Згорани")); + assertEquals("Zhorany'", UkrainianToLatin.generateLat("Згорани'")); + assertEquals("Zhorany'", UkrainianToLatin.generateLat("Згорани’")); } }
true
true
@Test public void generateLat() { assertEquals("", UkrainianToLatin.generateLat("")); assertEquals("abvhd", UkrainianToLatin.generateLat("абвгд")); assertEquals("abvhd kh", UkrainianToLatin.generateLat("абвгд х")); assertEquals("abvhd kh yulia", UkrainianToLatin.generateLat("абвгд х юля")); assertEquals("yizhak", UkrainianToLatin.generateLat("їжак")); assertEquals("yizhak-siryi", UkrainianToLatin.generateLat("їжак-сірий")); assertEquals("Rozghon", UkrainianToLatin.generateLat("Розгон")); assertEquals("Zghorany", UkrainianToLatin.generateLat("Згорани")); assertEquals("Zghorany'", UkrainianToLatin.generateLat("Згорани'")); assertEquals("Zghorany'", UkrainianToLatin.generateLat("Згорани’")); }
@Test public void generateLat() { assertEquals("", UkrainianToLatin.generateLat("")); assertEquals("abvhd", UkrainianToLatin.generateLat("абвгд")); assertEquals("abvhd kh", UkrainianToLatin.generateLat("абвгд х")); assertEquals("abvhd kh yulia", UkrainianToLatin.generateLat("абвгд х юля")); assertEquals("yizhak", UkrainianToLatin.generateLat("їжак")); assertEquals("yizhak-siryi", UkrainianToLatin.generateLat("їжак-сірий")); assertEquals("Rozhon", UkrainianToLatin.generateLat("Розгон")); assertEquals("Zhorany", UkrainianToLatin.generateLat("Згорани")); assertEquals("Zhorany'", UkrainianToLatin.generateLat("Згорани'")); assertEquals("Zhorany'", UkrainianToLatin.generateLat("Згорани’")); }
diff --git a/src/games/batoru/client/PatchyLandscapeRenderer.java b/src/games/batoru/client/PatchyLandscapeRenderer.java index 8ce2a0e..12e1c22 100644 --- a/src/games/batoru/client/PatchyLandscapeRenderer.java +++ b/src/games/batoru/client/PatchyLandscapeRenderer.java @@ -1,104 +1,105 @@ package games.batoru.client; import javax.vecmath.*; import net.java.games.jogl.GL; import org.codejive.utils4gl.RenderContext; import org.codejive.utils4gl.Renderable; import org.codejive.world3d.Universe; import games.batoru.PatchyLandscape; /** * @author Tako * */ public class PatchyLandscapeRenderer implements Renderable { private Universe m_universe; private PatchyLandscape m_model; private long m_lTimeOfBirth; private int m_nTerrainList; public PatchyLandscapeRenderer(Universe _universe, PatchyLandscape _model) { m_universe = _universe; m_model = _model; m_lTimeOfBirth = m_universe.getAge(); m_nTerrainList = -1; } public boolean readyForRendering() { return (m_nTerrainList != -1); } public void initRendering(RenderContext _context) { GL gl = _context.getGl(); m_nTerrainList = gl.glGenLists(1); gl.glNewList(m_nTerrainList, GL.GL_COMPILE); renderGeo(gl); gl.glEndList(); } public void render(RenderContext _context) { GL gl = _context.getGl(); gl.glBindTexture(gl.GL_TEXTURE_2D, _context.getTextureHandle(0)); float fTimer = (m_universe.getAge() - m_lTimeOfBirth) / 1000.0f; if (fTimer < 4.0f) { float fScale = (fTimer / 4.0f); gl.glColor4f(1.0f, 1.0f, 1.0f, Math.max(fScale, 0.2f)); // gl.glEnable(GL.GL_BLEND); // gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); // Translucency gl.glScalef(1.0f, fScale, 1.0f); gl.glColor3f(1, 1, 1); gl.glBegin(GL.GL_TRIANGLE_STRIP); gl.glCallList(m_nTerrainList); gl.glEnd(); // gl.glDisable(GL.GL_BLEND); } else { + gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); gl.glBegin(GL.GL_TRIANGLE_STRIP); gl.glCallList(m_nTerrainList); gl.glEnd(); } /* if (fTimer < 4.0f) { gl.glDisable(GL.GL_DEPTH_TEST); gl.glScalef(1.0f, 1.0f, 1.0f); gl.glBegin(GL.GL_LINES); gl.glCallList(m_nTerrainList); gl.glEnd(); gl.glEnable(GL.GL_DEPTH_TEST); } */ } private void renderGeo(GL _gl) { float vfHeights[][] = m_model.getHeights(); Point3f origin = m_model.getOrigin(); boolean bSwitchDirection = false; int w = m_model.getWidth(); int h = m_model.getHeight(); for (int i = 0; i < w; i++) { if (bSwitchDirection) { for (int j = 0; j < h; j++) { _gl.glTexCoord2f((float)(i + 1) / w, (float)j / h); _gl.glVertex3f(origin.x + (i + 1) * m_model.getPatchWidth(), origin.y + vfHeights[i + 1][j], origin.z + j * m_model.getPatchHeight()); _gl.glTexCoord2f((float)i / w, (float)j / h); _gl.glVertex3f(origin.x + i * m_model.getPatchWidth(), origin.y + vfHeights[i][j], origin.z + j * m_model.getPatchHeight()); } } else { for (int j = h - 1; j >= 0; j--) { _gl.glTexCoord2f((float)i / w, (float)j / h); _gl.glVertex3f(origin.x + i * m_model.getPatchWidth(), origin.y + vfHeights[i][j], origin.z + j * m_model.getPatchHeight()); _gl.glTexCoord2f((float)(i + 1) / w, (float)j / h); _gl.glVertex3f(origin.x + (i + 1) * m_model.getPatchWidth(), origin.y + vfHeights[i + 1][j], origin.z + j * m_model.getPatchHeight()); } } bSwitchDirection = !bSwitchDirection; } } }
true
true
public void render(RenderContext _context) { GL gl = _context.getGl(); gl.glBindTexture(gl.GL_TEXTURE_2D, _context.getTextureHandle(0)); float fTimer = (m_universe.getAge() - m_lTimeOfBirth) / 1000.0f; if (fTimer < 4.0f) { float fScale = (fTimer / 4.0f); gl.glColor4f(1.0f, 1.0f, 1.0f, Math.max(fScale, 0.2f)); // gl.glEnable(GL.GL_BLEND); // gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); // Translucency gl.glScalef(1.0f, fScale, 1.0f); gl.glColor3f(1, 1, 1); gl.glBegin(GL.GL_TRIANGLE_STRIP); gl.glCallList(m_nTerrainList); gl.glEnd(); // gl.glDisable(GL.GL_BLEND); } else { gl.glBegin(GL.GL_TRIANGLE_STRIP); gl.glCallList(m_nTerrainList); gl.glEnd(); } /* if (fTimer < 4.0f) { gl.glDisable(GL.GL_DEPTH_TEST); gl.glScalef(1.0f, 1.0f, 1.0f); gl.glBegin(GL.GL_LINES); gl.glCallList(m_nTerrainList); gl.glEnd(); gl.glEnable(GL.GL_DEPTH_TEST); }
public void render(RenderContext _context) { GL gl = _context.getGl(); gl.glBindTexture(gl.GL_TEXTURE_2D, _context.getTextureHandle(0)); float fTimer = (m_universe.getAge() - m_lTimeOfBirth) / 1000.0f; if (fTimer < 4.0f) { float fScale = (fTimer / 4.0f); gl.glColor4f(1.0f, 1.0f, 1.0f, Math.max(fScale, 0.2f)); // gl.glEnable(GL.GL_BLEND); // gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); // Translucency gl.glScalef(1.0f, fScale, 1.0f); gl.glColor3f(1, 1, 1); gl.glBegin(GL.GL_TRIANGLE_STRIP); gl.glCallList(m_nTerrainList); gl.glEnd(); // gl.glDisable(GL.GL_BLEND); } else { gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); gl.glBegin(GL.GL_TRIANGLE_STRIP); gl.glCallList(m_nTerrainList); gl.glEnd(); } /* if (fTimer < 4.0f) { gl.glDisable(GL.GL_DEPTH_TEST); gl.glScalef(1.0f, 1.0f, 1.0f); gl.glBegin(GL.GL_LINES); gl.glCallList(m_nTerrainList); gl.glEnd(); gl.glEnable(GL.GL_DEPTH_TEST); }
diff --git a/src/org/rascalmpl/semantics/dynamic/UserType.java b/src/org/rascalmpl/semantics/dynamic/UserType.java index 61ce0fd137..0f92ac0576 100644 --- a/src/org/rascalmpl/semantics/dynamic/UserType.java +++ b/src/org/rascalmpl/semantics/dynamic/UserType.java @@ -1,119 +1,121 @@ /******************************************************************************* * Copyright (c) 2009-2011 CWI * 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: * * Jurgen J. Vinju - [email protected] - CWI * * Mark Hills - [email protected] (CWI) *******************************************************************************/ package org.rascalmpl.semantics.dynamic; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.imp.pdb.facts.IConstructor; import org.eclipse.imp.pdb.facts.type.Type; import org.rascalmpl.ast.QualifiedName; import org.rascalmpl.interpreter.env.Environment; import org.rascalmpl.interpreter.staticErrors.UndeclaredTypeError; public abstract class UserType extends org.rascalmpl.ast.UserType { static public class Name extends org.rascalmpl.ast.UserType.Name { public Name(IConstructor __param1, QualifiedName __param2) { super(__param1, __param2); } @Override public Type typeOf(Environment __eval) { Environment theEnv = __eval.getHeap().getEnvironmentForName( getName(), __eval); String name = org.rascalmpl.interpreter.utils.Names.typeName(this .getName()); if (theEnv != null) { Type type = theEnv.lookupAlias(name); if (type != null) { return type; } Type tree = theEnv.lookupAbstractDataType(name); if (tree != null) { return tree; } Type symbol = theEnv.lookupConcreteSyntaxType(name); if (symbol != null) { return symbol; } } throw new UndeclaredTypeError(name, this); } } static public class Parametric extends org.rascalmpl.ast.UserType.Parametric { public Parametric(IConstructor __param1, QualifiedName __param2, List<org.rascalmpl.ast.Type> __param3) { super(__param1, __param2, __param3); } @Override public Type typeOf(Environment __eval) { String name; Type type = null; Environment theEnv = __eval.getHeap().getEnvironmentForName( this.getName(), __eval); name = org.rascalmpl.interpreter.utils.Names.typeName(this .getName()); if (theEnv != null) { type = theEnv.lookupAlias(name); if (type == null) { type = theEnv.lookupAbstractDataType(name); } } if (type != null) { Map<Type, Type> bindings = new HashMap<Type, Type>(); Type[] params = new Type[this.getParameters().size()]; int i = 0; for (org.rascalmpl.ast.Type param : this.getParameters()) { params[i++] = param.typeOf(__eval); } // __eval has side-effects that we might need? type.getTypeParameters().match(TF.tupleType(params), bindings); - // Note that instantiation use type variables from the current - // context, not the declaring context - Type outerInstance = type.instantiate(__eval.getTypeBindings()); - return outerInstance.instantiate(bindings); + // Instantiate first using the type actually given in the parameter, + // e.g., for T[str], with data T[&U] = ..., instantate the binding + // of &U = str, and then instantate using bindings from the current + // environment (generally meaning we are inside a function with + // type parameters, and those parameters are now bound to real types) + return type.instantiate(bindings).instantiate(__eval.getTypeBindings()); } throw new UndeclaredTypeError(name, this); } } public UserType(IConstructor __param1) { super(__param1); } }
true
true
public Type typeOf(Environment __eval) { String name; Type type = null; Environment theEnv = __eval.getHeap().getEnvironmentForName( this.getName(), __eval); name = org.rascalmpl.interpreter.utils.Names.typeName(this .getName()); if (theEnv != null) { type = theEnv.lookupAlias(name); if (type == null) { type = theEnv.lookupAbstractDataType(name); } } if (type != null) { Map<Type, Type> bindings = new HashMap<Type, Type>(); Type[] params = new Type[this.getParameters().size()]; int i = 0; for (org.rascalmpl.ast.Type param : this.getParameters()) { params[i++] = param.typeOf(__eval); } // __eval has side-effects that we might need? type.getTypeParameters().match(TF.tupleType(params), bindings); // Note that instantiation use type variables from the current // context, not the declaring context Type outerInstance = type.instantiate(__eval.getTypeBindings()); return outerInstance.instantiate(bindings); } throw new UndeclaredTypeError(name, this); }
public Type typeOf(Environment __eval) { String name; Type type = null; Environment theEnv = __eval.getHeap().getEnvironmentForName( this.getName(), __eval); name = org.rascalmpl.interpreter.utils.Names.typeName(this .getName()); if (theEnv != null) { type = theEnv.lookupAlias(name); if (type == null) { type = theEnv.lookupAbstractDataType(name); } } if (type != null) { Map<Type, Type> bindings = new HashMap<Type, Type>(); Type[] params = new Type[this.getParameters().size()]; int i = 0; for (org.rascalmpl.ast.Type param : this.getParameters()) { params[i++] = param.typeOf(__eval); } // __eval has side-effects that we might need? type.getTypeParameters().match(TF.tupleType(params), bindings); // Instantiate first using the type actually given in the parameter, // e.g., for T[str], with data T[&U] = ..., instantate the binding // of &U = str, and then instantate using bindings from the current // environment (generally meaning we are inside a function with // type parameters, and those parameters are now bound to real types) return type.instantiate(bindings).instantiate(__eval.getTypeBindings()); } throw new UndeclaredTypeError(name, this); }
diff --git a/framework/common/src/org/ofbiz/common/email/EmailServices.java b/framework/common/src/org/ofbiz/common/email/EmailServices.java index 162c289de..cabecfb08 100644 --- a/framework/common/src/org/ofbiz/common/email/EmailServices.java +++ b/framework/common/src/org/ofbiz/common/email/EmailServices.java @@ -1,690 +1,692 @@ /******************************************************************************* * 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. *******************************************************************************/ /* This file has been modified by Open Source Strategies, Inc. */ package org.ofbiz.common.email; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.security.Security; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.SendFailedException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.stream.StreamSource; import javolution.util.FastList; import javolution.util.FastMap; import org.apache.fop.apps.FOPException; import org.apache.fop.apps.Fop; import org.apache.fop.apps.MimeConstants; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.GeneralException; import org.ofbiz.base.util.HttpClient; import org.ofbiz.base.util.HttpClientException; import org.ofbiz.base.util.UtilGenerics; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.collections.MapStack; import org.ofbiz.base.util.string.FlexibleStringExpander; import org.ofbiz.entity.GenericValue; import org.ofbiz.service.DispatchContext; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.ServiceUtil; import org.ofbiz.service.mail.MimeMessageWrapper; import org.ofbiz.webapp.view.ApacheFopWorker; import org.ofbiz.widget.fo.FoScreenRenderer; import org.ofbiz.widget.html.HtmlScreenRenderer; import org.ofbiz.widget.screen.ScreenRenderer; import org.xml.sax.SAXException; import com.sun.mail.smtp.SMTPAddressFailedException; /** * Email Services */ public class EmailServices { public final static String module = EmailServices.class.getName(); protected static final HtmlScreenRenderer htmlScreenRenderer = new HtmlScreenRenderer(); protected static final FoScreenRenderer foScreenRenderer = new FoScreenRenderer(); /** * Basic JavaMail Service *@param ctx The DispatchContext that this service is operating in *@param context Map containing the input parameters *@return Map with the result of the service, the output parameters */ public static Map<String, Object> sendMail(DispatchContext ctx, Map<String, ? extends Object> context) { String communicationEventId = (String) context.get("communicationEventId"); String orderId = (String) context.get("orderId"); if (communicationEventId != null) { Debug.logInfo("SendMail Running, for communicationEventId : " + communicationEventId, module); } Map<String, Object> results = ServiceUtil.returnSuccess(); String subject = (String) context.get("subject"); subject = FlexibleStringExpander.expandString(subject, context); String partyId = (String) context.get("partyId"); String body = (String) context.get("body"); List<Map<String, Object>> bodyParts = UtilGenerics.checkList(context.get("bodyParts")); GenericValue userLogin = (GenericValue) context.get("userLogin"); results.put("communicationEventId", communicationEventId); results.put("partyId", partyId); results.put("subject", subject); if (UtilValidate.isNotEmpty(orderId)) { results.put("orderId", orderId); } if (UtilValidate.isNotEmpty(body)) { body = FlexibleStringExpander.expandString(body, context); results.put("body", body); } if (UtilValidate.isNotEmpty(bodyParts)) { results.put("bodyParts", bodyParts); } results.put("userLogin", userLogin); String sendTo = (String) context.get("sendTo"); String sendCc = (String) context.get("sendCc"); String sendBcc = (String) context.get("sendBcc"); // check to see if we should redirect all mail for testing String redirectAddress = UtilProperties.getPropertyValue("general.properties", "mail.notifications.redirectTo"); if (UtilValidate.isNotEmpty(redirectAddress)) { String originalRecipients = " [To: " + sendTo + ", Cc: " + sendCc + ", Bcc: " + sendBcc + "]"; subject += originalRecipients; sendTo = redirectAddress; sendCc = null; sendBcc = null; } String sendFrom = (String) context.get("sendFrom"); String sendType = (String) context.get("sendType"); String port = (String) context.get("port"); String socketFactoryClass = (String) context.get("socketFactoryClass"); String socketFactoryPort = (String) context.get("socketFactoryPort"); String socketFactoryFallback = (String) context.get("socketFactoryFallback"); String sendVia = (String) context.get("sendVia"); String authUser = (String) context.get("authUser"); String authPass = (String) context.get("authPass"); String messageId = (String) context.get("messageId"); String contentType = (String) context.get("contentType"); Boolean sendPartial = (Boolean) context.get("sendPartial"); boolean useSmtpAuth = false; // define some default if (sendType == null || sendType.equals("mail.smtp.host")) { sendType = "mail.smtp.host"; if (UtilValidate.isEmpty(sendVia)) { sendVia = UtilProperties.getPropertyValue("general.properties", "mail.smtp.relay.host", "localhost"); } if (UtilValidate.isEmpty(authUser)) { authUser = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.user"); } if (UtilValidate.isEmpty(authPass)) { authPass = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.password"); } if (UtilValidate.isNotEmpty(authUser)) { useSmtpAuth = true; } if (UtilValidate.isEmpty(port)) { port = UtilProperties.getPropertyValue("general.properties", "mail.smtp.port"); } if (UtilValidate.isEmpty(socketFactoryPort)) { socketFactoryPort = UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.port"); } if (UtilValidate.isEmpty(socketFactoryClass)) { socketFactoryClass = UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.class"); } if (UtilValidate.isEmpty(socketFactoryFallback)) { socketFactoryFallback = UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.fallback", "false"); } if (sendPartial == null) { sendPartial = UtilProperties.propertyValueEqualsIgnoreCase("general.properties", "mail.smtp.sendpartial", "true") ? true : false; } } else if (sendVia == null) { return ServiceUtil.returnError("Parameter sendVia is required when sendType is not mail.smtp.host"); } if (contentType == null) { contentType = "text/html"; } if (UtilValidate.isNotEmpty(bodyParts)) { contentType = "multipart/mixed"; } results.put("contentType", contentType); Session session; MimeMessage mail; try { Properties props = System.getProperties(); props.put(sendType, sendVia); if (UtilValidate.isNotEmpty(port)) { props.put("mail.smtp.port", port); } if (UtilValidate.isNotEmpty(socketFactoryPort)) { props.put("mail.smtp.socketFactory.port", socketFactoryPort); } if (UtilValidate.isNotEmpty(socketFactoryClass)) { props.put("mail.smtp.socketFactory.class", socketFactoryClass); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); } if (UtilValidate.isNotEmpty(socketFactoryFallback)) { props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback); } if (useSmtpAuth) { props.put("mail.smtp.auth", "true"); } if (sendPartial != null) { props.put("mail.smtp.sendpartial", sendPartial ? "true" : "false"); } session = Session.getInstance(props); boolean debug = UtilProperties.propertyValueEqualsIgnoreCase("general.properties", "mail.debug.on", "Y"); session.setDebug(debug); mail = new MimeMessage(session); if (messageId != null) { mail.setHeader("In-Reply-To", messageId); mail.setHeader("References", messageId); } - mail.setFrom(new InternetAddress(sendFrom)); + InternetAddress sender = new InternetAddress(sendFrom, sendFrom); + mail.setFrom(sender); + mail.setReplyTo(new InternetAddress[] {sender}); mail.setSubject(subject, "UTF-8"); mail.setHeader("X-Mailer", "Apache OFBiz, The Apache Open For Business Project"); mail.setSentDate(new Date()); mail.addRecipients(Message.RecipientType.TO, sendTo); if (UtilValidate.isNotEmpty(sendCc)) { mail.addRecipients(Message.RecipientType.CC, sendCc); } if (UtilValidate.isNotEmpty(sendBcc)) { mail.addRecipients(Message.RecipientType.BCC, sendBcc); } if (UtilValidate.isNotEmpty(bodyParts)) { // check for multipart message (with attachments) // BodyParts contain a list of Maps items containing content(String) and type(String) of the attachement MimeMultipart mp = new MimeMultipart(); Debug.logInfo(bodyParts.size() + " multiparts found",module); for (Map<String, Object> bodyPart: bodyParts) { Object bodyPartContent = bodyPart.get("content"); MimeBodyPart mbp = new MimeBodyPart(); if (bodyPartContent instanceof String) { Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: " + bodyPart.get("content").toString().length() , module); mbp.setText((String) bodyPartContent, "UTF-8", ((String) bodyPart.get("type")).substring(5)); } else if (bodyPartContent instanceof byte[]) { ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) bodyPartContent, (String) bodyPart.get("type")); Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: " + ((byte[]) bodyPartContent).length , module); mbp.setDataHandler(new DataHandler(bads)); } else if (bodyPartContent instanceof DataHandler) { mbp.setDataHandler((DataHandler) bodyPartContent); } else { mbp.setDataHandler(new DataHandler(bodyPartContent, (String) bodyPart.get("type"))); } String fileName = (String) bodyPart.get("filename"); if (fileName != null) { mbp.setFileName(fileName); } mp.addBodyPart(mbp); } mail.setContent(mp); mail.saveChanges(); } else { // create the singelpart message if (contentType.startsWith("text")) { mail.setText(body, "UTF-8", contentType.substring(5)); } else { mail.setContent(body, contentType); } mail.saveChanges(); } } catch (MessagingException e) { String errMsg = "MessagingException when creating message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]"; Debug.logError(e, errMsg, module); Debug.logError("Email message that could not be created to [" + sendTo + "] had context: " + context, module); return ServiceUtil.returnError(errMsg); } catch (IOException e) { String errMsg = "IOExcepton when creating message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]"; Debug.logError(e, errMsg, module); Debug.logError("Email message that could not be created to [" + sendTo + "] had context: " + context, module); return ServiceUtil.returnError(errMsg); } // check to see if sending mail is enabled String mailEnabled = UtilProperties.getPropertyValue("general.properties", "mail.notifications.enabled", "N"); if (!"Y".equalsIgnoreCase(mailEnabled)) { // no error; just return as if we already processed Debug.logImportant("Mail notifications disabled in general.properties; mail with subject [" + subject + "] not sent to addressee [" + sendTo + "]", module); Debug.logVerbose("What would have been sent, the addressee: " + sendTo + " subject: " + subject + " context: " + context, module); results.put("messageWrapper", new MimeMessageWrapper(session, mail)); return results; } Transport trans = null; try { trans = session.getTransport("smtp"); if (!useSmtpAuth) { trans.connect(); } else { trans.connect(sendVia, authUser, authPass); } trans.sendMessage(mail, mail.getAllRecipients()); results.put("messageWrapper", new MimeMessageWrapper(session, mail)); results.put("messageId", mail.getMessageID()); trans.close(); } catch (SendFailedException e) { // message code prefix may be used by calling services to determine the cause of the failure String errMsg = "[ADDRERR] Address error when sending message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]"; Debug.logError(e, errMsg, module); List<SMTPAddressFailedException> failedAddresses = FastList.newInstance(); Exception nestedException = null; while ((nestedException = e.getNextException()) != null && nestedException instanceof MessagingException) { if (nestedException instanceof SMTPAddressFailedException) { SMTPAddressFailedException safe = (SMTPAddressFailedException) nestedException; Debug.logError("Failed to send message to [" + safe.getAddress() + "], return code [" + safe.getReturnCode() + "], return message [" + safe.getMessage() + "]", errMsg); failedAddresses.add(safe); break; } } Boolean sendFailureNotification = (Boolean) context.get("sendFailureNotification"); if (sendFailureNotification == null || sendFailureNotification) { sendFailureNotification(ctx, context, mail, failedAddresses); results.put("messageWrapper", new MimeMessageWrapper(session, mail)); try { results.put("messageId", mail.getMessageID()); trans.close(); } catch (MessagingException e1) { Debug.logError(e1, module); } } else { return ServiceUtil.returnError(errMsg); } } catch (MessagingException e) { // message code prefix may be used by calling services to determine the cause of the failure String errMsg = "[CON] Connection error when sending message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]"; Debug.logError(e, errMsg, module); Debug.logError("Email message that could not be sent to [" + sendTo + "] had context: " + context, module); return ServiceUtil.returnError(errMsg); } return results; } /** * JavaMail Service that gets body content from a URL *@param ctx The DispatchContext that this service is operating in *@param rcontext Map containing the input parameters *@return Map with the result of the service, the output parameters */ public static Map<String, Object> sendMailFromUrl(DispatchContext ctx, Map<String, ? extends Object> rcontext) { // pretty simple, get the content and then call the sendMail method below Map<String, Object> sendMailContext = UtilMisc.makeMapWritable(rcontext); String bodyUrl = (String) sendMailContext.remove("bodyUrl"); Map<String, Object> bodyUrlParameters = UtilGenerics.checkMap(sendMailContext.remove("bodyUrlParameters")); LocalDispatcher dispatcher = ctx.getDispatcher(); URL url = null; try { url = new URL(bodyUrl); } catch (MalformedURLException e) { Debug.logWarning(e, module); return ServiceUtil.returnError("Malformed URL: " + bodyUrl + "; error was: " + e.toString()); } HttpClient httpClient = new HttpClient(url, bodyUrlParameters); String body = null; try { body = httpClient.post(); } catch (HttpClientException e) { Debug.logWarning(e, module); return ServiceUtil.returnError("Error getting content: " + e.toString()); } sendMailContext.put("body", body); Map<String, Object> sendMailResult; try { sendMailResult = dispatcher.runSync("sendMail", sendMailContext); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } // just return the same result; it contains all necessary information return sendMailResult; } /** * JavaMail Service that gets body content from a Screen Widget * defined in the product store record and if available as attachment also. *@param dctx The DispatchContext that this service is operating in *@param rServiceContext Map containing the input parameters *@return Map with the result of the service, the output parameters */ public static Map<String, Object> sendMailFromScreen(DispatchContext dctx, Map<String, ? extends Object> rServiceContext) { Map<String, Object> serviceContext = UtilMisc.makeMapWritable(rServiceContext); LocalDispatcher dispatcher = dctx.getDispatcher(); String webSiteId = (String) serviceContext.remove("webSiteId"); String bodyText = (String) serviceContext.remove("bodyText"); String bodyScreenUri = (String) serviceContext.remove("bodyScreenUri"); String xslfoAttachScreenLocation = (String) serviceContext.remove("xslfoAttachScreenLocation"); String attachmentName = (String) serviceContext.remove("attachmentName"); Locale locale = (Locale) serviceContext.get("locale"); Map<String, Object> bodyParameters = UtilGenerics.checkMap(serviceContext.remove("bodyParameters")); if (bodyParameters == null) { bodyParameters = MapStack.create(); } if (!bodyParameters.containsKey("locale")) { bodyParameters.put("locale", locale); } else { locale = (Locale) bodyParameters.get("locale"); } String partyId = (String) serviceContext.get("partyId"); if (partyId == null) { partyId = (String) bodyParameters.get("partyId"); } String orderId = (String) bodyParameters.get("orderId"); bodyParameters.put("communicationEventId", serviceContext.get("communicationEventId")); NotificationServices.setBaseUrl(dctx.getDelegator(), webSiteId, bodyParameters); String contentType = (String) serviceContext.remove("contentType"); if (UtilValidate.isEmpty(attachmentName)) { attachmentName = "Details.pdf"; } StringWriter bodyWriter = new StringWriter(); MapStack<String> screenContext = MapStack.create(); screenContext.put("locale", locale); ScreenRenderer screens = new ScreenRenderer(bodyWriter, screenContext, htmlScreenRenderer); screens.populateContextForService(dctx, bodyParameters); screenContext.putAll(bodyParameters); if (bodyScreenUri != null) { try { screens.render(bodyScreenUri); } catch (GeneralException e) { String errMsg = "Error rendering screen for email: " + e.toString(); Debug.logError(e, errMsg, module); return ServiceUtil.returnError(errMsg); } catch (IOException e) { String errMsg = "Error rendering screen for email: " + e.toString(); Debug.logError(e, errMsg, module); return ServiceUtil.returnError(errMsg); } catch (SAXException e) { String errMsg = "Error rendering screen for email: " + e.toString(); Debug.logError(e, errMsg, module); return ServiceUtil.returnError(errMsg); } catch (ParserConfigurationException e) { String errMsg = "Error rendering screen for email: " + e.toString(); Debug.logError(e, errMsg, module); return ServiceUtil.returnError(errMsg); } } boolean isMultiPart = false; // check if attachment screen location passed in if (UtilValidate.isNotEmpty(xslfoAttachScreenLocation)) { isMultiPart = true; // start processing fo pdf attachment try { Writer writer = new StringWriter(); MapStack<String> screenContextAtt = MapStack.create(); // substitute the freemarker variables... ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContext, foScreenRenderer); screensAtt.populateContextForService(dctx, bodyParameters); screenContextAtt.putAll(bodyParameters); screensAtt.render(xslfoAttachScreenLocation); /* try { // save generated fo file for debugging String buf = writer.toString(); java.io.FileWriter fw = new java.io.FileWriter(new java.io.File("/tmp/file1.xml")); fw.write(buf.toString()); fw.close(); } catch (IOException e) { Debug.logError(e, "Couldn't save xsl-fo xml debug file: " + e.toString(), module); } */ // create the input stream for the generation StreamSource src = new StreamSource(new StringReader(writer.toString())); // create the output stream for the generation ByteArrayOutputStream baos = new ByteArrayOutputStream(); Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF); ApacheFopWorker.transform(src, null, fop); // and generate the PDF baos.flush(); baos.close(); // store in the list of maps for sendmail.... List<Map<String, ? extends Object>> bodyParts = FastList.newInstance(); if (bodyText != null) { bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale); bodyParts.add(UtilMisc.<String, Object>toMap("content", bodyText, "type", "text/html")); } else { bodyParts.add(UtilMisc.<String, Object>toMap("content", bodyWriter.toString(), "type", "text/html")); } bodyParts.add(UtilMisc.<String, Object>toMap("content", baos.toByteArray(), "type", "application/pdf", "filename", attachmentName)); serviceContext.put("bodyParts", bodyParts); } catch (GeneralException ge) { String errMsg = "Error rendering PDF attachment for email: " + ge.toString(); Debug.logError(ge, errMsg, module); return ServiceUtil.returnError(errMsg); } catch (IOException ie) { String errMsg = "Error rendering PDF attachment for email: " + ie.toString(); Debug.logError(ie, errMsg, module); return ServiceUtil.returnError(errMsg); } catch (FOPException fe) { String errMsg = "Error rendering PDF attachment for email: " + fe.toString(); Debug.logError(fe, errMsg, module); return ServiceUtil.returnError(errMsg); } catch (SAXException se) { String errMsg = "Error rendering PDF attachment for email: " + se.toString(); Debug.logError(se, errMsg, module); return ServiceUtil.returnError(errMsg); } catch (ParserConfigurationException pe) { String errMsg = "Error rendering PDF attachment for email: " + pe.toString(); Debug.logError(pe, errMsg, module); return ServiceUtil.returnError(errMsg); } } else { isMultiPart = false; // store body and type for single part message in the context. if (bodyText != null) { bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale); serviceContext.put("body", bodyText); } else { serviceContext.put("body", bodyWriter.toString()); } // Only override the default contentType in case of plaintext, since other contentTypes may be multipart // and would require specific handling. if (contentType != null && contentType.equalsIgnoreCase("text/plain")) { serviceContext.put("contentType", "text/plain"); } else { serviceContext.put("contentType", "text/html"); } } // also expand the subject at this point, just in case it has the FlexibleStringExpander syntax in it... String subject = (String) serviceContext.remove("subject"); subject = FlexibleStringExpander.expandString(subject, screenContext, locale); Debug.logInfo("Expanded email subject to: " + subject, module); serviceContext.put("subject", subject); serviceContext.put("partyId", partyId); if (UtilValidate.isNotEmpty(orderId)) { serviceContext.put("orderId", orderId); } if (Debug.verboseOn()) Debug.logVerbose("sendMailFromScreen sendMail context: " + serviceContext, module); Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, Object> sendMailResult; try { if (isMultiPart) { sendMailResult = dispatcher.runSync("sendMailMultiPart", serviceContext); } else { sendMailResult = dispatcher.runSync("sendMail", serviceContext); } } catch (Exception e) { String errMsg = "Error send email :" + e.toString(); Debug.logError(e, errMsg, module); return ServiceUtil.returnError(errMsg); } if (ServiceUtil.isError(sendMailResult)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(sendMailResult)); } result.put("messageWrapper", sendMailResult.get("messageWrapper")); result.put("body", bodyWriter.toString()); result.put("subject", subject); if (UtilValidate.isNotEmpty(orderId)) { result.put("orderId", orderId); } return result; } public static void sendFailureNotification(DispatchContext dctx, Map<String, ? extends Object> context, MimeMessage message, List<SMTPAddressFailedException> failures) { Map<String, Object> newContext = FastMap.newInstance(); newContext.put("userLogin", context.get("userLogin")); newContext.put("sendFailureNotification", false); newContext.put("sendFrom", context.get("sendFrom")); newContext.put("sendTo", context.get("sendFrom")); newContext.put("subject", "Undelivered Mail Returned to Sender"); StringBuilder sb = new StringBuilder(); sb.append("Delivery to the following recipient(s) failed:\n\n"); for (SMTPAddressFailedException failure : failures) { sb.append(failure.getAddress()); sb.append(": "); sb.append(failure.getMessage()); sb.append("/n/n"); } sb.append("----- Original message -----/n/n"); List<Map<String, Object>> bodyParts = FastList.newInstance(); bodyParts.add(UtilMisc.<String, Object>toMap("content", sb.toString(), "type", "text/plain")); Map<String, Object> bodyPart = FastMap.newInstance(); bodyPart.put("content", sb.toString()); bodyPart.put("type", "text/plain"); try { bodyParts.add(UtilMisc.<String, Object>toMap("content", message.getDataHandler())); } catch (MessagingException e) { Debug.logError(e, module); } try { dctx.getDispatcher().runSync("sendMailMultiPart", newContext); } catch (GenericServiceException e) { Debug.logError(e, module); } } /** class to create a file in memory required for sending as an attachment */ public static class StringDataSource implements DataSource { private String contentType; private ByteArrayOutputStream contentArray; public StringDataSource(String content, String contentType) throws IOException { this.contentType = contentType; contentArray = new ByteArrayOutputStream(); contentArray.write(content.getBytes("iso-8859-1")); contentArray.flush(); contentArray.close(); } public String getContentType() { return contentType == null ? "application/octet-stream" : contentType; } public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(contentArray.toByteArray()); } public String getName() { return "stringDatasource"; } public OutputStream getOutputStream() throws IOException { throw new IOException("Cannot write to this read-only resource"); } } /** class to create a file in memory required for sending as an attachment */ public static class ByteArrayDataSource implements DataSource { private String contentType; private byte[] contentArray; public ByteArrayDataSource(byte[] content, String contentType) throws IOException { this.contentType = contentType; this.contentArray = content; } public String getContentType() { return contentType == null ? "application/octet-stream" : contentType; } public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(contentArray); } public String getName() { return "ByteArrayDataSource"; } public OutputStream getOutputStream() throws IOException { throw new IOException("Cannot write to this read-only resource"); } } }
true
true
public static Map<String, Object> sendMail(DispatchContext ctx, Map<String, ? extends Object> context) { String communicationEventId = (String) context.get("communicationEventId"); String orderId = (String) context.get("orderId"); if (communicationEventId != null) { Debug.logInfo("SendMail Running, for communicationEventId : " + communicationEventId, module); } Map<String, Object> results = ServiceUtil.returnSuccess(); String subject = (String) context.get("subject"); subject = FlexibleStringExpander.expandString(subject, context); String partyId = (String) context.get("partyId"); String body = (String) context.get("body"); List<Map<String, Object>> bodyParts = UtilGenerics.checkList(context.get("bodyParts")); GenericValue userLogin = (GenericValue) context.get("userLogin"); results.put("communicationEventId", communicationEventId); results.put("partyId", partyId); results.put("subject", subject); if (UtilValidate.isNotEmpty(orderId)) { results.put("orderId", orderId); } if (UtilValidate.isNotEmpty(body)) { body = FlexibleStringExpander.expandString(body, context); results.put("body", body); } if (UtilValidate.isNotEmpty(bodyParts)) { results.put("bodyParts", bodyParts); } results.put("userLogin", userLogin); String sendTo = (String) context.get("sendTo"); String sendCc = (String) context.get("sendCc"); String sendBcc = (String) context.get("sendBcc"); // check to see if we should redirect all mail for testing String redirectAddress = UtilProperties.getPropertyValue("general.properties", "mail.notifications.redirectTo"); if (UtilValidate.isNotEmpty(redirectAddress)) { String originalRecipients = " [To: " + sendTo + ", Cc: " + sendCc + ", Bcc: " + sendBcc + "]"; subject += originalRecipients; sendTo = redirectAddress; sendCc = null; sendBcc = null; } String sendFrom = (String) context.get("sendFrom"); String sendType = (String) context.get("sendType"); String port = (String) context.get("port"); String socketFactoryClass = (String) context.get("socketFactoryClass"); String socketFactoryPort = (String) context.get("socketFactoryPort"); String socketFactoryFallback = (String) context.get("socketFactoryFallback"); String sendVia = (String) context.get("sendVia"); String authUser = (String) context.get("authUser"); String authPass = (String) context.get("authPass"); String messageId = (String) context.get("messageId"); String contentType = (String) context.get("contentType"); Boolean sendPartial = (Boolean) context.get("sendPartial"); boolean useSmtpAuth = false; // define some default if (sendType == null || sendType.equals("mail.smtp.host")) { sendType = "mail.smtp.host"; if (UtilValidate.isEmpty(sendVia)) { sendVia = UtilProperties.getPropertyValue("general.properties", "mail.smtp.relay.host", "localhost"); } if (UtilValidate.isEmpty(authUser)) { authUser = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.user"); } if (UtilValidate.isEmpty(authPass)) { authPass = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.password"); } if (UtilValidate.isNotEmpty(authUser)) { useSmtpAuth = true; } if (UtilValidate.isEmpty(port)) { port = UtilProperties.getPropertyValue("general.properties", "mail.smtp.port"); } if (UtilValidate.isEmpty(socketFactoryPort)) { socketFactoryPort = UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.port"); } if (UtilValidate.isEmpty(socketFactoryClass)) { socketFactoryClass = UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.class"); } if (UtilValidate.isEmpty(socketFactoryFallback)) { socketFactoryFallback = UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.fallback", "false"); } if (sendPartial == null) { sendPartial = UtilProperties.propertyValueEqualsIgnoreCase("general.properties", "mail.smtp.sendpartial", "true") ? true : false; } } else if (sendVia == null) { return ServiceUtil.returnError("Parameter sendVia is required when sendType is not mail.smtp.host"); } if (contentType == null) { contentType = "text/html"; } if (UtilValidate.isNotEmpty(bodyParts)) { contentType = "multipart/mixed"; } results.put("contentType", contentType); Session session; MimeMessage mail; try { Properties props = System.getProperties(); props.put(sendType, sendVia); if (UtilValidate.isNotEmpty(port)) { props.put("mail.smtp.port", port); } if (UtilValidate.isNotEmpty(socketFactoryPort)) { props.put("mail.smtp.socketFactory.port", socketFactoryPort); } if (UtilValidate.isNotEmpty(socketFactoryClass)) { props.put("mail.smtp.socketFactory.class", socketFactoryClass); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); } if (UtilValidate.isNotEmpty(socketFactoryFallback)) { props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback); } if (useSmtpAuth) { props.put("mail.smtp.auth", "true"); } if (sendPartial != null) { props.put("mail.smtp.sendpartial", sendPartial ? "true" : "false"); } session = Session.getInstance(props); boolean debug = UtilProperties.propertyValueEqualsIgnoreCase("general.properties", "mail.debug.on", "Y"); session.setDebug(debug); mail = new MimeMessage(session); if (messageId != null) { mail.setHeader("In-Reply-To", messageId); mail.setHeader("References", messageId); } mail.setFrom(new InternetAddress(sendFrom)); mail.setSubject(subject, "UTF-8"); mail.setHeader("X-Mailer", "Apache OFBiz, The Apache Open For Business Project"); mail.setSentDate(new Date()); mail.addRecipients(Message.RecipientType.TO, sendTo); if (UtilValidate.isNotEmpty(sendCc)) { mail.addRecipients(Message.RecipientType.CC, sendCc); } if (UtilValidate.isNotEmpty(sendBcc)) { mail.addRecipients(Message.RecipientType.BCC, sendBcc); } if (UtilValidate.isNotEmpty(bodyParts)) { // check for multipart message (with attachments) // BodyParts contain a list of Maps items containing content(String) and type(String) of the attachement MimeMultipart mp = new MimeMultipart(); Debug.logInfo(bodyParts.size() + " multiparts found",module); for (Map<String, Object> bodyPart: bodyParts) { Object bodyPartContent = bodyPart.get("content"); MimeBodyPart mbp = new MimeBodyPart(); if (bodyPartContent instanceof String) { Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: " + bodyPart.get("content").toString().length() , module); mbp.setText((String) bodyPartContent, "UTF-8", ((String) bodyPart.get("type")).substring(5)); } else if (bodyPartContent instanceof byte[]) { ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) bodyPartContent, (String) bodyPart.get("type")); Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: " + ((byte[]) bodyPartContent).length , module); mbp.setDataHandler(new DataHandler(bads)); } else if (bodyPartContent instanceof DataHandler) { mbp.setDataHandler((DataHandler) bodyPartContent); } else { mbp.setDataHandler(new DataHandler(bodyPartContent, (String) bodyPart.get("type"))); } String fileName = (String) bodyPart.get("filename"); if (fileName != null) { mbp.setFileName(fileName); } mp.addBodyPart(mbp); } mail.setContent(mp); mail.saveChanges(); } else { // create the singelpart message if (contentType.startsWith("text")) { mail.setText(body, "UTF-8", contentType.substring(5)); } else { mail.setContent(body, contentType); } mail.saveChanges(); } } catch (MessagingException e) { String errMsg = "MessagingException when creating message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]"; Debug.logError(e, errMsg, module); Debug.logError("Email message that could not be created to [" + sendTo + "] had context: " + context, module); return ServiceUtil.returnError(errMsg); } catch (IOException e) { String errMsg = "IOExcepton when creating message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]"; Debug.logError(e, errMsg, module); Debug.logError("Email message that could not be created to [" + sendTo + "] had context: " + context, module); return ServiceUtil.returnError(errMsg); } // check to see if sending mail is enabled String mailEnabled = UtilProperties.getPropertyValue("general.properties", "mail.notifications.enabled", "N"); if (!"Y".equalsIgnoreCase(mailEnabled)) { // no error; just return as if we already processed Debug.logImportant("Mail notifications disabled in general.properties; mail with subject [" + subject + "] not sent to addressee [" + sendTo + "]", module); Debug.logVerbose("What would have been sent, the addressee: " + sendTo + " subject: " + subject + " context: " + context, module); results.put("messageWrapper", new MimeMessageWrapper(session, mail)); return results; } Transport trans = null; try { trans = session.getTransport("smtp"); if (!useSmtpAuth) { trans.connect(); } else { trans.connect(sendVia, authUser, authPass); } trans.sendMessage(mail, mail.getAllRecipients()); results.put("messageWrapper", new MimeMessageWrapper(session, mail)); results.put("messageId", mail.getMessageID()); trans.close(); } catch (SendFailedException e) { // message code prefix may be used by calling services to determine the cause of the failure String errMsg = "[ADDRERR] Address error when sending message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]"; Debug.logError(e, errMsg, module); List<SMTPAddressFailedException> failedAddresses = FastList.newInstance(); Exception nestedException = null; while ((nestedException = e.getNextException()) != null && nestedException instanceof MessagingException) { if (nestedException instanceof SMTPAddressFailedException) { SMTPAddressFailedException safe = (SMTPAddressFailedException) nestedException; Debug.logError("Failed to send message to [" + safe.getAddress() + "], return code [" + safe.getReturnCode() + "], return message [" + safe.getMessage() + "]", errMsg); failedAddresses.add(safe); break; } } Boolean sendFailureNotification = (Boolean) context.get("sendFailureNotification"); if (sendFailureNotification == null || sendFailureNotification) { sendFailureNotification(ctx, context, mail, failedAddresses); results.put("messageWrapper", new MimeMessageWrapper(session, mail)); try { results.put("messageId", mail.getMessageID()); trans.close(); } catch (MessagingException e1) { Debug.logError(e1, module); } } else { return ServiceUtil.returnError(errMsg); } } catch (MessagingException e) { // message code prefix may be used by calling services to determine the cause of the failure String errMsg = "[CON] Connection error when sending message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]"; Debug.logError(e, errMsg, module); Debug.logError("Email message that could not be sent to [" + sendTo + "] had context: " + context, module); return ServiceUtil.returnError(errMsg); } return results; }
public static Map<String, Object> sendMail(DispatchContext ctx, Map<String, ? extends Object> context) { String communicationEventId = (String) context.get("communicationEventId"); String orderId = (String) context.get("orderId"); if (communicationEventId != null) { Debug.logInfo("SendMail Running, for communicationEventId : " + communicationEventId, module); } Map<String, Object> results = ServiceUtil.returnSuccess(); String subject = (String) context.get("subject"); subject = FlexibleStringExpander.expandString(subject, context); String partyId = (String) context.get("partyId"); String body = (String) context.get("body"); List<Map<String, Object>> bodyParts = UtilGenerics.checkList(context.get("bodyParts")); GenericValue userLogin = (GenericValue) context.get("userLogin"); results.put("communicationEventId", communicationEventId); results.put("partyId", partyId); results.put("subject", subject); if (UtilValidate.isNotEmpty(orderId)) { results.put("orderId", orderId); } if (UtilValidate.isNotEmpty(body)) { body = FlexibleStringExpander.expandString(body, context); results.put("body", body); } if (UtilValidate.isNotEmpty(bodyParts)) { results.put("bodyParts", bodyParts); } results.put("userLogin", userLogin); String sendTo = (String) context.get("sendTo"); String sendCc = (String) context.get("sendCc"); String sendBcc = (String) context.get("sendBcc"); // check to see if we should redirect all mail for testing String redirectAddress = UtilProperties.getPropertyValue("general.properties", "mail.notifications.redirectTo"); if (UtilValidate.isNotEmpty(redirectAddress)) { String originalRecipients = " [To: " + sendTo + ", Cc: " + sendCc + ", Bcc: " + sendBcc + "]"; subject += originalRecipients; sendTo = redirectAddress; sendCc = null; sendBcc = null; } String sendFrom = (String) context.get("sendFrom"); String sendType = (String) context.get("sendType"); String port = (String) context.get("port"); String socketFactoryClass = (String) context.get("socketFactoryClass"); String socketFactoryPort = (String) context.get("socketFactoryPort"); String socketFactoryFallback = (String) context.get("socketFactoryFallback"); String sendVia = (String) context.get("sendVia"); String authUser = (String) context.get("authUser"); String authPass = (String) context.get("authPass"); String messageId = (String) context.get("messageId"); String contentType = (String) context.get("contentType"); Boolean sendPartial = (Boolean) context.get("sendPartial"); boolean useSmtpAuth = false; // define some default if (sendType == null || sendType.equals("mail.smtp.host")) { sendType = "mail.smtp.host"; if (UtilValidate.isEmpty(sendVia)) { sendVia = UtilProperties.getPropertyValue("general.properties", "mail.smtp.relay.host", "localhost"); } if (UtilValidate.isEmpty(authUser)) { authUser = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.user"); } if (UtilValidate.isEmpty(authPass)) { authPass = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.password"); } if (UtilValidate.isNotEmpty(authUser)) { useSmtpAuth = true; } if (UtilValidate.isEmpty(port)) { port = UtilProperties.getPropertyValue("general.properties", "mail.smtp.port"); } if (UtilValidate.isEmpty(socketFactoryPort)) { socketFactoryPort = UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.port"); } if (UtilValidate.isEmpty(socketFactoryClass)) { socketFactoryClass = UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.class"); } if (UtilValidate.isEmpty(socketFactoryFallback)) { socketFactoryFallback = UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.fallback", "false"); } if (sendPartial == null) { sendPartial = UtilProperties.propertyValueEqualsIgnoreCase("general.properties", "mail.smtp.sendpartial", "true") ? true : false; } } else if (sendVia == null) { return ServiceUtil.returnError("Parameter sendVia is required when sendType is not mail.smtp.host"); } if (contentType == null) { contentType = "text/html"; } if (UtilValidate.isNotEmpty(bodyParts)) { contentType = "multipart/mixed"; } results.put("contentType", contentType); Session session; MimeMessage mail; try { Properties props = System.getProperties(); props.put(sendType, sendVia); if (UtilValidate.isNotEmpty(port)) { props.put("mail.smtp.port", port); } if (UtilValidate.isNotEmpty(socketFactoryPort)) { props.put("mail.smtp.socketFactory.port", socketFactoryPort); } if (UtilValidate.isNotEmpty(socketFactoryClass)) { props.put("mail.smtp.socketFactory.class", socketFactoryClass); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); } if (UtilValidate.isNotEmpty(socketFactoryFallback)) { props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback); } if (useSmtpAuth) { props.put("mail.smtp.auth", "true"); } if (sendPartial != null) { props.put("mail.smtp.sendpartial", sendPartial ? "true" : "false"); } session = Session.getInstance(props); boolean debug = UtilProperties.propertyValueEqualsIgnoreCase("general.properties", "mail.debug.on", "Y"); session.setDebug(debug); mail = new MimeMessage(session); if (messageId != null) { mail.setHeader("In-Reply-To", messageId); mail.setHeader("References", messageId); } InternetAddress sender = new InternetAddress(sendFrom, sendFrom); mail.setFrom(sender); mail.setReplyTo(new InternetAddress[] {sender}); mail.setSubject(subject, "UTF-8"); mail.setHeader("X-Mailer", "Apache OFBiz, The Apache Open For Business Project"); mail.setSentDate(new Date()); mail.addRecipients(Message.RecipientType.TO, sendTo); if (UtilValidate.isNotEmpty(sendCc)) { mail.addRecipients(Message.RecipientType.CC, sendCc); } if (UtilValidate.isNotEmpty(sendBcc)) { mail.addRecipients(Message.RecipientType.BCC, sendBcc); } if (UtilValidate.isNotEmpty(bodyParts)) { // check for multipart message (with attachments) // BodyParts contain a list of Maps items containing content(String) and type(String) of the attachement MimeMultipart mp = new MimeMultipart(); Debug.logInfo(bodyParts.size() + " multiparts found",module); for (Map<String, Object> bodyPart: bodyParts) { Object bodyPartContent = bodyPart.get("content"); MimeBodyPart mbp = new MimeBodyPart(); if (bodyPartContent instanceof String) { Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: " + bodyPart.get("content").toString().length() , module); mbp.setText((String) bodyPartContent, "UTF-8", ((String) bodyPart.get("type")).substring(5)); } else if (bodyPartContent instanceof byte[]) { ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) bodyPartContent, (String) bodyPart.get("type")); Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: " + ((byte[]) bodyPartContent).length , module); mbp.setDataHandler(new DataHandler(bads)); } else if (bodyPartContent instanceof DataHandler) { mbp.setDataHandler((DataHandler) bodyPartContent); } else { mbp.setDataHandler(new DataHandler(bodyPartContent, (String) bodyPart.get("type"))); } String fileName = (String) bodyPart.get("filename"); if (fileName != null) { mbp.setFileName(fileName); } mp.addBodyPart(mbp); } mail.setContent(mp); mail.saveChanges(); } else { // create the singelpart message if (contentType.startsWith("text")) { mail.setText(body, "UTF-8", contentType.substring(5)); } else { mail.setContent(body, contentType); } mail.saveChanges(); } } catch (MessagingException e) { String errMsg = "MessagingException when creating message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]"; Debug.logError(e, errMsg, module); Debug.logError("Email message that could not be created to [" + sendTo + "] had context: " + context, module); return ServiceUtil.returnError(errMsg); } catch (IOException e) { String errMsg = "IOExcepton when creating message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]"; Debug.logError(e, errMsg, module); Debug.logError("Email message that could not be created to [" + sendTo + "] had context: " + context, module); return ServiceUtil.returnError(errMsg); } // check to see if sending mail is enabled String mailEnabled = UtilProperties.getPropertyValue("general.properties", "mail.notifications.enabled", "N"); if (!"Y".equalsIgnoreCase(mailEnabled)) { // no error; just return as if we already processed Debug.logImportant("Mail notifications disabled in general.properties; mail with subject [" + subject + "] not sent to addressee [" + sendTo + "]", module); Debug.logVerbose("What would have been sent, the addressee: " + sendTo + " subject: " + subject + " context: " + context, module); results.put("messageWrapper", new MimeMessageWrapper(session, mail)); return results; } Transport trans = null; try { trans = session.getTransport("smtp"); if (!useSmtpAuth) { trans.connect(); } else { trans.connect(sendVia, authUser, authPass); } trans.sendMessage(mail, mail.getAllRecipients()); results.put("messageWrapper", new MimeMessageWrapper(session, mail)); results.put("messageId", mail.getMessageID()); trans.close(); } catch (SendFailedException e) { // message code prefix may be used by calling services to determine the cause of the failure String errMsg = "[ADDRERR] Address error when sending message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]"; Debug.logError(e, errMsg, module); List<SMTPAddressFailedException> failedAddresses = FastList.newInstance(); Exception nestedException = null; while ((nestedException = e.getNextException()) != null && nestedException instanceof MessagingException) { if (nestedException instanceof SMTPAddressFailedException) { SMTPAddressFailedException safe = (SMTPAddressFailedException) nestedException; Debug.logError("Failed to send message to [" + safe.getAddress() + "], return code [" + safe.getReturnCode() + "], return message [" + safe.getMessage() + "]", errMsg); failedAddresses.add(safe); break; } } Boolean sendFailureNotification = (Boolean) context.get("sendFailureNotification"); if (sendFailureNotification == null || sendFailureNotification) { sendFailureNotification(ctx, context, mail, failedAddresses); results.put("messageWrapper", new MimeMessageWrapper(session, mail)); try { results.put("messageId", mail.getMessageID()); trans.close(); } catch (MessagingException e1) { Debug.logError(e1, module); } } else { return ServiceUtil.returnError(errMsg); } } catch (MessagingException e) { // message code prefix may be used by calling services to determine the cause of the failure String errMsg = "[CON] Connection error when sending message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]"; Debug.logError(e, errMsg, module); Debug.logError("Email message that could not be sent to [" + sendTo + "] had context: " + context, module); return ServiceUtil.returnError(errMsg); } return results; }
diff --git a/FreeTTS/com/sun/speech/freetts/en/us/cmu_us_kal/KevinVoiceDirectory.java b/FreeTTS/com/sun/speech/freetts/en/us/cmu_us_kal/KevinVoiceDirectory.java index 7b1effe..5a3199b 100644 --- a/FreeTTS/com/sun/speech/freetts/en/us/cmu_us_kal/KevinVoiceDirectory.java +++ b/FreeTTS/com/sun/speech/freetts/en/us/cmu_us_kal/KevinVoiceDirectory.java @@ -1,32 +1,32 @@ package com.sun.speech.freetts.en.us.cmu_us_kal; import com.sun.speech.freetts.en.us.CMUDiphoneVoice; import com.sun.speech.freetts.VoiceDirectory; import com.sun.speech.freetts.Voice; import com.sun.speech.freetts.Gender; import com.sun.speech.freetts.Age; import java.util.Locale; //TODO documentation public class KevinVoiceDirectory extends VoiceDirectory { public Voice[] getVoices() { //TODO different name? Voice kevin = new CMUDiphoneVoice(true, "kevin", Gender.MALE, Age.YOUNGER_ADULT, "default 8-bit diphone voice", Locale.US); Voice kevin16 = new CMUDiphoneVoice(true, "kevin16", Gender.MALE, Age.YOUNGER_ADULT, "default 16-bit diphone voice", Locale.US); kevin.getFeatures().setString(Voice.DATABASE_NAME, - "cmu_us_kal/diphone_units.bin"); + "cmu_us_kal/cmu_us_kal.bin"); kevin16.getFeatures().setString(Voice.DATABASE_NAME, - "cmu_us_kal/diphone_units16.bin"); + "cmu_us_kal/cmu_us_kal16.bin"); Voice[] voices = {kevin, kevin16}; return voices; } public static void main(String[] args) { System.out.println((new KevinVoiceDirectory()).toString()); } }
false
true
public Voice[] getVoices() { //TODO different name? Voice kevin = new CMUDiphoneVoice(true, "kevin", Gender.MALE, Age.YOUNGER_ADULT, "default 8-bit diphone voice", Locale.US); Voice kevin16 = new CMUDiphoneVoice(true, "kevin16", Gender.MALE, Age.YOUNGER_ADULT, "default 16-bit diphone voice", Locale.US); kevin.getFeatures().setString(Voice.DATABASE_NAME, "cmu_us_kal/diphone_units.bin"); kevin16.getFeatures().setString(Voice.DATABASE_NAME, "cmu_us_kal/diphone_units16.bin"); Voice[] voices = {kevin, kevin16}; return voices; }
public Voice[] getVoices() { //TODO different name? Voice kevin = new CMUDiphoneVoice(true, "kevin", Gender.MALE, Age.YOUNGER_ADULT, "default 8-bit diphone voice", Locale.US); Voice kevin16 = new CMUDiphoneVoice(true, "kevin16", Gender.MALE, Age.YOUNGER_ADULT, "default 16-bit diphone voice", Locale.US); kevin.getFeatures().setString(Voice.DATABASE_NAME, "cmu_us_kal/cmu_us_kal.bin"); kevin16.getFeatures().setString(Voice.DATABASE_NAME, "cmu_us_kal/cmu_us_kal16.bin"); Voice[] voices = {kevin, kevin16}; return voices; }
diff --git a/src/net/sourceforge/schemaspy/view/DotConnector.java b/src/net/sourceforge/schemaspy/view/DotConnector.java index ffae356..96fe8e0 100755 --- a/src/net/sourceforge/schemaspy/view/DotConnector.java +++ b/src/net/sourceforge/schemaspy/view/DotConnector.java @@ -1,175 +1,177 @@ package net.sourceforge.schemaspy.view; import net.sourceforge.schemaspy.model.Table; import net.sourceforge.schemaspy.model.TableColumn; import net.sourceforge.schemaspy.util.Dot; /** * Represents Graphvis dot's concept of an edge. That is, a connector between two nodes. * * @author John Currier */ public class DotConnector implements Comparable<DotConnector> { private final TableColumn parentColumn; private final Table parentTable; private final TableColumn childColumn; private final Table childTable; private final boolean implied; private final boolean bottomJustify; private String parentPort; private String childPort; /** * Create an edge that logically connects a child column to a parent column. * * @param parentColumn TableColumn * @param childColumn TableColumn * @param implied boolean */ public DotConnector(TableColumn parentColumn, TableColumn childColumn, boolean implied) { this.parentColumn = parentColumn; this.childColumn = childColumn; this.implied = implied; parentPort = parentColumn.getName(); parentTable = parentColumn.getTable(); childPort = childColumn.getName(); childTable = childColumn.getTable(); bottomJustify = !Dot.getInstance().supportsCenteredEastWestEdges(); } /** * Returns true if this edge logically "points to" the specified table * * @param possibleParentTable Table * @return boolean */ public boolean pointsTo(Table possibleParentTable) { return possibleParentTable.equals(parentTable); } public boolean isImplied() { return implied; } /** * By default a parent edge connects to the column name...this lets you * connect it the parent's type column instead (e.g. for detailed parents) * * Yes, I need to find a more appropriate name/metaphor for this method.... */ public void connectToParentDetails() { parentPort = parentColumn.getName() + ".type"; } public void connectToParentTitle() { //parentPort = parentColumn.getTable().getName() + ".heading"; parentPort = "elipses"; } public void connectToChildTitle() { //childPort = childColumn.getTable().getName() + ".heading"; childPort = "elipses"; } @Override public String toString() { StringBuilder edge = new StringBuilder(); edge.append(" \""); if (childTable.isRemote()) { edge.append(childTable.getSchema()); edge.append('.'); } edge.append(childTable.getName()); edge.append("\":\""); edge.append(childPort); edge.append("\":"); if (bottomJustify) edge.append("s"); edge.append("w -> \""); if (parentTable.isRemote()) { edge.append(parentTable.getSchema()); edge.append('.'); } edge.append(parentTable.getName()); edge.append("\":\""); edge.append(parentPort); edge.append("\":"); if (bottomJustify) edge.append("s"); edge.append("e "); // if enabled makes the diagram unreadable // have to figure out how to render these details in a readable manner final boolean fullErNotation = false; // Thanks to Dan Zingaro for figuring out how to correctly annotate // these relationships if (fullErNotation) { // PK end of connector edge.append("[arrowhead="); if (childColumn.isNullable()) edge.append("odottee"); // zero or one parents else edge.append("teetee"); // one parent + edge.append(" dir=both"); } else { // PK end of connector edge.append("[arrowhead=none"); + edge.append(" dir=back"); } // FK end of connector edge.append(" arrowtail="); if (childColumn.isUnique()) edge.append("teeodot"); // zero or one children else edge.append("crowodot");// zero or more children if (implied) edge.append(" style=dashed"); edge.append("];"); return edge.toString(); } public int compareTo(DotConnector other) { int rc = childTable.compareTo(other.childTable); if (rc == 0) rc = childColumn.getName().compareToIgnoreCase(other.childColumn.getName()); if (rc == 0) rc = parentTable.compareTo(other.parentTable); if (rc == 0) rc = parentColumn.getName().compareToIgnoreCase(other.parentColumn.getName()); if (rc == 0 && implied != other.implied) rc = implied ? 1 : -1; return rc; } @Override public boolean equals(Object other) { if (!(other instanceof DotConnector)) return false; return compareTo((DotConnector)other) == 0; } @Override public int hashCode() { int p = parentTable == null ? 0 : parentTable.getName().hashCode(); int c = childTable == null ? 0 : childTable.getName().hashCode(); return (p << 16) & c; } public TableColumn getParentColumn() { return parentColumn; } public Table getParentTable() { return parentTable; } public TableColumn getChildColumn() { return childColumn; } public Table getChildTable() { return childTable; } }
false
true
public String toString() { StringBuilder edge = new StringBuilder(); edge.append(" \""); if (childTable.isRemote()) { edge.append(childTable.getSchema()); edge.append('.'); } edge.append(childTable.getName()); edge.append("\":\""); edge.append(childPort); edge.append("\":"); if (bottomJustify) edge.append("s"); edge.append("w -> \""); if (parentTable.isRemote()) { edge.append(parentTable.getSchema()); edge.append('.'); } edge.append(parentTable.getName()); edge.append("\":\""); edge.append(parentPort); edge.append("\":"); if (bottomJustify) edge.append("s"); edge.append("e "); // if enabled makes the diagram unreadable // have to figure out how to render these details in a readable manner final boolean fullErNotation = false; // Thanks to Dan Zingaro for figuring out how to correctly annotate // these relationships if (fullErNotation) { // PK end of connector edge.append("[arrowhead="); if (childColumn.isNullable()) edge.append("odottee"); // zero or one parents else edge.append("teetee"); // one parent } else { // PK end of connector edge.append("[arrowhead=none"); } // FK end of connector edge.append(" arrowtail="); if (childColumn.isUnique()) edge.append("teeodot"); // zero or one children else edge.append("crowodot");// zero or more children if (implied) edge.append(" style=dashed"); edge.append("];"); return edge.toString(); }
public String toString() { StringBuilder edge = new StringBuilder(); edge.append(" \""); if (childTable.isRemote()) { edge.append(childTable.getSchema()); edge.append('.'); } edge.append(childTable.getName()); edge.append("\":\""); edge.append(childPort); edge.append("\":"); if (bottomJustify) edge.append("s"); edge.append("w -> \""); if (parentTable.isRemote()) { edge.append(parentTable.getSchema()); edge.append('.'); } edge.append(parentTable.getName()); edge.append("\":\""); edge.append(parentPort); edge.append("\":"); if (bottomJustify) edge.append("s"); edge.append("e "); // if enabled makes the diagram unreadable // have to figure out how to render these details in a readable manner final boolean fullErNotation = false; // Thanks to Dan Zingaro for figuring out how to correctly annotate // these relationships if (fullErNotation) { // PK end of connector edge.append("[arrowhead="); if (childColumn.isNullable()) edge.append("odottee"); // zero or one parents else edge.append("teetee"); // one parent edge.append(" dir=both"); } else { // PK end of connector edge.append("[arrowhead=none"); edge.append(" dir=back"); } // FK end of connector edge.append(" arrowtail="); if (childColumn.isUnique()) edge.append("teeodot"); // zero or one children else edge.append("crowodot");// zero or more children if (implied) edge.append(" style=dashed"); edge.append("];"); return edge.toString(); }
diff --git a/me/ChrizC/lockbuy/LBBlockListener.java b/me/ChrizC/lockbuy/LBBlockListener.java index 95ed704..c134a1d 100644 --- a/me/ChrizC/lockbuy/LBBlockListener.java +++ b/me/ChrizC/lockbuy/LBBlockListener.java @@ -1,142 +1,142 @@ package me.ChrizC.lockbuy; import org.bukkit.event.block.BlockListener; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.World; import org.bukkit.block.BlockState; import org.bukkit.block.Sign; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.ChatColor; import org.bukkit.Material; import java.util.regex.Pattern; import java.util.regex.Matcher; public class LBBlockListener extends BlockListener { private LockBuy plugin; //Initiate variables Sign sign; Sign locketteSign; World world; Player player; Pattern p = Pattern.compile("([-+]?[0-9]\\d{0,2}(\\.\\d{1,2})?%?)"); boolean signFound; //Initiate chat prefix. public static final String ERR_PREFIX = ChatColor.RED + "[LockBuy] "; public LBBlockListener(LockBuy instance) { plugin = instance; } @Override public void onSignChange(SignChangeEvent event) { sign = (Sign) event.getBlock().getState(); world = event.getBlock().getWorld(); player = event.getPlayer(); signFound = false; //Is this sign one that we're looking for? if (event.getLine(0).equals("[LockBuy]")) { //Yes, it is! BlockFace[] array = new BlockFace[]{BlockFace.UP, BlockFace.DOWN, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}; //Let's check every adjacent block, and see if we're next to a Lockette sign. for (BlockFace face : array) { BlockState state = sign.getBlock().getFace(face).getState(); if (state instanceof Sign) { Sign temp = (Sign) state; if (temp.getLine(0).equalsIgnoreCase("[Private]")) { locketteSign = temp; signFound = true; } } } //Are we next to a Lockette sign? if (signFound == true) { //Yes, we are! //Are we making a sign for ourselves? if (!locketteSign.getLine(1).equals(player.getName())) { //Does the player have permission to do this? if (plugin.permissionsCheck(player, "lockbuy.admin.place", true) == true) { //Yes, he does! //Has the player provided a feasible number? Matcher m = p.matcher(event.getLine(1)); if (m.find() == true) { //Yes. //Is number negative? - if (Integer.parseInt(m.group()) > 0) { + if (Double.parseDouble(m.group()) > 0) { //No. event.setLine(3, ChatColor.GREEN + "[Active]"); } else { //Yes. player.sendMessage(ERR_PREFIX + "You cannot define a negative value, or 0."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //No. player.sendMessage(ERR_PREFIX + "You must define a proper price."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //No, he doesn't! player.sendMessage(ERR_PREFIX + "Error! You do not have the correct Permission to place this sign."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //Does the player have permission to do this? if (plugin.permissionsCheck(player, "lockbuy.user.place", false) == true || plugin.permissionsCheck(player, "lockbuy.admin.place", true) == true) { //Yes, he does! //Has the player provided a feasible number? Matcher m = p.matcher(event.getLine(1)); if (m.find() == true) { //Yes. //Is number negative? - if (Integer.parseInt(m.group()) > 0) { + if (Double.parseDouble(m.group()) > 0) { //No. event.setLine(3, ChatColor.GREEN + "[Active]"); } else { //Yes. player.sendMessage(ERR_PREFIX + "You cannot define a negative value, or 0."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //No. player.sendMessage(ERR_PREFIX + "You must define a proper price."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //No, he doesn't! player.sendMessage(ERR_PREFIX + "Error! You do not have the correct Permission to place this sign."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } } else { //No, we're not! player.sendMessage(ERR_PREFIX + "Error! No Lockette sign found!"); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } } }
false
true
public void onSignChange(SignChangeEvent event) { sign = (Sign) event.getBlock().getState(); world = event.getBlock().getWorld(); player = event.getPlayer(); signFound = false; //Is this sign one that we're looking for? if (event.getLine(0).equals("[LockBuy]")) { //Yes, it is! BlockFace[] array = new BlockFace[]{BlockFace.UP, BlockFace.DOWN, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}; //Let's check every adjacent block, and see if we're next to a Lockette sign. for (BlockFace face : array) { BlockState state = sign.getBlock().getFace(face).getState(); if (state instanceof Sign) { Sign temp = (Sign) state; if (temp.getLine(0).equalsIgnoreCase("[Private]")) { locketteSign = temp; signFound = true; } } } //Are we next to a Lockette sign? if (signFound == true) { //Yes, we are! //Are we making a sign for ourselves? if (!locketteSign.getLine(1).equals(player.getName())) { //Does the player have permission to do this? if (plugin.permissionsCheck(player, "lockbuy.admin.place", true) == true) { //Yes, he does! //Has the player provided a feasible number? Matcher m = p.matcher(event.getLine(1)); if (m.find() == true) { //Yes. //Is number negative? if (Integer.parseInt(m.group()) > 0) { //No. event.setLine(3, ChatColor.GREEN + "[Active]"); } else { //Yes. player.sendMessage(ERR_PREFIX + "You cannot define a negative value, or 0."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //No. player.sendMessage(ERR_PREFIX + "You must define a proper price."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //No, he doesn't! player.sendMessage(ERR_PREFIX + "Error! You do not have the correct Permission to place this sign."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //Does the player have permission to do this? if (plugin.permissionsCheck(player, "lockbuy.user.place", false) == true || plugin.permissionsCheck(player, "lockbuy.admin.place", true) == true) { //Yes, he does! //Has the player provided a feasible number? Matcher m = p.matcher(event.getLine(1)); if (m.find() == true) { //Yes. //Is number negative? if (Integer.parseInt(m.group()) > 0) { //No. event.setLine(3, ChatColor.GREEN + "[Active]"); } else { //Yes. player.sendMessage(ERR_PREFIX + "You cannot define a negative value, or 0."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //No. player.sendMessage(ERR_PREFIX + "You must define a proper price."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //No, he doesn't! player.sendMessage(ERR_PREFIX + "Error! You do not have the correct Permission to place this sign."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } } else { //No, we're not! player.sendMessage(ERR_PREFIX + "Error! No Lockette sign found!"); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } }
public void onSignChange(SignChangeEvent event) { sign = (Sign) event.getBlock().getState(); world = event.getBlock().getWorld(); player = event.getPlayer(); signFound = false; //Is this sign one that we're looking for? if (event.getLine(0).equals("[LockBuy]")) { //Yes, it is! BlockFace[] array = new BlockFace[]{BlockFace.UP, BlockFace.DOWN, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}; //Let's check every adjacent block, and see if we're next to a Lockette sign. for (BlockFace face : array) { BlockState state = sign.getBlock().getFace(face).getState(); if (state instanceof Sign) { Sign temp = (Sign) state; if (temp.getLine(0).equalsIgnoreCase("[Private]")) { locketteSign = temp; signFound = true; } } } //Are we next to a Lockette sign? if (signFound == true) { //Yes, we are! //Are we making a sign for ourselves? if (!locketteSign.getLine(1).equals(player.getName())) { //Does the player have permission to do this? if (plugin.permissionsCheck(player, "lockbuy.admin.place", true) == true) { //Yes, he does! //Has the player provided a feasible number? Matcher m = p.matcher(event.getLine(1)); if (m.find() == true) { //Yes. //Is number negative? if (Double.parseDouble(m.group()) > 0) { //No. event.setLine(3, ChatColor.GREEN + "[Active]"); } else { //Yes. player.sendMessage(ERR_PREFIX + "You cannot define a negative value, or 0."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //No. player.sendMessage(ERR_PREFIX + "You must define a proper price."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //No, he doesn't! player.sendMessage(ERR_PREFIX + "Error! You do not have the correct Permission to place this sign."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //Does the player have permission to do this? if (plugin.permissionsCheck(player, "lockbuy.user.place", false) == true || plugin.permissionsCheck(player, "lockbuy.admin.place", true) == true) { //Yes, he does! //Has the player provided a feasible number? Matcher m = p.matcher(event.getLine(1)); if (m.find() == true) { //Yes. //Is number negative? if (Double.parseDouble(m.group()) > 0) { //No. event.setLine(3, ChatColor.GREEN + "[Active]"); } else { //Yes. player.sendMessage(ERR_PREFIX + "You cannot define a negative value, or 0."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //No. player.sendMessage(ERR_PREFIX + "You must define a proper price."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } else { //No, he doesn't! player.sendMessage(ERR_PREFIX + "Error! You do not have the correct Permission to place this sign."); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } } else { //No, we're not! player.sendMessage(ERR_PREFIX + "Error! No Lockette sign found!"); sign.getBlock().setType(Material.AIR); player.getInventory().addItem(new ItemStack(Material.SIGN, 1)); } } }
diff --git a/main/src/main/java/com/bloatit/web/linkable/features/FeatureSummaryComponent.java b/main/src/main/java/com/bloatit/web/linkable/features/FeatureSummaryComponent.java index e66f13733..30e093567 100644 --- a/main/src/main/java/com/bloatit/web/linkable/features/FeatureSummaryComponent.java +++ b/main/src/main/java/com/bloatit/web/linkable/features/FeatureSummaryComponent.java @@ -1,660 +1,660 @@ /* * Copyright (C) 2010 BloatIt. This file is part of BloatIt. BloatIt 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. * BloatIt 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 BloatIt. If not, see <http://www.gnu.org/licenses/>. */ package com.bloatit.web.linkable.features; import static com.bloatit.framework.webprocessor.context.Context.tr; import static com.bloatit.framework.webprocessor.context.Context.trn; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.bloatit.data.DaoBug.Level; import com.bloatit.framework.exceptions.highlevel.ShallNotPassException; import com.bloatit.framework.utils.PageIterable; import com.bloatit.framework.utils.datetime.DateUtils; import com.bloatit.framework.utils.datetime.TimeRenderer; import com.bloatit.framework.utils.i18n.CurrencyLocale; import com.bloatit.framework.utils.i18n.DateLocale.FormatStyle; import com.bloatit.framework.webprocessor.components.HtmlDiv; import com.bloatit.framework.webprocessor.components.HtmlGenericElement; import com.bloatit.framework.webprocessor.components.HtmlImage; import com.bloatit.framework.webprocessor.components.HtmlLink; import com.bloatit.framework.webprocessor.components.HtmlParagraph; import com.bloatit.framework.webprocessor.components.HtmlSpan; import com.bloatit.framework.webprocessor.components.HtmlTitle; import com.bloatit.framework.webprocessor.components.PlaceHolderElement; import com.bloatit.framework.webprocessor.components.advanced.HtmlScript; import com.bloatit.framework.webprocessor.components.javascript.JsShowHide; import com.bloatit.framework.webprocessor.components.meta.HtmlBranch; import com.bloatit.framework.webprocessor.components.meta.HtmlMixedText; import com.bloatit.framework.webprocessor.components.meta.HtmlNode; import com.bloatit.framework.webprocessor.context.Context; import com.bloatit.model.Actor; import com.bloatit.model.Bug; import com.bloatit.model.Feature; import com.bloatit.model.Image; import com.bloatit.model.Milestone; import com.bloatit.model.Offer; import com.bloatit.model.Release; import com.bloatit.model.right.AuthToken; import com.bloatit.model.right.UnauthorizedOperationException; import com.bloatit.web.HtmlTools; import com.bloatit.web.components.HtmlAuthorLink; import com.bloatit.web.linkable.master.HtmlPageComponent; import com.bloatit.web.linkable.members.MembersTools; import com.bloatit.web.linkable.softwares.SoftwaresTools; import com.bloatit.web.url.ContributionProcessUrl; import com.bloatit.web.url.CreateReleasePageUrl; import com.bloatit.web.url.FeatureModerationPageUrl; import com.bloatit.web.url.FeaturePageAliasUrl; import com.bloatit.web.url.MakeOfferPageUrl; import com.bloatit.web.url.PopularityVoteActionUrl; import com.bloatit.web.url.ReleasePageUrl; import com.bloatit.web.url.ReportBugPageUrl; public final class FeatureSummaryComponent extends HtmlPageComponent { private final Feature feature; protected FeatureSummaryComponent(final Feature feature) { super(); this.feature = feature; try { // //////////////////// // Div feature_summary final HtmlDiv featureSummary = new HtmlDiv("feature_summary"); { // //////////////////// // Div feature_summary_top final HtmlDiv featureSummaryTop = new HtmlDiv("feature_summary_top"); { // //////////////////// // Div feature_summary_left final HtmlDiv featureSummaryLeft = new HtmlDiv("feature_summary_left"); { featureSummaryLeft.add(new SoftwaresTools.Logo(feature.getSoftware())); } featureSummaryTop.add(featureSummaryLeft); // //////////////////// // Div feature_summary_center final HtmlDiv featureSummaryCenter = new HtmlDiv("feature_summary_center"); { // Try to display the title final HtmlTitle title = new HtmlTitle(1); title.setCssClass("feature_title"); if (feature.hasSoftware()) { title.add(new SoftwaresTools.Link(feature.getSoftware())); title.addText(" – "); } title.addText(FeaturesTools.getTitle(feature)); featureSummaryCenter.add(title); } featureSummaryTop.add(featureSummaryCenter); } featureSummary.add(featureSummaryTop); // final JsShowHide shareBlockShowHide = new JsShowHide(false); // //////////////////// // Div feature_summary_bottom final HtmlDiv featureSummaryBottom = new HtmlDiv("feature_summary_bottom"); { // //////////////////// // Div feature_summary_popularity final HtmlDiv featureSummaryPopularity = new HtmlDiv("feature_summary_popularity"); { final HtmlParagraph popularityText = new HtmlParagraph(Context.tr("Popularity"), "feature_popularity_text"); final HtmlParagraph popularityScore = new HtmlParagraph(HtmlTools.compressKarma(feature.getPopularity()), "feature_popularity_score"); featureSummaryPopularity.add(popularityText); featureSummaryPopularity.add(popularityScore); if (!feature.getRights().isOwner()) { final int vote = feature.getUserVoteValue(); if (vote == 0) { final HtmlDiv featurePopularityJudge = new HtmlDiv("feature_popularity_judge"); { - if (feature.canVoteUp().isEmpty()) { + if (!AuthToken.isAuthenticated() || feature.canVoteUp().isEmpty()) { final PopularityVoteActionUrl usefulUrl = new PopularityVoteActionUrl(Context.getSession().getShortKey(), feature, true); final HtmlLink usefulLink = usefulUrl.getHtmlLink("+"); usefulLink.setCssClass("useful"); featurePopularityJudge.add(usefulLink); } - if (feature.canVoteDown().isEmpty()) { + if (!AuthToken.isAuthenticated() || feature.canVoteDown().isEmpty()) { final PopularityVoteActionUrl uselessUrl = new PopularityVoteActionUrl(Context.getSession().getShortKey(), feature, false); final HtmlLink uselessLink = uselessUrl.getHtmlLink("−"); uselessLink.setCssClass("useless"); featurePopularityJudge.add(uselessLink); } } featureSummaryPopularity.add(featurePopularityJudge); } else { // Already voted final HtmlDiv featurePopularityJudged = new HtmlDiv("feature_popularity_judged"); { if (vote > 0) { featurePopularityJudged.add(new HtmlParagraph("+" + vote, "useful")); } else { featurePopularityJudged.add(new HtmlParagraph("−" + Math.abs(vote), "useless")); } } featureSummaryPopularity.add(featurePopularityJudged); } } else { final HtmlDiv featurePopularityNone = new HtmlDiv("feature_popularity_none"); featureSummaryPopularity.add(featurePopularityNone); } // Delete the feature if (AuthToken.isAuthenticated() && AuthToken.getMember().getRights().hasAdminUserPrivilege()) { featureSummaryPopularity.add(new FeatureModerationPageUrl(feature).getHtmlLink(Context.tr("Moderate"))); } } featureSummaryBottom.add(featureSummaryPopularity); HtmlDiv featureSummaryProgress; featureSummaryProgress = generateProgressBlock(feature, FeaturesTools.FeatureContext.FEATURE_PAGE); featureSummaryBottom.add(featureSummaryProgress); // //////////////////// // Div feature_summary_share final HtmlDiv featureSummaryShare = new HtmlDiv("feature_summary_share_button"); { // final HtmlLink showHideShareBlock = new HtmlLink("#", // Context.tr("+ Share")); // shareBlockShowHide.addActuator(showHideShareBlock); // featureSummaryShare.add(showHideShareBlock); } featureSummaryBottom.add(featureSummaryShare); } featureSummary.add(featureSummaryBottom); // //////////////////// // Div feature_summary_share final HtmlDiv feature_summary_share_external = new HtmlDiv("feature_summary_share"); featureSummary.add(feature_summary_share_external); feature_summary_share_external.add(generateIdenticaShareItem()); feature_summary_share_external.add(generateTwitterShareItem()); feature_summary_share_external.add(generateLinkedInShareItem()); feature_summary_share_external.add(generatePlusoneShareItem()); feature_summary_share_external.add(generateFacebookShareItem()); // shareBlockShowHide.addListener(feature_summary_share_external); // shareBlockShowHide.apply(); } add(featureSummary); } catch (final UnauthorizedOperationException e) { Context.getSession().notifyError(Context.tr("An error prevented us from displaying feature information. Please notify us.")); throw new ShallNotPassException("User cannot access feature information", e); } } private HtmlNode generateIdenticaShareItem() { final HtmlDiv item = new HtmlDiv("share_item"); final HtmlDiv identicaBlock = new HtmlDiv("identica"); item.add(identicaBlock); identicaBlock.addAttribute("style", "background-color: white;border: 1px solid #ddd;display:inline-block;"); final HtmlLink actionLink = new HtmlLink("javascript:(function(){var%20d=document,w=window,e=w.getSelection,k=d.getSelection,x=d.selection,s=(e?e():(k)?k():(x?x.createRange().text:0)),f='https://identi.ca//index.php?action=bookmarklet',e=encodeURIComponent,g=f+'&status_textarea=%E2%80%9C'+((e(s))?e(s):e(document.title))+'%E2%80%9D%20%E2%80%94%20" + new FeaturePageAliasUrl(feature).externalUrlString(true) + "';function%20a(){if(!w.open(g,'t','toolbar=0,resizable=0,scrollbars=1,status=1,width=450,height=200')){l.href=g;}}a();})()"); final HtmlImage backgroundImage = new HtmlImage(new Image("/resources/commons/img/share/identica.png"), "identi.ca"); backgroundImage.addAttribute("style", "border:none;"); actionLink.add(backgroundImage); identicaBlock.add(actionLink); return item; } private HtmlNode generateTwitterShareItem() { final HtmlDiv item = new HtmlDiv("share_item"); final HtmlLink actionLink = new HtmlLink("https://twitter.com/share", "Tweet"); item.add(actionLink); actionLink.setCssClass("twitter-share-button"); actionLink.addAttribute("data-count", "horizontal"); actionLink.addAttribute("data-url", new FeaturePageAliasUrl(feature).externalUrlString(true)); item.add(new PlaceHolderElement() { @Override protected List<HtmlNode> getPostNodes() { List<HtmlNode> nodes = new ArrayList<HtmlNode>(); final HtmlScript script = new HtmlScript(); script.addAttribute("src", "https://platform.twitter.com/widgets.js"); nodes.add(script); return nodes; } }); return item; } private HtmlNode generateLinkedInShareItem() { final HtmlDiv item = new HtmlDiv("share_item"); item.add(new PlaceHolderElement() { @Override protected List<HtmlNode> getPostNodes() { List<HtmlNode> nodes = new ArrayList<HtmlNode>(); final HtmlScript script = new HtmlScript(); nodes.add(script); script.addAttribute("src", "https://platform.linkedin.com/in.js"); return nodes; } }); final HtmlScript script2 = new HtmlScript(); item.add(script2); script2.addAttribute("type", "IN/Share"); script2.addAttribute("data-counter", "right"); script2.addAttribute("data-url", new FeaturePageAliasUrl(feature).externalUrlString(true)); return item; } private HtmlNode generatePlusoneShareItem() { final HtmlDiv item = new HtmlDiv("share_item"); item.add(new PlaceHolderElement() { @Override protected List<HtmlNode> getPostNodes() { List<HtmlNode> nodes = new ArrayList<HtmlNode>(); final HtmlScript script = new HtmlScript(); nodes.add(script); script.addAttribute("src", "https://apis.google.com/js/plusone.js"); script.append("{lang: '" + Context.getLocalizator().getCode() + "'}"); return nodes; } }); final HtmlGenericElement element = new HtmlGenericElement("g:plusone"); item.add(element); element.addAttribute("size", "medium"); element.addAttribute("href", new FeaturePageAliasUrl(feature).externalUrlString(true)); return item; } private HtmlNode generateFacebookShareItem() { final HtmlDiv item = new HtmlDiv("share_item"); final HtmlGenericElement facebookRootElement = new HtmlGenericElement("div"); item.add(facebookRootElement); facebookRootElement.addAttribute("id", "fb-root"); final HtmlScript script = new HtmlScript(); item.add(script); script.append("(function(d, s, id) {\n"// + "var js, fjs = d.getElementsByTagName(s)[0];\n"// + "if (d.getElementById(id)) {return;}\n"// + "js = d.createElement(s); js.id = id;\n"// + "js.src = \"//connect.facebook.net/fr_FR/all.js#xfbml=1\";\n"// + "fjs.parentNode.insertBefore(js, fjs);\n" // + "}(document, 'script', 'facebook-jssdk'));");// final HtmlGenericElement element = new HtmlGenericElement("div"); item.add(element); element.addAttribute("class", "fb-like"); element.addAttribute("data-href", new FeaturePageAliasUrl(feature).externalUrlString(true)); element.addAttribute("data-send", "false"); element.addAttribute("data-layout", "button_count"); element.addAttribute("data-width", "110"); element.addAttribute("data-show-faces", "false"); element.addAttribute("data-action", "recommend"); return item; } private HtmlDiv generateProgressBlock(final Feature feature, FeaturesTools.FeatureContext context) throws UnauthorizedOperationException { // //////////////////// // Div feature_summary_progress final HtmlDiv featureSummaryProgress = new HtmlDiv("feature_summary_progress"); { final HtmlDiv featureSummaryProgressAndState = new HtmlDiv("feature_summary_progress_and_state"); { featureSummaryProgressAndState.add(FeaturesTools.generateProgress(feature, context)); featureSummaryProgressAndState.add(FeaturesTools.generateState(feature)); } featureSummaryProgress.add(featureSummaryProgressAndState); // //////////////////// // Div feature_summary_actions final HtmlDiv actions = new HtmlDiv("feature_summary_actions"); { final HtmlDiv actionsButtons = new HtmlDiv("feature_summary_actions_buttons"); actions.add(actionsButtons); switch (feature.getFeatureState()) { case PENDING: actionsButtons.add(new HtmlDiv("contribute_block").add(generateContributeAction())); actionsButtons.add(new HtmlDiv("make_offer_block").add(generateMakeAnOfferAction())); break; case PREPARING: actionsButtons.add(new HtmlDiv("contribute_block").add(generateContributeAction())); actionsButtons.add(new HtmlDiv("alternative_offer_block").add(generateAlternativeOfferAction())); break; case DEVELOPPING: actionsButtons.add(new HtmlDiv("report_bug_block").add(generateDevelopingLeftActions())); actionsButtons.add(new HtmlDiv("developer_description_block").add(generateReportBugAction())); break; case FINISHED: actionsButtons.add(new HtmlDiv("report_bug_block").add(generateFinishedAction())); actionsButtons.add(new HtmlDiv("developer_description_block").add(generateReportBugAction())); break; case DISCARDED: // 2 columns are empty: Ok break; default: break; } } featureSummaryProgress.add(actions); } return featureSummaryProgress; } private PlaceHolderElement generateContributeAction() { final PlaceHolderElement element = new PlaceHolderElement(); final HtmlParagraph contributeText = new HtmlParagraph(Context.tr("You share this need and you want participate financially?")); element.add(contributeText); final HtmlLink link = new ContributionProcessUrl(feature).getHtmlLink(Context.tr("Contribute")); link.setCssClass("button"); element.add(link); return element; } private PlaceHolderElement generateMakeAnOfferAction() { final PlaceHolderElement element = new PlaceHolderElement(); final HtmlParagraph makeOfferText = new HtmlParagraph(Context.tr("You are a developer and want to be paid to achieve this request?")); element.add(makeOfferText); final HtmlLink link = new MakeOfferPageUrl(feature).getHtmlLink(Context.tr("Make an offer")); link.setCssClass("button"); element.add(link); return element; } private PlaceHolderElement generateAlternativeOfferAction() { final PlaceHolderElement element = new PlaceHolderElement(); final Offer selectedOffer = feature.getSelectedOffer(); if (selectedOffer != null) { final BigDecimal amountLeft = selectedOffer.getAmount().subtract(feature.getContribution()); if (amountLeft.compareTo(BigDecimal.ZERO) > 0) { final CurrencyLocale currency = Context.getLocalizator().getCurrency(amountLeft); element.add(new HtmlParagraph(tr(" {0} are missing before the development start.", currency.getSimpleEuroString()))); } else { final TimeRenderer renderer = new TimeRenderer(DateUtils.elapsed(DateUtils.now(), feature.getValidationDate())); element.add(new HtmlParagraph(tr("The development will begin in about ") + renderer.getTimeString() + ".")); } } final HtmlLink link = new MakeOfferPageUrl(feature).getHtmlLink(); final HtmlParagraph makeOfferText = new HtmlParagraph(new HtmlMixedText(Context.tr("An offer has already been made on this feature. However, you can <0::make an alternative offer>."), link)); element.add(makeOfferText); return element; } private PlaceHolderElement generateReportBugAction() { final PlaceHolderElement element = new PlaceHolderElement(); final Offer selectedOffer = feature.getSelectedOffer(); final Milestone currentMilestone = selectedOffer.isFinished() ? selectedOffer.getLastMilestone() : selectedOffer.getCurrentMilestone(); if (!selectedOffer.hasRelease()) { final Date releaseDate = currentMilestone.getExpirationDate(); final String date = Context.getLocalizator().getDate(releaseDate).toString(FormatStyle.LONG); element.add(new HtmlParagraph(tr("There is no release yet."))); if (DateUtils.isInTheFuture(releaseDate)) { element.add(new HtmlParagraph(tr("Next release is scheduled for {0}.", date))); } else { element.add(new HtmlParagraph(tr("Next release was scheduled for {0}.", date))); } } else { final int releaseCount = currentMilestone.getReleases().size(); final Release lastRelease = selectedOffer.getLastRelease(); final HtmlLink lastReleaseLink = new ReleasePageUrl(lastRelease).getHtmlLink(); final String releaseDate = Context.getLocalizator().getDate(lastRelease.getCreationDate()).toString(FormatStyle.FULL); element.add(new HtmlParagraph(trn("There is {0} release.", "There is {0} releases.", releaseCount, releaseCount))); element.add(new HtmlParagraph(new HtmlMixedText(tr("The <0::last version> was released {0}.", releaseDate), lastReleaseLink))); element.add(new HtmlParagraph(tr(" Test it and report bugs."))); final HtmlLink link = new ReportBugPageUrl(selectedOffer).getHtmlLink(Context.tr("Report a bug")); link.setCssClass("button"); element.add(link); } if (selectedOffer.getCurrentMilestone() != null && selectedOffer.getCurrentMilestone().canAddRelease()) { final HtmlLink link = new CreateReleasePageUrl(currentMilestone).getHtmlLink(Context.tr("Add a release")); link.setCssClass("button"); element.add(link); } return element; } private PlaceHolderElement generateDevelopingLeftActions() { final PlaceHolderElement element = new PlaceHolderElement(); final Actor<?> author = feature.getSelectedOffer().getAuthor(); final HtmlLink authorLink = new HtmlAuthorLink(feature.getSelectedOffer()); element.add(new HtmlDiv("float_left").add(MembersTools.getMemberAvatar(author))); element.add(new HtmlParagraph(new HtmlMixedText(tr("This feature is developed by <0>."), authorLink))); final Offer selectedOffer = feature.getSelectedOffer(); if (!feature.getSelectedOffer().isFinished() && selectedOffer.hasRelease()) { if (selectedOffer.getMilestones().size() == 1) { final Milestone currentMilestone = feature.getSelectedOffer().getCurrentMilestone(); if (!currentMilestone.hasBlockingBug()) { final Date validationDate = currentMilestone.getValidationDate(); if (DateUtils.isInTheFuture(validationDate)) { element.add(new HtmlParagraph(tr("If there is no new bug until {0}, it will be successful, and the developer will get its money.", Context.getLocalizator().getDate(validationDate).toString(FormatStyle.LONG)))); } else { element.add(new HtmlParagraph(tr("As soon as an administrator validate this feature, it will be successful, and the developer will get its money."))); } } else { final HtmlParagraph para = new HtmlParagraph(tr("This feature will be successful when all the {0} bugs are resolved.", getAllLevelsString(currentMilestone))); element.add(para); addMilestoneDetails(currentMilestone, authorLink, para); } } else { for (final Milestone milestone : selectedOffer.getMilestones()) { addMilestoneState(milestone, authorLink, element); } } } else { element.add(new HtmlParagraph(tr("Read the comments to have more recent informations."))); } return element; } private void addMilestoneState(final Milestone milestone, final HtmlLink authorLink, final PlaceHolderElement element) { switch (milestone.getMilestoneState()) { case DEVELOPING: element.add(new HtmlParagraph(tr("Milestone {0}: Developing", milestone.getPosition()))); break; case UAT: element.add(new HtmlParagraph(tr("Milestone {0}: User acceptance testing", milestone.getPosition()))); break; case VALIDATED: element.add(new HtmlParagraph(tr("Milestone {0}: Successful", milestone.getPosition()))); break; case CANCELED: element.add(new HtmlParagraph(tr("Milestone {0}: Canceled", milestone.getPosition()))); break; case PENDING:// should never append default:// should never append assert false; break; } if (!milestone.hasBlockingBug()) { final Date validationDate = milestone.getValidationDate(); if (DateUtils.isInTheFuture(validationDate)) { element.add(new HtmlParagraph(tr("If there is no new bug until {0}, this milestone will be successful, and the developer will get its money.", Context.getLocalizator().getDate(validationDate).toString(FormatStyle.LONG)))); } else { element.add(new HtmlParagraph(tr("As soon as an administrator validate this milestone, it will be successful, and the developer will get its money."))); } } else { element.add(new HtmlParagraph(tr("This milestone will be successful when all the {0} bugs will be resolved.", getAllLevelsString(milestone)))); addMilestoneDetails(milestone, authorLink, element); } } private void addMilestoneDetails(final Milestone milestone, final HtmlLink authorLink, final HtmlBranch element) { final int fatalSize = milestone.getNonResolvedBugs(Level.FATAL).size(); final int majorSize = milestone.getNonResolvedBugs(Level.MAJOR).size(); final int minorSize = milestone.getNonResolvedBugs(Level.MINOR).size(); final int fatalBugsPercent = milestone.getFatalBugsPercent(); final int majorBugsPercent = milestone.getMajorBugsPercent(); final int minorBugsPercent = milestone.getMinorBugsPercent(); final HtmlDiv details = new HtmlDiv(); if (fatalSize > 0 && fatalBugsPercent > 0) { details.add(new HtmlParagraph(new HtmlMixedText(trn("<0> will receive {0}% of the amount when the remaining FATAL bug are resolved.", "<0> will receive {0}% of the amount when the {1} remaining FATAL bugs are resolved.", fatalSize, fatalBugsPercent, fatalSize), authorLink))); } if (majorSize > 0 && majorBugsPercent > 0) { details.add(new HtmlParagraph(new HtmlMixedText(trn("<0> will receive {0}% of the amount when the remaining MAJOR bug are resolved.", "<0> will receive {0}% of the amount when the {1} remaining MAJOR bugs are resolved.", majorSize, majorBugsPercent, majorSize), authorLink))); } if (minorSize > 0 && minorBugsPercent > 0) { details.add(new HtmlParagraph(new HtmlMixedText(trn("<0> will receive {0}% of the amount when the remaining MINOR bug are resolved.", "<0> will receive {0}% of the amount when the {1} remaining MINOR bugs are resolved.", minorSize, minorBugsPercent, minorSize), authorLink))); } final HtmlBranch showHideLink = new HtmlSpan().addText(" " + tr("Details")); element.add(showHideLink); element.add(details); final JsShowHide showHideValidationDetails = new JsShowHide(element, false); showHideValidationDetails.setHasFallback(false); showHideLink.setCssClass("fake_link"); showHideValidationDetails.addActuator(showHideLink); showHideValidationDetails.addListener(details); showHideValidationDetails.apply(); } private String getAllLevelsString(final Milestone milestone) { final int fatalSize = milestone.getNonResolvedBugs(Level.FATAL).size(); final int majorSize = milestone.getNonResolvedBugs(Level.MAJOR).size(); final int minorSize = milestone.getNonResolvedBugs(Level.MINOR).size(); final List<Level> levels = new ArrayList<Level>(); if (fatalSize > 0 && milestone.getFatalBugsPercent() > 0) { levels.add(Level.FATAL); } if (majorSize > 0 && milestone.getMajorBugsPercent() > 0) { levels.add(Level.MAJOR); } if (minorSize > 0 && milestone.getMinorBugsPercent() > 0) { levels.add(Level.MINOR); } return composeLevels(levels); } private String composeLevels(final List<Level> levels) { final StringBuilder lev = new StringBuilder(); for (int i = 0; i < levels.size(); ++i) { if (i != 0 && i < levels.size() - 1) { lev.append(", "); } if (i != 0 && i == levels.size() - 1) { lev.append(tr(" and ")); } switch (levels.get(i)) { case FATAL: lev.append(tr("FATAL")); break; case MAJOR: lev.append(tr("MAJOR")); break; case MINOR: lev.append(tr("MINOR")); break; } } return lev.toString(); } private PlaceHolderElement generateFinishedAction() { final PlaceHolderElement element = new PlaceHolderElement(); final HtmlLink authorLink = new HtmlAuthorLink(feature.getSelectedOffer()); element.add(new HtmlDiv("float_left").add(MembersTools.getMemberAvatar(feature.getSelectedOffer().getAuthor()))); element.add(new HtmlParagraph(tr("This feature is finished."))); element.add(new HtmlParagraph(new HtmlMixedText(tr("The development was done by <0>."), authorLink))); final PageIterable<Bug> openBugs = feature.getOpenBugs(); if (openBugs.size() > 0) { element.add(new HtmlParagraph(trn("There is {0} open bug.", "There is {0} open bug.", openBugs.size(), openBugs.size()))); } else { element.add(new HtmlParagraph(tr("There is no open bug."))); } return element; } }
false
true
protected FeatureSummaryComponent(final Feature feature) { super(); this.feature = feature; try { // //////////////////// // Div feature_summary final HtmlDiv featureSummary = new HtmlDiv("feature_summary"); { // //////////////////// // Div feature_summary_top final HtmlDiv featureSummaryTop = new HtmlDiv("feature_summary_top"); { // //////////////////// // Div feature_summary_left final HtmlDiv featureSummaryLeft = new HtmlDiv("feature_summary_left"); { featureSummaryLeft.add(new SoftwaresTools.Logo(feature.getSoftware())); } featureSummaryTop.add(featureSummaryLeft); // //////////////////// // Div feature_summary_center final HtmlDiv featureSummaryCenter = new HtmlDiv("feature_summary_center"); { // Try to display the title final HtmlTitle title = new HtmlTitle(1); title.setCssClass("feature_title"); if (feature.hasSoftware()) { title.add(new SoftwaresTools.Link(feature.getSoftware())); title.addText(" – "); } title.addText(FeaturesTools.getTitle(feature)); featureSummaryCenter.add(title); } featureSummaryTop.add(featureSummaryCenter); } featureSummary.add(featureSummaryTop); // final JsShowHide shareBlockShowHide = new JsShowHide(false); // //////////////////// // Div feature_summary_bottom final HtmlDiv featureSummaryBottom = new HtmlDiv("feature_summary_bottom"); { // //////////////////// // Div feature_summary_popularity final HtmlDiv featureSummaryPopularity = new HtmlDiv("feature_summary_popularity"); { final HtmlParagraph popularityText = new HtmlParagraph(Context.tr("Popularity"), "feature_popularity_text"); final HtmlParagraph popularityScore = new HtmlParagraph(HtmlTools.compressKarma(feature.getPopularity()), "feature_popularity_score"); featureSummaryPopularity.add(popularityText); featureSummaryPopularity.add(popularityScore); if (!feature.getRights().isOwner()) { final int vote = feature.getUserVoteValue(); if (vote == 0) { final HtmlDiv featurePopularityJudge = new HtmlDiv("feature_popularity_judge"); { if (feature.canVoteUp().isEmpty()) { final PopularityVoteActionUrl usefulUrl = new PopularityVoteActionUrl(Context.getSession().getShortKey(), feature, true); final HtmlLink usefulLink = usefulUrl.getHtmlLink("+"); usefulLink.setCssClass("useful"); featurePopularityJudge.add(usefulLink); } if (feature.canVoteDown().isEmpty()) { final PopularityVoteActionUrl uselessUrl = new PopularityVoteActionUrl(Context.getSession().getShortKey(), feature, false); final HtmlLink uselessLink = uselessUrl.getHtmlLink("−"); uselessLink.setCssClass("useless"); featurePopularityJudge.add(uselessLink); } } featureSummaryPopularity.add(featurePopularityJudge); } else { // Already voted final HtmlDiv featurePopularityJudged = new HtmlDiv("feature_popularity_judged"); { if (vote > 0) { featurePopularityJudged.add(new HtmlParagraph("+" + vote, "useful")); } else { featurePopularityJudged.add(new HtmlParagraph("−" + Math.abs(vote), "useless")); } } featureSummaryPopularity.add(featurePopularityJudged); } } else { final HtmlDiv featurePopularityNone = new HtmlDiv("feature_popularity_none"); featureSummaryPopularity.add(featurePopularityNone); } // Delete the feature if (AuthToken.isAuthenticated() && AuthToken.getMember().getRights().hasAdminUserPrivilege()) { featureSummaryPopularity.add(new FeatureModerationPageUrl(feature).getHtmlLink(Context.tr("Moderate"))); } } featureSummaryBottom.add(featureSummaryPopularity); HtmlDiv featureSummaryProgress; featureSummaryProgress = generateProgressBlock(feature, FeaturesTools.FeatureContext.FEATURE_PAGE); featureSummaryBottom.add(featureSummaryProgress); // //////////////////// // Div feature_summary_share final HtmlDiv featureSummaryShare = new HtmlDiv("feature_summary_share_button"); { // final HtmlLink showHideShareBlock = new HtmlLink("#", // Context.tr("+ Share")); // shareBlockShowHide.addActuator(showHideShareBlock); // featureSummaryShare.add(showHideShareBlock); } featureSummaryBottom.add(featureSummaryShare); } featureSummary.add(featureSummaryBottom); // //////////////////// // Div feature_summary_share final HtmlDiv feature_summary_share_external = new HtmlDiv("feature_summary_share"); featureSummary.add(feature_summary_share_external); feature_summary_share_external.add(generateIdenticaShareItem()); feature_summary_share_external.add(generateTwitterShareItem()); feature_summary_share_external.add(generateLinkedInShareItem()); feature_summary_share_external.add(generatePlusoneShareItem()); feature_summary_share_external.add(generateFacebookShareItem()); // shareBlockShowHide.addListener(feature_summary_share_external); // shareBlockShowHide.apply(); } add(featureSummary); } catch (final UnauthorizedOperationException e) { Context.getSession().notifyError(Context.tr("An error prevented us from displaying feature information. Please notify us.")); throw new ShallNotPassException("User cannot access feature information", e); } }
protected FeatureSummaryComponent(final Feature feature) { super(); this.feature = feature; try { // //////////////////// // Div feature_summary final HtmlDiv featureSummary = new HtmlDiv("feature_summary"); { // //////////////////// // Div feature_summary_top final HtmlDiv featureSummaryTop = new HtmlDiv("feature_summary_top"); { // //////////////////// // Div feature_summary_left final HtmlDiv featureSummaryLeft = new HtmlDiv("feature_summary_left"); { featureSummaryLeft.add(new SoftwaresTools.Logo(feature.getSoftware())); } featureSummaryTop.add(featureSummaryLeft); // //////////////////// // Div feature_summary_center final HtmlDiv featureSummaryCenter = new HtmlDiv("feature_summary_center"); { // Try to display the title final HtmlTitle title = new HtmlTitle(1); title.setCssClass("feature_title"); if (feature.hasSoftware()) { title.add(new SoftwaresTools.Link(feature.getSoftware())); title.addText(" – "); } title.addText(FeaturesTools.getTitle(feature)); featureSummaryCenter.add(title); } featureSummaryTop.add(featureSummaryCenter); } featureSummary.add(featureSummaryTop); // final JsShowHide shareBlockShowHide = new JsShowHide(false); // //////////////////// // Div feature_summary_bottom final HtmlDiv featureSummaryBottom = new HtmlDiv("feature_summary_bottom"); { // //////////////////// // Div feature_summary_popularity final HtmlDiv featureSummaryPopularity = new HtmlDiv("feature_summary_popularity"); { final HtmlParagraph popularityText = new HtmlParagraph(Context.tr("Popularity"), "feature_popularity_text"); final HtmlParagraph popularityScore = new HtmlParagraph(HtmlTools.compressKarma(feature.getPopularity()), "feature_popularity_score"); featureSummaryPopularity.add(popularityText); featureSummaryPopularity.add(popularityScore); if (!feature.getRights().isOwner()) { final int vote = feature.getUserVoteValue(); if (vote == 0) { final HtmlDiv featurePopularityJudge = new HtmlDiv("feature_popularity_judge"); { if (!AuthToken.isAuthenticated() || feature.canVoteUp().isEmpty()) { final PopularityVoteActionUrl usefulUrl = new PopularityVoteActionUrl(Context.getSession().getShortKey(), feature, true); final HtmlLink usefulLink = usefulUrl.getHtmlLink("+"); usefulLink.setCssClass("useful"); featurePopularityJudge.add(usefulLink); } if (!AuthToken.isAuthenticated() || feature.canVoteDown().isEmpty()) { final PopularityVoteActionUrl uselessUrl = new PopularityVoteActionUrl(Context.getSession().getShortKey(), feature, false); final HtmlLink uselessLink = uselessUrl.getHtmlLink("−"); uselessLink.setCssClass("useless"); featurePopularityJudge.add(uselessLink); } } featureSummaryPopularity.add(featurePopularityJudge); } else { // Already voted final HtmlDiv featurePopularityJudged = new HtmlDiv("feature_popularity_judged"); { if (vote > 0) { featurePopularityJudged.add(new HtmlParagraph("+" + vote, "useful")); } else { featurePopularityJudged.add(new HtmlParagraph("−" + Math.abs(vote), "useless")); } } featureSummaryPopularity.add(featurePopularityJudged); } } else { final HtmlDiv featurePopularityNone = new HtmlDiv("feature_popularity_none"); featureSummaryPopularity.add(featurePopularityNone); } // Delete the feature if (AuthToken.isAuthenticated() && AuthToken.getMember().getRights().hasAdminUserPrivilege()) { featureSummaryPopularity.add(new FeatureModerationPageUrl(feature).getHtmlLink(Context.tr("Moderate"))); } } featureSummaryBottom.add(featureSummaryPopularity); HtmlDiv featureSummaryProgress; featureSummaryProgress = generateProgressBlock(feature, FeaturesTools.FeatureContext.FEATURE_PAGE); featureSummaryBottom.add(featureSummaryProgress); // //////////////////// // Div feature_summary_share final HtmlDiv featureSummaryShare = new HtmlDiv("feature_summary_share_button"); { // final HtmlLink showHideShareBlock = new HtmlLink("#", // Context.tr("+ Share")); // shareBlockShowHide.addActuator(showHideShareBlock); // featureSummaryShare.add(showHideShareBlock); } featureSummaryBottom.add(featureSummaryShare); } featureSummary.add(featureSummaryBottom); // //////////////////// // Div feature_summary_share final HtmlDiv feature_summary_share_external = new HtmlDiv("feature_summary_share"); featureSummary.add(feature_summary_share_external); feature_summary_share_external.add(generateIdenticaShareItem()); feature_summary_share_external.add(generateTwitterShareItem()); feature_summary_share_external.add(generateLinkedInShareItem()); feature_summary_share_external.add(generatePlusoneShareItem()); feature_summary_share_external.add(generateFacebookShareItem()); // shareBlockShowHide.addListener(feature_summary_share_external); // shareBlockShowHide.apply(); } add(featureSummary); } catch (final UnauthorizedOperationException e) { Context.getSession().notifyError(Context.tr("An error prevented us from displaying feature information. Please notify us.")); throw new ShallNotPassException("User cannot access feature information", e); } }
diff --git a/src/main/java/com/forgenz/mobmanager/spawner/config/Region.java b/src/main/java/com/forgenz/mobmanager/spawner/config/Region.java index 06d44e2..460ccae 100644 --- a/src/main/java/com/forgenz/mobmanager/spawner/config/Region.java +++ b/src/main/java/com/forgenz/mobmanager/spawner/config/Region.java @@ -1,324 +1,324 @@ /* * Copyright 2013 Michael McKnight. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and contributors and should not be interpreted as representing official policies, * either expressed or implied, of anybody else. */ package com.forgenz.mobmanager.spawner.config; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.block.Biome; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import com.forgenz.mobmanager.MMComponent; import com.forgenz.mobmanager.common.config.AbstractConfig; import com.forgenz.mobmanager.common.util.MiscUtil; import com.forgenz.mobmanager.common.util.RandomUtil; import com.forgenz.mobmanager.spawner.config.regions.GlobalRegion; import com.forgenz.mobmanager.spawner.config.regions.PointCircleRegion; import com.forgenz.mobmanager.spawner.config.regions.PointSquareRegion; import com.forgenz.mobmanager.spawner.util.MobCounter; import com.forgenz.mobmanager.spawner.util.MobSpawner; /** * Represents an area which mobs can be spawned */ public abstract class Region extends AbstractConfig { public final String name; public final int priority; public final int spawnAttempts; public final float spawnAttemptChance; public final int maxBlockRange, minBlockRange; public final int maxPlayerMobs; public final int mobLimitTimeout; public MobCounter maxAliveLimiter; private final List<Mob> mobs; public final boolean hasRegionLimitBypass; public Region(ConfigurationSection cfg, RegionType type) { super.setCfg(cfg); name = cfg.getName(); int priority = getAndSet("Priority", type != RegionType.GLOBAL ? 1 : 0); this.priority = priority > 0 ? priority : type != RegionType.GLOBAL ? 1 : 0; set("Priority", priority); spawnAttempts = getAndSet("SpawnAttempts", 1); spawnAttemptChance = getAndSet("SpawnAttemptChance", 100.0F) / 100.0F; maxBlockRange = getAndSet("MaxBlockRange", 56); minBlockRange = getAndSet("MinBlockRange", 24); maxPlayerMobs = getAndSet("MaxPlayerMobs", 15); mobLimitTimeout = getAndSet("MobPlayerLimitTimeoutTicks", 6000); int maxRegionMobs = getAndSet("MaxRegionMobs", 0); - int regionMobCooldown = getAndSet("RegionMobCooldown", 60); + int regionMobCooldown = getAndSet("RegionMobCooldown", 60) * 1000; boolean enforceAllRemovalConditions = getAndSet("EnforceAllCooldownConditions", false); if (maxRegionMobs > 0) maxAliveLimiter = new MobCounter(maxRegionMobs, regionMobCooldown, enforceAllRemovalConditions); initialise(); ArrayList<Mob> mobs = new ArrayList<Mob>(); boolean hasRegionLimitBypass = false; // Fetch mob configs List<Object> mobConfigs = MiscUtil.getList(getAndSet("Mobs", new ArrayList<Map<String, Object>>())); // Iterate through each config for (int i = 0; i < mobConfigs.size(); ++i) { // Fetch the config Map<String, Object> mobConfig = MiscUtil.copyConfigMap(mobConfigs.get(i)); // Update the map mobConfigs.set(i, mobConfig); // Parse the mob config Mob mob = Mob.setup(mobConfig, this); if (mob != null) mobs.add(mob); if (mob.bypassRegionLimit) hasRegionLimitBypass = true; } set("Mobs", mobConfigs); this.hasRegionLimitBypass = hasRegionLimitBypass; this.mobs = Collections.unmodifiableList(mobs); super.clearCfg(); } public abstract void initialise(); public abstract boolean withinRegion(Location location); /** * Returns the list of mobs */ public List<Mob> getMobs(int y, Environment environment, Biome biome) { List<Mob> mobList = new ArrayList<Mob>(mobs.size()); for (Mob mob : mobs) { SpawnRequirements r = mob.getRequirements(); if (r == null || (r.meetsHeightRequirements(y) && r.meetsEnvironmentRequirements(environment) && r.meetsBiomeRequirements(biome))) mobList.add(mob); } return mobList; } public boolean withinAliveLimit() { return maxAliveLimiter == null || maxAliveLimiter.withinLimit(); } /** * Adds the entity to this mobs MaxAlive limit * * @param e The entity to add */ public void spawned(LivingEntity e) { if (maxAliveLimiter != null) maxAliveLimiter.spawned(e); } /** * Attempts to spawn a mob within the region * <p> * Note: Not essential that the location is within the region but it should be :3 * * @param player The player the mob will be spawning for * @param spawnLoc The location the mob will be spawning at * @param lightLevel The light level at the given spawn location * @param biome The biome type at the given spawn location * @param materialBelow The material of the block below the given spawn location * @param environment The environment of the world the given location is in * * @return True if a mob was spawned */ public boolean spawnMob(Player player, int playerY, int heightRange, Location spawnLoc, int lightLevel, Biome biome, Material materialBelow, Environment environment) { // Fetch all the mobs which we can spawn in this location ArrayList<Mob> spawnableMobs = getSpawnableMobs(spawnLoc.getWorld(), spawnLoc, lightLevel, biome, materialBelow, environment); // If no mobs can spawn here return false :'( if (spawnableMobs.isEmpty()) return false; // Fetch a random mob from the list of spawnable mobs Mob mob = getMob(mobs, getTotalChance(mobs)); // If the mob is null, or the entity type is invalid return false :'( if (mob == null || mob.getMobType().getBukkitEntityType() == null) return false; // If this mobs requirements check was delayed check it now if (mob.delayRequirementsCheck && mob.requirementsMet(spawnLoc.getWorld(), spawnLoc, lightLevel, biome, materialBelow, environment)) return false; // If the alive limit is not met and the chosen mob can't bypass it we do nothing if (!mob.bypassRegionLimit && !withinAliveLimit()) return false; // Add the height offset if (!mob.addHeightOffset(spawnLoc, playerY, heightRange)) return false; // Add a task to spawn the mob in the main thread MMComponent.getSpawner().getSpawnerTask().addSpawner(new MobSpawner(this, player, spawnLoc, mob, playerY, heightRange)); return true; } /** * Fetches all mobs which can spawn in the given location and returns a list of them * * @param world The world the mob is spawning in * @param y The Y coordinate at which the mob will be spawning at * @param lightLevel The light level at the spawn location * @param biome The Biome type at the spawn location * @param materialBelow The Material of the block below the spawn location * @param environment The environment in the world the spawn location is in * * @return A list of spawnable mobs */ private ArrayList<Mob> getSpawnableMobs(World world, Location sLoc, int lightLevel, Biome biome, Material materialBelow, Environment environment) { // Initialise the list ArrayList<Mob> spawnableMobs = MMComponent.getSpawner().getConfig().getCachedList(); for (Mob mob : mobs) { // Check if the mobs requirements are met if (mob.requirementsMet(world, sLoc, lightLevel, biome, materialBelow, environment)) spawnableMobs.add(mob); } return spawnableMobs; } /** * Calculates the total of chances * * @param mobs List of mobs to total the chances of * * @return Sum of all chances */ private int getTotalChance(final List<Mob> mobs) { int chance = 0; for (Mob mob : mobs) chance += mob.spawnChance; return chance; } /** * Fetches a random mob from the given list</br> * Uses the mobs chances to pick mobs * * @param mobs List of mobs to pick from * @param totalChance Sum of all mob chances in the list * * @return A single mob */ private Mob getMob(final List<Mob> mobs, int totalChance) { // Get a random number between 0 and the int chance = RandomUtil.i.nextInt(totalChance); for (Mob mob : mobs) { // Minus the chance of the mob from the total chance -= mob.spawnChance; // Once 'chance' reduces below 0 we have found our mob if (chance < 0) return mob; } // Waht� MMComponent.getSpawner().warning("Mob chances failed (That should never happen)"); return null; } @Override public String toString() { return name; } /** * Represents a type of region */ public enum RegionType { /** Global Region */ GLOBAL(GlobalRegion.class), /** Cylindrical region centered around a point */ POINT_CIRCLE(PointCircleRegion.class), /** Rectangular region centered around a point */ POINT_SQUARE(PointSquareRegion.class); private final Class<? extends Region> clazz; private RegionType(Class<? extends Region> clazz) { this.clazz = clazz; } public Region createRegion(ConfigurationSection cfg) { try { return clazz.getConstructor(ConfigurationSection.class).newInstance(cfg); } catch (Exception e) { MMComponent.getSpawner().severe("Error occured when creating region. RegionType=%s, RegionName=%s", e, this, cfg.getName()); return null; } } } }
true
true
public Region(ConfigurationSection cfg, RegionType type) { super.setCfg(cfg); name = cfg.getName(); int priority = getAndSet("Priority", type != RegionType.GLOBAL ? 1 : 0); this.priority = priority > 0 ? priority : type != RegionType.GLOBAL ? 1 : 0; set("Priority", priority); spawnAttempts = getAndSet("SpawnAttempts", 1); spawnAttemptChance = getAndSet("SpawnAttemptChance", 100.0F) / 100.0F; maxBlockRange = getAndSet("MaxBlockRange", 56); minBlockRange = getAndSet("MinBlockRange", 24); maxPlayerMobs = getAndSet("MaxPlayerMobs", 15); mobLimitTimeout = getAndSet("MobPlayerLimitTimeoutTicks", 6000); int maxRegionMobs = getAndSet("MaxRegionMobs", 0); int regionMobCooldown = getAndSet("RegionMobCooldown", 60); boolean enforceAllRemovalConditions = getAndSet("EnforceAllCooldownConditions", false); if (maxRegionMobs > 0) maxAliveLimiter = new MobCounter(maxRegionMobs, regionMobCooldown, enforceAllRemovalConditions); initialise(); ArrayList<Mob> mobs = new ArrayList<Mob>(); boolean hasRegionLimitBypass = false; // Fetch mob configs List<Object> mobConfigs = MiscUtil.getList(getAndSet("Mobs", new ArrayList<Map<String, Object>>())); // Iterate through each config for (int i = 0; i < mobConfigs.size(); ++i) { // Fetch the config Map<String, Object> mobConfig = MiscUtil.copyConfigMap(mobConfigs.get(i)); // Update the map mobConfigs.set(i, mobConfig); // Parse the mob config Mob mob = Mob.setup(mobConfig, this); if (mob != null) mobs.add(mob); if (mob.bypassRegionLimit) hasRegionLimitBypass = true; } set("Mobs", mobConfigs); this.hasRegionLimitBypass = hasRegionLimitBypass; this.mobs = Collections.unmodifiableList(mobs); super.clearCfg(); }
public Region(ConfigurationSection cfg, RegionType type) { super.setCfg(cfg); name = cfg.getName(); int priority = getAndSet("Priority", type != RegionType.GLOBAL ? 1 : 0); this.priority = priority > 0 ? priority : type != RegionType.GLOBAL ? 1 : 0; set("Priority", priority); spawnAttempts = getAndSet("SpawnAttempts", 1); spawnAttemptChance = getAndSet("SpawnAttemptChance", 100.0F) / 100.0F; maxBlockRange = getAndSet("MaxBlockRange", 56); minBlockRange = getAndSet("MinBlockRange", 24); maxPlayerMobs = getAndSet("MaxPlayerMobs", 15); mobLimitTimeout = getAndSet("MobPlayerLimitTimeoutTicks", 6000); int maxRegionMobs = getAndSet("MaxRegionMobs", 0); int regionMobCooldown = getAndSet("RegionMobCooldown", 60) * 1000; boolean enforceAllRemovalConditions = getAndSet("EnforceAllCooldownConditions", false); if (maxRegionMobs > 0) maxAliveLimiter = new MobCounter(maxRegionMobs, regionMobCooldown, enforceAllRemovalConditions); initialise(); ArrayList<Mob> mobs = new ArrayList<Mob>(); boolean hasRegionLimitBypass = false; // Fetch mob configs List<Object> mobConfigs = MiscUtil.getList(getAndSet("Mobs", new ArrayList<Map<String, Object>>())); // Iterate through each config for (int i = 0; i < mobConfigs.size(); ++i) { // Fetch the config Map<String, Object> mobConfig = MiscUtil.copyConfigMap(mobConfigs.get(i)); // Update the map mobConfigs.set(i, mobConfig); // Parse the mob config Mob mob = Mob.setup(mobConfig, this); if (mob != null) mobs.add(mob); if (mob.bypassRegionLimit) hasRegionLimitBypass = true; } set("Mobs", mobConfigs); this.hasRegionLimitBypass = hasRegionLimitBypass; this.mobs = Collections.unmodifiableList(mobs); super.clearCfg(); }
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipFactoryImpl.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipFactoryImpl.java index 1c6dc9517..bf4dc49fa 100644 --- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipFactoryImpl.java +++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipFactoryImpl.java @@ -1,722 +1,723 @@ /* * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.mobicents.servlet.sip.message; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Serializable; import java.text.ParseException; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.servlet.sip.Address; import javax.servlet.sip.AuthInfo; import javax.servlet.sip.Parameterable; import javax.servlet.sip.ServletParseException; import javax.servlet.sip.SipApplicationSession; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipURI; import javax.servlet.sip.URI; import javax.servlet.sip.ar.SipApplicationRouterInfo; import javax.sip.ListeningPoint; import javax.sip.SipException; import javax.sip.header.CSeqHeader; import javax.sip.header.CallIdHeader; import javax.sip.header.ContactHeader; import javax.sip.header.ContentTypeHeader; import javax.sip.header.FromHeader; import javax.sip.header.Header; import javax.sip.header.MaxForwardsHeader; import javax.sip.header.RouteHeader; import javax.sip.header.ToHeader; import javax.sip.message.Request; import org.apache.log4j.Logger; import org.mobicents.servlet.sip.JainSipUtils; import org.mobicents.servlet.sip.SipFactories; import org.mobicents.servlet.sip.address.AddressImpl; import org.mobicents.servlet.sip.address.GenericURIImpl; import org.mobicents.servlet.sip.address.SipURIImpl; import org.mobicents.servlet.sip.address.TelURLImpl; import org.mobicents.servlet.sip.address.URIImpl; import org.mobicents.servlet.sip.core.ApplicationRoutingHeaderComposer; import org.mobicents.servlet.sip.core.ExtendedListeningPoint; import org.mobicents.servlet.sip.core.SipApplicationDispatcher; import org.mobicents.servlet.sip.core.SipNetworkInterfaceManager; import org.mobicents.servlet.sip.core.dispatchers.MessageDispatcher; import org.mobicents.servlet.sip.core.session.MobicentsSipApplicationSession; import org.mobicents.servlet.sip.core.session.MobicentsSipSession; import org.mobicents.servlet.sip.core.session.SessionManagerUtil; import org.mobicents.servlet.sip.core.session.SipApplicationSessionKey; import org.mobicents.servlet.sip.core.session.SipManager; import org.mobicents.servlet.sip.core.session.SipSessionKey; import org.mobicents.servlet.sip.security.AuthInfoImpl; import org.mobicents.servlet.sip.startup.SipContext; import org.mobicents.servlet.sip.startup.StaticServiceHolder; import org.mobicents.servlet.sip.startup.failover.BalancerDescription; public class SipFactoryImpl implements Externalizable { private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(SipFactoryImpl.class .getCanonicalName()); private static final String TAG_PARAM = "tag"; private static final String METHOD_PARAM = "method"; private static final String MADDR_PARAM = "maddr"; private static final String TTL_PARAM = "ttl"; private static final String TRANSPORT_PARAM = "transport"; private static final String LR_PARAM = "lr"; private boolean useLoadBalancer = false; private BalancerDescription loadBalancerToUse = null; public static class NamesComparator implements Comparator<String>, Serializable { private static final long serialVersionUID = 1L; public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } } private static final Set<String> forbbidenParams = new HashSet<String>(); static { forbbidenParams.add(TAG_PARAM); forbbidenParams.add(METHOD_PARAM); forbbidenParams.add(MADDR_PARAM); forbbidenParams.add(TTL_PARAM); forbbidenParams.add(TRANSPORT_PARAM); forbbidenParams.add(LR_PARAM); } private transient SipApplicationDispatcher sipApplicationDispatcher = null; public SipFactoryImpl() {} /** * Dafault constructor * @param sipApplicationDispatcher */ public SipFactoryImpl(SipApplicationDispatcher sipApplicationDispatcher) { this.sipApplicationDispatcher = sipApplicationDispatcher; } /* * (non-Javadoc) * * @see javax.servlet.sip.SipFactory#createAddress(java.lang.String) */ public Address createAddress(String sipAddress) throws ServletParseException { try { if (logger.isDebugEnabled()) { logger.debug("Creating Address from [" + sipAddress + "]"); } AddressImpl retval = new AddressImpl(); retval.setValue(sipAddress); return retval; } catch (IllegalArgumentException e) { throw new ServletParseException(e); } } /* * (non-Javadoc) * * @see javax.servlet.sip.SipFactory#createAddress(javax.servlet.sip.URI) */ public Address createAddress(URI uri) { if (logger.isDebugEnabled()) { logger.debug("Creating Address fromm URI[" + uri.toString() + "]"); } URIImpl uriImpl = (URIImpl) uri; return new AddressImpl(SipFactories.addressFactory .createAddress(uriImpl.getURI()), null, true); } /* * (non-Javadoc) * * @see javax.servlet.sip.SipFactory#createAddress(javax.servlet.sip.URI, * java.lang.String) */ public Address createAddress(URI uri, String displayName) { try { if (logger.isDebugEnabled()) { logger.debug("Creating Address from URI[" + uri.toString() + "] with display name[" + displayName + "]"); } javax.sip.address.Address address = SipFactories.addressFactory .createAddress(((URIImpl) uri).getURI()); address.setDisplayName(displayName); return new AddressImpl(address, null, true); } catch (ParseException e) { throw new IllegalArgumentException(e); } } /* * (non-Javadoc) * * @see javax.servlet.sip.SipFactory#createApplicationSession() */ public SipApplicationSession createApplicationSession() { throw new UnsupportedOperationException("use createApplicationSession(SipContext sipContext) instead !"); } /** * Creates an application session associated with the context * @param sipContext * @return */ public SipApplicationSession createApplicationSession(SipContext sipContext) { if (logger.isDebugEnabled()) { logger.debug("Creating new application session for sip context "+ sipContext.getApplicationName()); } //call id not needed anymore since the sipappsessionkey is not a callid anymore but a random uuid SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey( sipContext.getApplicationName(), null); MobicentsSipApplicationSession sipApplicationSession = ((SipManager)sipContext.getManager()).getSipApplicationSession( sipApplicationSessionKey, true); return sipApplicationSession.getSession(); } /* * (non-Javadoc) * * @see javax.servlet.sip.SipFactory#createRequest(javax.servlet.sip.SipApplicationSession, * java.lang.String, javax.servlet.sip.Address, * javax.servlet.sip.Address) */ public SipServletRequest createRequest(SipApplicationSession sipAppSession, String method, Address from, Address to, String handler) { if (logger.isDebugEnabled()) { logger .debug("Creating new SipServletRequest for SipApplicationSession[" + sipAppSession + "] METHOD[" + method + "] FROM_A[" + from + "] TO_A[" + to + "]"); } validateCreation(method, sipAppSession); try { //javadoc specifies that a copy of the address should be done hence the clone return createSipServletRequest(sipAppSession, method, (Address)from.clone(), (Address)to.clone(), handler); } catch (ServletParseException e) { logger.error("Error creating sipServletRequest", e); return null; } } /* * (non-Javadoc) * * @see javax.servlet.sip.SipFactory#createRequest(javax.servlet.sip.SipApplicationSession, * java.lang.String, javax.servlet.sip.URI, javax.servlet.sip.URI) */ public SipServletRequest createRequest(SipApplicationSession sipAppSession, String method, URI from, URI to, String handler) { if (logger.isDebugEnabled()) { logger .debug("Creating new SipServletRequest for SipApplicationSession[" + sipAppSession + "] METHOD[" + method + "] FROM_URI[" + from + "] TO_URI[" + to + "]"); } validateCreation(method, sipAppSession); //javadoc specifies that a copy of the uri should be done hence the clone Address toA = this.createAddress(to.clone()); Address fromA = this.createAddress(from.clone()); try { return createSipServletRequest(sipAppSession, method, fromA, toA, handler); } catch (ServletParseException e) { logger.error("Error creating sipServletRequest", e); return null; } } /* * (non-Javadoc) * * @see javax.servlet.sip.SipFactory#createRequest(javax.servlet.sip.SipApplicationSession, * java.lang.String, java.lang.String, java.lang.String) */ public SipServletRequest createRequest(SipApplicationSession sipAppSession, String method, String from, String to, String handler) throws ServletParseException { if (logger.isDebugEnabled()) { logger .debug("Creating new SipServletRequest for SipApplicationSession[" + sipAppSession + "] METHOD[" + method + "] FROM[" + from + "] TO[" + to + "]"); } validateCreation(method, sipAppSession); Address toA = this.createAddress(to); Address fromA = this.createAddress(from); return createSipServletRequest(sipAppSession, method, fromA, toA, handler); } /* * (non-Javadoc) * * @see javax.servlet.sip.SipFactory#createRequest(javax.servlet.sip.SipServletRequest, * boolean) */ public SipServletRequest createRequest(SipServletRequest origRequest, boolean sameCallId) { if (logger.isDebugEnabled()) { logger.debug("Creating SipServletRequest from original request[" + origRequest + "] with same call id[" + sameCallId + "]"); } return origRequest.getB2buaHelper().createRequest(origRequest); } /* * (non-Javadoc) * * @see javax.servlet.sip.SipFactory#createSipURI(java.lang.String, * java.lang.String) */ public SipURI createSipURI(String user, String host) { if (logger.isDebugEnabled()) { logger.debug("Creating SipURI from USER[" + user + "] HOST[" + host + "]"); } try { return new SipURIImpl(SipFactories.addressFactory.createSipURI( user, host)); } catch (ParseException e) { logger.error("couldn't parse the SipURI from USER[" + user + "] HOST[" + host + "]", e); throw new IllegalArgumentException("Could not create SIP URI user = " + user + " host = " + host); } } public URI createURI(String uri) throws ServletParseException { // if(!checkScheme(uri)) { // // testCreateProxyBranches101 needs this to be IllegalArgumentExcpetion, but the test is wrong // throw new ServletParseException("The uri " + uri + " is not valid"); // } try { javax.sip.address.URI jainUri = SipFactories.addressFactory .createURI(uri); if (jainUri instanceof javax.sip.address.SipURI) { return new SipURIImpl( (javax.sip.address.SipURI) jainUri); } else if (jainUri instanceof javax.sip.address.TelURL) { return new TelURLImpl( (javax.sip.address.TelURL) jainUri); } else { return new GenericURIImpl(jainUri); } } catch (ParseException ex) { throw new ServletParseException("Bad param " + uri, ex); } } // ------------ HELPER METHODS // -------------------- createRequest /** * Does basic check for illegal methods, wrong state, if it finds, it throws * exception * */ private static void validateCreation(String method, SipApplicationSession app) { if (method.equals(Request.ACK)) { throw new IllegalArgumentException( "Wrong method to create request with[" + Request.ACK + "]!"); } if (method.equals(Request.PRACK)) { throw new IllegalArgumentException( "Wrong method to create request with[" + Request.PRACK + "]!"); } if (method.equals(Request.CANCEL)) { throw new IllegalArgumentException( "Wrong method to create request with[" + Request.CANCEL + "]!"); } if (!app.isValid()) { throw new IllegalArgumentException( "Cant associate request with invalidaded sip session application!"); } } /** * This method actually does create javax.sip.message.Request, dialog(if * method is INVITE or SUBSCRIBE), ctx and wraps this in new sipsession * * @param sipAppSession * @param method * @param from * @param to * @return */ private SipServletRequest createSipServletRequest( SipApplicationSession sipAppSession, String method, Address from, Address to, String handler) throws ServletParseException { MobicentsSipApplicationSession mobicentsSipApplicationSession = (MobicentsSipApplicationSession) sipAppSession; // the request object with method, request URI, and From, To, Call-ID, // CSeq, Route headers filled in. Request requestToWrap = null; ContactHeader contactHeader = null; ToHeader toHeader = null; FromHeader fromHeader = null; CSeqHeader cseqHeader = null; CallIdHeader callIdHeader = null; MaxForwardsHeader maxForwardsHeader = null; // FIXME: Is this nough? // We need address from which this will be sent, also this one will be // default for contact and via String transport = ListeningPoint.UDP; // LETS CREATE OUR HEADERS javax.sip.address.Address fromAddress = null; try { // Issue 676 : Any component of the from and to URIs not allowed in the context of // SIP From and To headers are removed from the copies [refer Table 1, Section // 19.1.1, RFC3261] for(String param : forbbidenParams) { from.getURI().removeParameter(param); } // Issue 676 : from tags not removed so removing the tag from.removeParameter(TAG_PARAM); fromAddress = SipFactories.addressFactory .createAddress(((URIImpl)from.getURI()).getURI()); fromAddress.setDisplayName(from.getDisplayName()); fromHeader = SipFactories.headerFactory.createFromHeader(fromAddress, null); } catch (Exception pe) { throw new ServletParseException("Impossoible to parse the given From " + from.toString(), pe); } javax.sip.address.Address toAddress = null; try{ // Issue 676 : Any component of the from and to URIs not allowed in the context of // SIP From and To headers are removed from the copies [refer Table 1, Section // 19.1.1, RFC3261] for(String param : forbbidenParams) { to.getURI().removeParameter(param); } // Issue 676 : to tags not removed so removing the tag to.removeParameter(TAG_PARAM); toAddress = SipFactories.addressFactory .createAddress(((URIImpl)to.getURI()).getURI()); toAddress.setDisplayName(to.getDisplayName()); toHeader = SipFactories.headerFactory.createToHeader(toAddress, null); } catch (Exception pe) { throw new ServletParseException("Impossoible to parse the given To " + to.toString(), pe); } try { cseqHeader = SipFactories.headerFactory.createCSeqHeader(1L, method); // Fix provided by Hauke D. Issue 411 SipApplicationSessionKey sipApplicationSessionKey = mobicentsSipApplicationSession.getKey(); // if(sipApplicationSessionKey.isAppGeneratedKey()) { callIdHeader = SipFactories.headerFactory.createCallIdHeader( getSipNetworkInterfaceManager().getExtendedListeningPoints().next().getSipProvider().getNewCallId().getCallId()); // } else { // callIdHeader = SipFactories.headerFactory.createCallIdHeader( // sipApplicationSessionKey.getId()); // } maxForwardsHeader = SipFactories.headerFactory .createMaxForwardsHeader(JainSipUtils.MAX_FORWARD_HEADER_VALUE); URIImpl requestURI = (URIImpl)to.getURI().clone(); // copying address params into headers. Iterator<String> keys = to.getParameterNames(); while (keys.hasNext()) { String key = keys.next(); toHeader.setParameter(key, to.getParameter(key)); } keys = from.getParameterNames(); while (keys.hasNext()) { String key = keys.next(); fromHeader.setParameter(key, from.getParameter(key)); } //Issue 112 by folsson : no via header to add will be added when the request will be sent out List<Header> viaHeaders = new ArrayList<Header>(); requestToWrap = SipFactories.messageFactory.createRequest( requestURI.getURI(), method, callIdHeader, cseqHeader, fromHeader, toHeader, viaHeaders, maxForwardsHeader); //Adding default contact header for register - if(Request.REGISTER.equalsIgnoreCase(method)) { + if(Request.REGISTER.equalsIgnoreCase(method) + || Request.INVITE.equalsIgnoreCase(method)) { String fromName = null; if(fromHeader.getAddress().getURI() instanceof javax.sip.address.SipURI) { fromName = ((javax.sip.address.SipURI)fromHeader.getAddress().getURI()).getUser(); } // Create the contact name address. contactHeader = null; // if a sip load balancer is present in front of the server, the contact header is the one from the sip lb // so that the subsequent requests can be failed over if(useLoadBalancer) { javax.sip.address.SipURI sipURI = SipFactories.addressFactory.createSipURI(fromName, loadBalancerToUse.getAddress().getHostAddress()); sipURI.setHost(loadBalancerToUse.getAddress().getHostAddress()); sipURI.setPort(loadBalancerToUse.getSipPort()); sipURI.setTransportParam(transport); javax.sip.address.Address contactAddress = SipFactories.addressFactory.createAddress(sipURI); if(fromName != null && fromName.length() > 0) { contactAddress.setDisplayName(fromName); } contactHeader = SipFactories.headerFactory.createContactHeader(contactAddress); } else { contactHeader = JainSipUtils.createContactHeader(getSipNetworkInterfaceManager(), requestToWrap, fromName); } } // Add all headers if(contactHeader != null) { requestToWrap.addHeader(contactHeader); } fromHeader.setTag(ApplicationRoutingHeaderComposer.getHash(sipApplicationDispatcher, sipAppSession.getApplicationName(), sipApplicationSessionKey.getId())); SipSessionKey key = SessionManagerUtil.getSipSessionKey( mobicentsSipApplicationSession.getKey().getId(), mobicentsSipApplicationSession.getKey().getApplicationName(), requestToWrap, false); MobicentsSipSession session = ((SipManager)mobicentsSipApplicationSession.getSipContext().getManager()). getSipSession(key, true, this, mobicentsSipApplicationSession); session.setHandler(handler); session.setLocalParty(new AddressImpl(fromAddress, null, false)); session.setRemoteParty(new AddressImpl(toAddress, null, false)); SipServletRequest retVal = new SipServletRequestImpl( requestToWrap, this, session, null, null, JainSipUtils.dialogCreatingMethods.contains(method)); return retVal; } catch (Exception e) { logger.error("Error creating sipServletRequest", e); } return null; } /** * {@inheritDoc} */ public Parameterable createParameterable(String value) throws ServletParseException { try { Header header = SipFactories.headerFactory.createHeader(ContactHeader.NAME, value); return SipServletMessageImpl.createParameterable(header, SipServletMessageImpl.getFullHeaderName(header.getName())); } catch (ParseException e) { try { Header header = SipFactories.headerFactory.createHeader(ContentTypeHeader.NAME, value); return SipServletMessageImpl.createParameterable(header, SipServletMessageImpl.getFullHeaderName(header.getName())); } catch (ParseException pe) { throw new ServletParseException("Impossible to parse the following parameterable "+ value , pe); } } } /** * {@inheritDoc} */ public SipApplicationRouterInfo getNextInterestedApplication(SipServletRequestImpl sipServletRequestImpl) { return sipApplicationDispatcher.getNextInterestedApplication(sipServletRequestImpl); } /* * (non-Javadoc) * @see javax.servlet.sip.SipFactory#createApplicationSessionByAppName(java.lang.String) */ public SipApplicationSession createApplicationSessionByAppName( String sipAppName) { if (logger.isDebugEnabled()) { logger.debug("Creating new application session for application name " + sipAppName); } SipContext sipContext = sipApplicationDispatcher.findSipApplication(sipAppName); if(sipContext == null) { throw new IllegalArgumentException("The specified application "+sipAppName+" is not currently deployed"); } return createApplicationSession(sipContext); } /* * (non-Javadoc) * @see javax.servlet.sip.SipFactory#createApplicationSessionByKey(java.lang.String) */ public SipApplicationSession createApplicationSessionByKey( String sipApplicationKey) { if (logger.isDebugEnabled()) { logger.debug("Creating new application session by following key " + sipApplicationKey); } SipApplicationSessionKey sipApplicationSessionKey = null; try { sipApplicationSessionKey = SessionManagerUtil.parseSipApplicationSessionKey( sipApplicationKey); } catch (ParseException e) { throw new IllegalArgumentException(sipApplicationKey + " is not a valid sip application session key", e); } SipContext sipContext = sipApplicationDispatcher.findSipApplication(sipApplicationSessionKey.getApplicationName()); if(sipContext == null) { throw new IllegalArgumentException("The specified application "+sipApplicationSessionKey.getApplicationName()+" is not currently deployed"); } MobicentsSipApplicationSession sipApplicationSession = ((SipManager)sipContext.getManager()).getSipApplicationSession( sipApplicationSessionKey, true); return sipApplicationSession.getSession(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipFactory#createAuthInfo() */ public AuthInfo createAuthInfo() { return new AuthInfoImpl(); } /** * @return the sipApplicationDispatcher */ public SipApplicationDispatcher getSipApplicationDispatcher() { return sipApplicationDispatcher; } /** * @param sipApplicationDispatcher the sipApplicationDispatcher to set */ public void setSipApplicationDispatcher( SipApplicationDispatcher sipApplicationDispatcher) { this.sipApplicationDispatcher = sipApplicationDispatcher; } /** * Retrieve the manager for the sip network interfaces * @return the manager for the sip network interfaces */ public SipNetworkInterfaceManager getSipNetworkInterfaceManager() { return sipApplicationDispatcher.getSipNetworkInterfaceManager(); } /** * @return the loadBalancerToUse */ public BalancerDescription getLoadBalancerToUse() { return loadBalancerToUse; } /** * @param loadBalancerToUse the loadBalancerToUse to set */ public void setLoadBalancerToUse(BalancerDescription loadBalancerToUse) { if(loadBalancerToUse == null) { useLoadBalancer = false; } else { useLoadBalancer = true; } this.loadBalancerToUse = loadBalancerToUse; } /** * @return the useLoadBalancer */ public boolean isUseLoadBalancer() { return useLoadBalancer; } /** * * @param request * @throws ParseException */ public void addLoadBalancerRouteHeader(Request request) { try { javax.sip.address.SipURI sipUri = SipFactories.addressFactory.createSipURI(null, loadBalancerToUse.getAddress().getHostAddress()); sipUri.setPort(loadBalancerToUse.getSipPort()); sipUri.setLrParam(); String transport = JainSipUtils.findTransport(request); sipUri.setTransportParam(transport); ExtendedListeningPoint listeningPoint = getSipNetworkInterfaceManager().findMatchingListeningPoint(transport, false); sipUri.setParameter(MessageDispatcher.ROUTE_PARAM_NODE_HOST, listeningPoint.getHost(JainSipUtils.findUsePublicAddress(getSipNetworkInterfaceManager(), request, listeningPoint))); sipUri.setParameter(MessageDispatcher.ROUTE_PARAM_NODE_PORT, "" + listeningPoint.getPort()); javax.sip.address.Address routeAddress = SipFactories.addressFactory.createAddress(sipUri); RouteHeader routeHeader = SipFactories.headerFactory.createRouteHeader(routeAddress); request.addFirst(routeHeader); } catch (ParseException e) { //this should never happen throw new IllegalArgumentException("Impossible to set the Load Balancer Route Header !", e); } catch (SipException e) { //this should never happen throw new IllegalArgumentException("Impossible to set the Load Balancer Route Header !", e); } } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { useLoadBalancer = in.readBoolean(); if(useLoadBalancer) { loadBalancerToUse = (BalancerDescription) in.readObject(); } sipApplicationDispatcher = StaticServiceHolder.sipStandardService.getSipApplicationDispatcher(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeBoolean(useLoadBalancer); if(useLoadBalancer) { out.writeObject(loadBalancerToUse); } } }
true
true
private SipServletRequest createSipServletRequest( SipApplicationSession sipAppSession, String method, Address from, Address to, String handler) throws ServletParseException { MobicentsSipApplicationSession mobicentsSipApplicationSession = (MobicentsSipApplicationSession) sipAppSession; // the request object with method, request URI, and From, To, Call-ID, // CSeq, Route headers filled in. Request requestToWrap = null; ContactHeader contactHeader = null; ToHeader toHeader = null; FromHeader fromHeader = null; CSeqHeader cseqHeader = null; CallIdHeader callIdHeader = null; MaxForwardsHeader maxForwardsHeader = null; // FIXME: Is this nough? // We need address from which this will be sent, also this one will be // default for contact and via String transport = ListeningPoint.UDP; // LETS CREATE OUR HEADERS javax.sip.address.Address fromAddress = null; try { // Issue 676 : Any component of the from and to URIs not allowed in the context of // SIP From and To headers are removed from the copies [refer Table 1, Section // 19.1.1, RFC3261] for(String param : forbbidenParams) { from.getURI().removeParameter(param); } // Issue 676 : from tags not removed so removing the tag from.removeParameter(TAG_PARAM); fromAddress = SipFactories.addressFactory .createAddress(((URIImpl)from.getURI()).getURI()); fromAddress.setDisplayName(from.getDisplayName()); fromHeader = SipFactories.headerFactory.createFromHeader(fromAddress, null); } catch (Exception pe) { throw new ServletParseException("Impossoible to parse the given From " + from.toString(), pe); } javax.sip.address.Address toAddress = null; try{ // Issue 676 : Any component of the from and to URIs not allowed in the context of // SIP From and To headers are removed from the copies [refer Table 1, Section // 19.1.1, RFC3261] for(String param : forbbidenParams) { to.getURI().removeParameter(param); } // Issue 676 : to tags not removed so removing the tag to.removeParameter(TAG_PARAM); toAddress = SipFactories.addressFactory .createAddress(((URIImpl)to.getURI()).getURI()); toAddress.setDisplayName(to.getDisplayName()); toHeader = SipFactories.headerFactory.createToHeader(toAddress, null); } catch (Exception pe) { throw new ServletParseException("Impossoible to parse the given To " + to.toString(), pe); } try { cseqHeader = SipFactories.headerFactory.createCSeqHeader(1L, method); // Fix provided by Hauke D. Issue 411 SipApplicationSessionKey sipApplicationSessionKey = mobicentsSipApplicationSession.getKey(); // if(sipApplicationSessionKey.isAppGeneratedKey()) { callIdHeader = SipFactories.headerFactory.createCallIdHeader( getSipNetworkInterfaceManager().getExtendedListeningPoints().next().getSipProvider().getNewCallId().getCallId()); // } else { // callIdHeader = SipFactories.headerFactory.createCallIdHeader( // sipApplicationSessionKey.getId()); // } maxForwardsHeader = SipFactories.headerFactory .createMaxForwardsHeader(JainSipUtils.MAX_FORWARD_HEADER_VALUE); URIImpl requestURI = (URIImpl)to.getURI().clone(); // copying address params into headers. Iterator<String> keys = to.getParameterNames(); while (keys.hasNext()) { String key = keys.next(); toHeader.setParameter(key, to.getParameter(key)); } keys = from.getParameterNames(); while (keys.hasNext()) { String key = keys.next(); fromHeader.setParameter(key, from.getParameter(key)); } //Issue 112 by folsson : no via header to add will be added when the request will be sent out List<Header> viaHeaders = new ArrayList<Header>(); requestToWrap = SipFactories.messageFactory.createRequest( requestURI.getURI(), method, callIdHeader, cseqHeader, fromHeader, toHeader, viaHeaders, maxForwardsHeader); //Adding default contact header for register if(Request.REGISTER.equalsIgnoreCase(method)) { String fromName = null; if(fromHeader.getAddress().getURI() instanceof javax.sip.address.SipURI) { fromName = ((javax.sip.address.SipURI)fromHeader.getAddress().getURI()).getUser(); } // Create the contact name address. contactHeader = null; // if a sip load balancer is present in front of the server, the contact header is the one from the sip lb // so that the subsequent requests can be failed over if(useLoadBalancer) { javax.sip.address.SipURI sipURI = SipFactories.addressFactory.createSipURI(fromName, loadBalancerToUse.getAddress().getHostAddress()); sipURI.setHost(loadBalancerToUse.getAddress().getHostAddress()); sipURI.setPort(loadBalancerToUse.getSipPort()); sipURI.setTransportParam(transport); javax.sip.address.Address contactAddress = SipFactories.addressFactory.createAddress(sipURI); if(fromName != null && fromName.length() > 0) { contactAddress.setDisplayName(fromName); } contactHeader = SipFactories.headerFactory.createContactHeader(contactAddress); } else { contactHeader = JainSipUtils.createContactHeader(getSipNetworkInterfaceManager(), requestToWrap, fromName); } } // Add all headers if(contactHeader != null) { requestToWrap.addHeader(contactHeader); } fromHeader.setTag(ApplicationRoutingHeaderComposer.getHash(sipApplicationDispatcher, sipAppSession.getApplicationName(), sipApplicationSessionKey.getId())); SipSessionKey key = SessionManagerUtil.getSipSessionKey( mobicentsSipApplicationSession.getKey().getId(), mobicentsSipApplicationSession.getKey().getApplicationName(), requestToWrap, false); MobicentsSipSession session = ((SipManager)mobicentsSipApplicationSession.getSipContext().getManager()). getSipSession(key, true, this, mobicentsSipApplicationSession); session.setHandler(handler); session.setLocalParty(new AddressImpl(fromAddress, null, false)); session.setRemoteParty(new AddressImpl(toAddress, null, false)); SipServletRequest retVal = new SipServletRequestImpl( requestToWrap, this, session, null, null, JainSipUtils.dialogCreatingMethods.contains(method)); return retVal; } catch (Exception e) { logger.error("Error creating sipServletRequest", e); } return null; }
private SipServletRequest createSipServletRequest( SipApplicationSession sipAppSession, String method, Address from, Address to, String handler) throws ServletParseException { MobicentsSipApplicationSession mobicentsSipApplicationSession = (MobicentsSipApplicationSession) sipAppSession; // the request object with method, request URI, and From, To, Call-ID, // CSeq, Route headers filled in. Request requestToWrap = null; ContactHeader contactHeader = null; ToHeader toHeader = null; FromHeader fromHeader = null; CSeqHeader cseqHeader = null; CallIdHeader callIdHeader = null; MaxForwardsHeader maxForwardsHeader = null; // FIXME: Is this nough? // We need address from which this will be sent, also this one will be // default for contact and via String transport = ListeningPoint.UDP; // LETS CREATE OUR HEADERS javax.sip.address.Address fromAddress = null; try { // Issue 676 : Any component of the from and to URIs not allowed in the context of // SIP From and To headers are removed from the copies [refer Table 1, Section // 19.1.1, RFC3261] for(String param : forbbidenParams) { from.getURI().removeParameter(param); } // Issue 676 : from tags not removed so removing the tag from.removeParameter(TAG_PARAM); fromAddress = SipFactories.addressFactory .createAddress(((URIImpl)from.getURI()).getURI()); fromAddress.setDisplayName(from.getDisplayName()); fromHeader = SipFactories.headerFactory.createFromHeader(fromAddress, null); } catch (Exception pe) { throw new ServletParseException("Impossoible to parse the given From " + from.toString(), pe); } javax.sip.address.Address toAddress = null; try{ // Issue 676 : Any component of the from and to URIs not allowed in the context of // SIP From and To headers are removed from the copies [refer Table 1, Section // 19.1.1, RFC3261] for(String param : forbbidenParams) { to.getURI().removeParameter(param); } // Issue 676 : to tags not removed so removing the tag to.removeParameter(TAG_PARAM); toAddress = SipFactories.addressFactory .createAddress(((URIImpl)to.getURI()).getURI()); toAddress.setDisplayName(to.getDisplayName()); toHeader = SipFactories.headerFactory.createToHeader(toAddress, null); } catch (Exception pe) { throw new ServletParseException("Impossoible to parse the given To " + to.toString(), pe); } try { cseqHeader = SipFactories.headerFactory.createCSeqHeader(1L, method); // Fix provided by Hauke D. Issue 411 SipApplicationSessionKey sipApplicationSessionKey = mobicentsSipApplicationSession.getKey(); // if(sipApplicationSessionKey.isAppGeneratedKey()) { callIdHeader = SipFactories.headerFactory.createCallIdHeader( getSipNetworkInterfaceManager().getExtendedListeningPoints().next().getSipProvider().getNewCallId().getCallId()); // } else { // callIdHeader = SipFactories.headerFactory.createCallIdHeader( // sipApplicationSessionKey.getId()); // } maxForwardsHeader = SipFactories.headerFactory .createMaxForwardsHeader(JainSipUtils.MAX_FORWARD_HEADER_VALUE); URIImpl requestURI = (URIImpl)to.getURI().clone(); // copying address params into headers. Iterator<String> keys = to.getParameterNames(); while (keys.hasNext()) { String key = keys.next(); toHeader.setParameter(key, to.getParameter(key)); } keys = from.getParameterNames(); while (keys.hasNext()) { String key = keys.next(); fromHeader.setParameter(key, from.getParameter(key)); } //Issue 112 by folsson : no via header to add will be added when the request will be sent out List<Header> viaHeaders = new ArrayList<Header>(); requestToWrap = SipFactories.messageFactory.createRequest( requestURI.getURI(), method, callIdHeader, cseqHeader, fromHeader, toHeader, viaHeaders, maxForwardsHeader); //Adding default contact header for register if(Request.REGISTER.equalsIgnoreCase(method) || Request.INVITE.equalsIgnoreCase(method)) { String fromName = null; if(fromHeader.getAddress().getURI() instanceof javax.sip.address.SipURI) { fromName = ((javax.sip.address.SipURI)fromHeader.getAddress().getURI()).getUser(); } // Create the contact name address. contactHeader = null; // if a sip load balancer is present in front of the server, the contact header is the one from the sip lb // so that the subsequent requests can be failed over if(useLoadBalancer) { javax.sip.address.SipURI sipURI = SipFactories.addressFactory.createSipURI(fromName, loadBalancerToUse.getAddress().getHostAddress()); sipURI.setHost(loadBalancerToUse.getAddress().getHostAddress()); sipURI.setPort(loadBalancerToUse.getSipPort()); sipURI.setTransportParam(transport); javax.sip.address.Address contactAddress = SipFactories.addressFactory.createAddress(sipURI); if(fromName != null && fromName.length() > 0) { contactAddress.setDisplayName(fromName); } contactHeader = SipFactories.headerFactory.createContactHeader(contactAddress); } else { contactHeader = JainSipUtils.createContactHeader(getSipNetworkInterfaceManager(), requestToWrap, fromName); } } // Add all headers if(contactHeader != null) { requestToWrap.addHeader(contactHeader); } fromHeader.setTag(ApplicationRoutingHeaderComposer.getHash(sipApplicationDispatcher, sipAppSession.getApplicationName(), sipApplicationSessionKey.getId())); SipSessionKey key = SessionManagerUtil.getSipSessionKey( mobicentsSipApplicationSession.getKey().getId(), mobicentsSipApplicationSession.getKey().getApplicationName(), requestToWrap, false); MobicentsSipSession session = ((SipManager)mobicentsSipApplicationSession.getSipContext().getManager()). getSipSession(key, true, this, mobicentsSipApplicationSession); session.setHandler(handler); session.setLocalParty(new AddressImpl(fromAddress, null, false)); session.setRemoteParty(new AddressImpl(toAddress, null, false)); SipServletRequest retVal = new SipServletRequestImpl( requestToWrap, this, session, null, null, JainSipUtils.dialogCreatingMethods.contains(method)); return retVal; } catch (Exception e) { logger.error("Error creating sipServletRequest", e); } return null; }
diff --git a/mes-plugins/mes-plugins-basic/src/main/java/com/qcadoo/mes/basic/listeners/CompaniesListListeners.java b/mes-plugins/mes-plugins-basic/src/main/java/com/qcadoo/mes/basic/listeners/CompaniesListListeners.java index 73cb6bf706..0dbff01479 100644 --- a/mes-plugins/mes-plugins-basic/src/main/java/com/qcadoo/mes/basic/listeners/CompaniesListListeners.java +++ b/mes-plugins/mes-plugins-basic/src/main/java/com/qcadoo/mes/basic/listeners/CompaniesListListeners.java @@ -1,77 +1,81 @@ /** * *************************************************************************** * Copyright (c) 2010 Qcadoo Limited * Project: Qcadoo MES * Version: 1.2.0 * * This file is part of Qcadoo. * * Qcadoo 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, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *************************************************************************** */ package com.qcadoo.mes.basic.listeners; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.qcadoo.localization.api.TranslationService; import com.qcadoo.mes.basic.ParameterService; import com.qcadoo.mes.basic.constants.ParameterFields; import com.qcadoo.model.api.Entity; import com.qcadoo.view.api.ComponentState; import com.qcadoo.view.api.ViewDefinitionState; import com.qcadoo.view.api.components.GridComponent; import com.qcadoo.view.api.components.WindowComponent; import com.qcadoo.view.api.ribbon.RibbonActionItem; import com.qcadoo.view.api.ribbon.RibbonGroup; @Service public class CompaniesListListeners { @Autowired private ParameterService parameterService; @Autowired private TranslationService translationService; public void checkIfIsOwner(final ViewDefinitionState view, final ComponentState state, final String[] args) { Entity parameter = parameterService.getParameter(); Entity owner = parameter.getBelongsToField(ParameterFields.COMPANY); + if (owner == null) { + disabledButton(view, true); + return; + } boolean enabled = true; GridComponent grid = (GridComponent) view.getComponentByReference("grid"); List<Entity> companies = grid.getSelectedEntities(); for (Entity company : companies) { if (company.getId().equals(owner.getId())) { enabled = false; } } disabledButton(view, enabled); } private void disabledButton(final ViewDefinitionState view, final boolean enabled) { WindowComponent window = (WindowComponent) view.getComponentByReference("window"); RibbonGroup actions = (RibbonGroup) window.getRibbon().getGroupByName("actions"); RibbonActionItem delete = actions.getItemByName("delete"); delete.setEnabled(enabled); if (enabled) { delete.setMessage(null); } else { delete.setMessage(translationService.translate("basic.company.isOwner", view.getLocale())); } delete.requestUpdate(true); } }
true
true
public void checkIfIsOwner(final ViewDefinitionState view, final ComponentState state, final String[] args) { Entity parameter = parameterService.getParameter(); Entity owner = parameter.getBelongsToField(ParameterFields.COMPANY); boolean enabled = true; GridComponent grid = (GridComponent) view.getComponentByReference("grid"); List<Entity> companies = grid.getSelectedEntities(); for (Entity company : companies) { if (company.getId().equals(owner.getId())) { enabled = false; } } disabledButton(view, enabled); }
public void checkIfIsOwner(final ViewDefinitionState view, final ComponentState state, final String[] args) { Entity parameter = parameterService.getParameter(); Entity owner = parameter.getBelongsToField(ParameterFields.COMPANY); if (owner == null) { disabledButton(view, true); return; } boolean enabled = true; GridComponent grid = (GridComponent) view.getComponentByReference("grid"); List<Entity> companies = grid.getSelectedEntities(); for (Entity company : companies) { if (company.getId().equals(owner.getId())) { enabled = false; } } disabledButton(view, enabled); }
diff --git a/src/main/java/se/unbound/tapestry/tagselect/components/TagSelect.java b/src/main/java/se/unbound/tapestry/tagselect/components/TagSelect.java index 49508eb..2e32035 100644 --- a/src/main/java/se/unbound/tapestry/tagselect/components/TagSelect.java +++ b/src/main/java/se/unbound/tapestry/tagselect/components/TagSelect.java @@ -1,330 +1,330 @@ package se.unbound.tapestry.tagselect.components; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.lang.StringUtils; import org.apache.tapestry5.ComponentEventCallback; import org.apache.tapestry5.ComponentResources; import org.apache.tapestry5.ContentType; import org.apache.tapestry5.EventConstants; import org.apache.tapestry5.Link; import org.apache.tapestry5.MarkupWriter; import org.apache.tapestry5.OptionModel; import org.apache.tapestry5.Renderable; import org.apache.tapestry5.SelectModel; import org.apache.tapestry5.annotations.Events; import org.apache.tapestry5.annotations.Import; import org.apache.tapestry5.annotations.Parameter; import org.apache.tapestry5.annotations.Persist; import org.apache.tapestry5.annotations.SetupRender; import org.apache.tapestry5.corelib.base.AbstractField; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.ioc.services.TypeCoercer; import org.apache.tapestry5.json.JSONObject; import org.apache.tapestry5.services.MarkupWriterFactory; import org.apache.tapestry5.services.Request; import org.apache.tapestry5.services.ResponseRenderer; import org.apache.tapestry5.services.javascript.JavaScriptSupport; import org.apache.tapestry5.util.TextStreamResponse; import se.unbound.tapestry.tagselect.AutoCompleteCallback; import se.unbound.tapestry.tagselect.LabelAwareValueEncoder; /** * Select component similar to the version select in Jira. */ @Import(library = { "${tapestry.scriptaculous}/controls.js", "TagSelect.js" }, stylesheet = "TagSelect.css") @Events(EventConstants.PROVIDE_COMPLETIONS) public class TagSelect extends AbstractField { static final String EVENT_NAME = "autocomplete"; private static final String PARAM_NAME = "u:input"; @Inject private ComponentResources resources; @Inject private JavaScriptSupport javaScriptSupport; @Inject private Request request; @Inject private TypeCoercer coercer; @Inject private MarkupWriterFactory factory; @Inject private ResponseRenderer responseRenderer; @Parameter(required = true) private Object value; /** * Allows a specific implementation of {@link LabelAwareValueEncoder} to be supplied. This is used to create * client-side string values and labels for the different options. */ @Parameter private LabelAwareValueEncoder<Object> encoder; @Persist private AtomicReference<SelectModel> model; /** * Called by Tapestry before rendering is started. */ @SetupRender public void setupRender() { this.model = new AtomicReference<SelectModel>(); } public Renderable getRenderer() { return new TagSelectRenderer(this.getClientId(), this.getControlName()); } Object onAutocomplete() { final String input = this.request.getParameter(TagSelect.PARAM_NAME); final String currentValues = this.request.getParameter("values"); final ComponentEventCallback<SelectModel> callback = new AutoCompleteCallback(this.model, this.coercer); this.resources.triggerEvent(EventConstants.PROVIDE_COMPLETIONS, new Object[] { input }, callback); final ContentType contentType = this.responseRenderer.findContentType(this); final MarkupWriter writer = this.factory.newPartialMarkupWriter(contentType); this.generateResponseMarkup(writer, this.model.get(), currentValues); return new TextStreamResponse(contentType.toString(), writer.toString()); } @Override protected void processSubmission(final String elementName) { final String parameterValue = this.request.getParameter(elementName + "-values"); final String[] items = parameterValue.split(";"); this.updateValue(items); } private void updateValue(final String[] items) { if (this.value instanceof Collection<?>) { final Collection<Object> collection = (Collection<Object>) this.value; collection.clear(); for (final String string : items) { if (StringUtils.isNotBlank(string)) { collection.add(this.toValue(string)); } } } else { this.value = this.toValue(items[0]); } } /** * Generates the markup response that will be returned to the client; this should be an &lt;ul&gt; element with * nested &lt;li&gt; elements. Subclasses may override this to produce more involved markup (including images and * CSS class attributes). * * @param writer to write the list to. * @param selectModel to write each option. * @param currentValues The currently selected values in the tagselect. */ protected void generateResponseMarkup(final MarkupWriter writer, final SelectModel selectModel, final String currentValues) { final List<String> values = Arrays.asList(currentValues.split(";")); writer.element("ul"); if (selectModel != null) { for (final OptionModel o : selectModel.getOptions()) { final String clientValue = this.toClient(o.getValue()); if (!values.contains(clientValue)) { writer.element("li", "id", clientValue); writer.write(o.getLabel()); writer.end(); } } } // ul writer.end(); } /** * Get the client value. * * @param object The object to get the client value for. * @return The client value of the object. */ public String toClient(final Object object) { if (this.encoder != null) { return this.encoder.toClient(object); } return String.valueOf(object); } private Object toValue(final String clientValue) { if (this.encoder != null) { return this.encoder.toValue(clientValue); } return clientValue; } /** * Renderable for creating the markup necessary for the select component. */ public class TagSelectRenderer implements Renderable { private final String clientId; private final String controlName; /** * Constructs a new {@link TagSelectRenderer}. * * @param clientId The clientId of the component. * @param controlName The controlName of the component. */ public TagSelectRenderer(final String clientId, final String controlName) { this.clientId = clientId; this.controlName = controlName; } @Override public void render(final MarkupWriter writer) { writer.element("input", "type", "hidden", "id", this.clientId + "-values", "name", this.controlName + "-values", "value", this.getSelectedValue(TagSelect.this.value)); writer.end(); writer.element("textarea", "autocomplete", "off", "id", this.clientId, "class", "u-textarea"); if (this.isSingleSelect(TagSelect.this.value)) { writer.attributes("u:type", "single"); } writer.end(); final String menuId = this.clientId + ":menu"; writer.element("div", "id", menuId, "class", "u-autocomplete-menu"); writer.end(); writer.element("div", "id", this.clientId + "-tag-container", "class", "u-tag-container"); writer.element("ul", "id", this.clientId + "-tags", "class", "u-tags"); final Collection<Object> collection = this.getSelectedTags(TagSelect.this.value); for (final Object each : collection) { this.writeSelectedItem(writer, each); } writer.end(); writer.end(); TagSelect.this.javaScriptSupport.addScript( "TagSelect.updatePadding('%s');", this.clientId); writer.element("div", "class", "u-clear"); writer.element("em", "id", this.clientId + "trigger", "class", "u-trigger", "onclick", - "TagSelect.triggerCompletion(" + this.clientId + ")"); + "TagSelect.triggerCompletion($('" + this.clientId + "'))"); writer.end(); writer.end(); TagSelect.this.javaScriptSupport.addScript( "TagSelect.registerKeyevent('%s');", this.clientId); TagSelect.this.resources.renderInformalParameters(writer); final Link link = TagSelect.this.resources.createEventLink(TagSelect.EVENT_NAME); final JSONObject config = new JSONObject(); config.put("paramName", TagSelect.PARAM_NAME); config.put("minChars", "0"); final String methodAfterUpdate = "function (li) { TagSelect.addSelection('" + this.clientId + "', li); }"; config.put("updateElement", methodAfterUpdate); final String callback = "function(field, query) { return query + '&values=' + $('" + this.clientId + "-values').value; }"; config.put("callback", callback); String configString = config.toString(); configString = configString.replace("\"" + methodAfterUpdate + "\"", methodAfterUpdate); configString = configString.replace("\"" + callback + "\"", callback); TagSelect.this.javaScriptSupport.addScript( "new Ajax.Autocompleter('%s', '%s', '%s', %s);", this.clientId, menuId, link.toAbsoluteURI(), configString); } private boolean isSingleSelect(final Object selectedValue) { return !(selectedValue instanceof Collection<?>); } private Collection<Object> getSelectedTags(final Object selectedValue) { final Collection<Object> selectedTags = new ArrayList<Object>(); if (selectedValue instanceof Collection<?>) { selectedTags.addAll((Collection<Object>) selectedValue); } else if (selectedValue != null && this.isNotBlank(selectedValue)) { selectedTags.add(selectedValue); } return selectedTags; } private boolean isNotBlank(final Object selectedValue) { final String stringValue = String.valueOf(selectedValue); return !stringValue.trim().isEmpty(); } private String getSelectedValue(final Object selectedValue) { String result = ""; if (selectedValue instanceof Collection<?>) { result = this.joinValue((Collection<Object>) selectedValue); } else if (selectedValue != null) { if (TagSelect.this.encoder != null) { result = TagSelect.this.toClient(selectedValue); } else { result = String.valueOf(selectedValue); } } return result; } private String joinValue(final Collection<Object> values) { final StringBuilder builder = new StringBuilder(); for (final Object each : values) { if (builder.length() > 0) { builder.append(";"); } builder.append(TagSelect.this.toClient(each)); } return builder.toString(); } private void writeSelectedItem(final MarkupWriter writer, final Object item) { final String clientValue = TagSelect.this.toClient(item); final String label = this.getLabel(item); final Long itemId = System.nanoTime(); writer.element("li", "class", "u-tag", "id", "u-tag-" + itemId); writer.element("button", "type", "button", "class", "u-tag-button"); writer.element("span"); writer.element("span", "class", "u-tag-value"); writer.write(label); writer.end(); writer.end(); writer.end(); writer.element("em", "class", "u-tag-remove", "onclick", "TagSelect.removeSelection('" + this.clientId + "', 'u-tag-" + itemId + "', '" + clientValue + "')"); writer.end(); writer.end(); } private String getLabel(final Object item) { if (TagSelect.this.encoder != null) { return TagSelect.this.encoder.getLabel(item); } return String.valueOf(item); } } }
true
true
public void render(final MarkupWriter writer) { writer.element("input", "type", "hidden", "id", this.clientId + "-values", "name", this.controlName + "-values", "value", this.getSelectedValue(TagSelect.this.value)); writer.end(); writer.element("textarea", "autocomplete", "off", "id", this.clientId, "class", "u-textarea"); if (this.isSingleSelect(TagSelect.this.value)) { writer.attributes("u:type", "single"); } writer.end(); final String menuId = this.clientId + ":menu"; writer.element("div", "id", menuId, "class", "u-autocomplete-menu"); writer.end(); writer.element("div", "id", this.clientId + "-tag-container", "class", "u-tag-container"); writer.element("ul", "id", this.clientId + "-tags", "class", "u-tags"); final Collection<Object> collection = this.getSelectedTags(TagSelect.this.value); for (final Object each : collection) { this.writeSelectedItem(writer, each); } writer.end(); writer.end(); TagSelect.this.javaScriptSupport.addScript( "TagSelect.updatePadding('%s');", this.clientId); writer.element("div", "class", "u-clear"); writer.element("em", "id", this.clientId + "trigger", "class", "u-trigger", "onclick", "TagSelect.triggerCompletion(" + this.clientId + ")"); writer.end(); writer.end(); TagSelect.this.javaScriptSupport.addScript( "TagSelect.registerKeyevent('%s');", this.clientId); TagSelect.this.resources.renderInformalParameters(writer); final Link link = TagSelect.this.resources.createEventLink(TagSelect.EVENT_NAME); final JSONObject config = new JSONObject(); config.put("paramName", TagSelect.PARAM_NAME); config.put("minChars", "0"); final String methodAfterUpdate = "function (li) { TagSelect.addSelection('" + this.clientId + "', li); }"; config.put("updateElement", methodAfterUpdate); final String callback = "function(field, query) { return query + '&values=' + $('" + this.clientId + "-values').value; }"; config.put("callback", callback); String configString = config.toString(); configString = configString.replace("\"" + methodAfterUpdate + "\"", methodAfterUpdate); configString = configString.replace("\"" + callback + "\"", callback); TagSelect.this.javaScriptSupport.addScript( "new Ajax.Autocompleter('%s', '%s', '%s', %s);", this.clientId, menuId, link.toAbsoluteURI(), configString); }
public void render(final MarkupWriter writer) { writer.element("input", "type", "hidden", "id", this.clientId + "-values", "name", this.controlName + "-values", "value", this.getSelectedValue(TagSelect.this.value)); writer.end(); writer.element("textarea", "autocomplete", "off", "id", this.clientId, "class", "u-textarea"); if (this.isSingleSelect(TagSelect.this.value)) { writer.attributes("u:type", "single"); } writer.end(); final String menuId = this.clientId + ":menu"; writer.element("div", "id", menuId, "class", "u-autocomplete-menu"); writer.end(); writer.element("div", "id", this.clientId + "-tag-container", "class", "u-tag-container"); writer.element("ul", "id", this.clientId + "-tags", "class", "u-tags"); final Collection<Object> collection = this.getSelectedTags(TagSelect.this.value); for (final Object each : collection) { this.writeSelectedItem(writer, each); } writer.end(); writer.end(); TagSelect.this.javaScriptSupport.addScript( "TagSelect.updatePadding('%s');", this.clientId); writer.element("div", "class", "u-clear"); writer.element("em", "id", this.clientId + "trigger", "class", "u-trigger", "onclick", "TagSelect.triggerCompletion($('" + this.clientId + "'))"); writer.end(); writer.end(); TagSelect.this.javaScriptSupport.addScript( "TagSelect.registerKeyevent('%s');", this.clientId); TagSelect.this.resources.renderInformalParameters(writer); final Link link = TagSelect.this.resources.createEventLink(TagSelect.EVENT_NAME); final JSONObject config = new JSONObject(); config.put("paramName", TagSelect.PARAM_NAME); config.put("minChars", "0"); final String methodAfterUpdate = "function (li) { TagSelect.addSelection('" + this.clientId + "', li); }"; config.put("updateElement", methodAfterUpdate); final String callback = "function(field, query) { return query + '&values=' + $('" + this.clientId + "-values').value; }"; config.put("callback", callback); String configString = config.toString(); configString = configString.replace("\"" + methodAfterUpdate + "\"", methodAfterUpdate); configString = configString.replace("\"" + callback + "\"", callback); TagSelect.this.javaScriptSupport.addScript( "new Ajax.Autocompleter('%s', '%s', '%s', %s);", this.clientId, menuId, link.toAbsoluteURI(), configString); }
diff --git a/src/java/DefaultQueryTranslator.java b/src/java/DefaultQueryTranslator.java index 87b4070..c32c895 100644 --- a/src/java/DefaultQueryTranslator.java +++ b/src/java/DefaultQueryTranslator.java @@ -1,170 +1,170 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.*; import java.io.*; import org.apache.lucene.search.*; import org.apache.lucene.analysis.*; import org.apache.lucene.queryParser.*; import org.apache.lucene.document.*; import org.apache.lucene.index.*; import org.apache.lucene.util.Version; public class DefaultQueryTranslator { public BooleanQuery translate( String query ) { String[] splitOnQuotes = query.split( "[\"]" ); List<String> terms = new ArrayList<String>( 8 ); List<String> minus = new ArrayList<String>( 8 ); for ( int i = 0 ; i < splitOnQuotes.length ; i++ ) { String qterm = splitOnQuotes[i]; if ( i % 2 == 1 ) { // If a '-' appears inside a quoted phrase, remove it. qterm = qterm.replace( '-', ' ' ); } // HACK: To handle "don't" -> "dont" and such. qterm = qterm.replace( "'", "" ); // Use the Java regex syntax: // \p{L} -- All Unicode letters // \p{N} -- All Unicode numbers - // Anything that is not a letter|number is stripped. - qterm = qterm.replaceAll( "[^\\p{L}\\p{N}']", " " ); + // Anything that is not a letter|number or '-' is stripped. + qterm = qterm.replaceAll( "[^\\p{L}\\p{N}-']", " " ); for ( String t : qterm.split( "\\s+" ) ) { if ( t.length() == 0 ) continue; if ( t.charAt( 0 ) == '-' ) { String m = t.replaceFirst( "[-]+", "" ); if ( m.trim().length( ) > 0 ) { minus.add( m.toLowerCase( ) ); } } else { terms.add( t.toLowerCase( ) ); } } } BooleanQuery bq = new BooleanQuery( ); fieldGroup( bq, terms, "url" , (float) 4.0 ); fieldGroup( bq, terms, "title", (float) 3.0 ); fieldGroup( bq, terms, "content", (float) 1.5 ); if ( terms.size( ) > 1 ) mixAndMatch( bq, terms ); minuses( bq, minus ); BooleanQuery q = new BooleanQuery( ); q.add( bq, BooleanClause.Occur.MUST ); return q; } public void fieldGroup( BooleanQuery bq, List<String> terms, String field, float boost ) { BooleanQuery group = new BooleanQuery( ); for ( String t : terms ) { TermQuery tq = new TermQuery( new Term( field, t ) ); tq.setBoost( boost ); group.add( tq, BooleanClause.Occur.MUST ); } bq.add( group, BooleanClause.Occur.SHOULD ); } public void mixAndMatch( BooleanQuery bq, List<String> terms ) { for ( int i = 0 ; i < terms.size() ; i++ ) { BooleanQuery group = new BooleanQuery( ); TermQuery tq = new TermQuery( new Term( "title", terms.get(i) ) ); group.add( tq, BooleanClause.Occur.MUST ); for ( int j = 0 ; j < terms.size() ; j++ ) { if ( j == i ) continue ; tq = new TermQuery( new Term( "content", terms.get(j) ) ); group.add( tq, BooleanClause.Occur.MUST ); } bq.add( group, BooleanClause.Occur.SHOULD ); } } public void minuses( BooleanQuery bq, List<String> minus ) { for ( String m : minus ) { bq.add( new TermQuery( new Term( "url" , m ) ), BooleanClause.Occur.MUST_NOT ); bq.add( new TermQuery( new Term( "title" , m ) ), BooleanClause.Occur.MUST_NOT ); bq.add( new TermQuery( new Term( "content", m ) ), BooleanClause.Occur.MUST_NOT ); } } public void addGroup( BooleanQuery bq, String field, String[] values ) { if ( values == null || values.length == 0 ) { return ; } BooleanQuery group = new BooleanQuery( ); for ( String value : values ) { TermQuery tq = new TermQuery( new Term( field, value ) ); group.add( tq, BooleanClause.Occur.SHOULD ); } bq.add( group, BooleanClause.Occur.MUST ); } public static void main( String[] args ) throws Exception { if ( args.length != 1 ) { System.out.println( "QueryTranslator <query>" ); System.exit( 1 ); } String query = args[0]; DefaultQueryTranslator translator = new DefaultQueryTranslator( ); BooleanQuery q = translator.translate( query ); System.out.println( "q: " + q.toString( ) ); } }
true
true
public BooleanQuery translate( String query ) { String[] splitOnQuotes = query.split( "[\"]" ); List<String> terms = new ArrayList<String>( 8 ); List<String> minus = new ArrayList<String>( 8 ); for ( int i = 0 ; i < splitOnQuotes.length ; i++ ) { String qterm = splitOnQuotes[i]; if ( i % 2 == 1 ) { // If a '-' appears inside a quoted phrase, remove it. qterm = qterm.replace( '-', ' ' ); } // HACK: To handle "don't" -> "dont" and such. qterm = qterm.replace( "'", "" ); // Use the Java regex syntax: // \p{L} -- All Unicode letters // \p{N} -- All Unicode numbers // Anything that is not a letter|number is stripped. qterm = qterm.replaceAll( "[^\\p{L}\\p{N}']", " " ); for ( String t : qterm.split( "\\s+" ) ) { if ( t.length() == 0 ) continue; if ( t.charAt( 0 ) == '-' ) { String m = t.replaceFirst( "[-]+", "" ); if ( m.trim().length( ) > 0 ) { minus.add( m.toLowerCase( ) ); } } else { terms.add( t.toLowerCase( ) ); } } } BooleanQuery bq = new BooleanQuery( ); fieldGroup( bq, terms, "url" , (float) 4.0 ); fieldGroup( bq, terms, "title", (float) 3.0 ); fieldGroup( bq, terms, "content", (float) 1.5 ); if ( terms.size( ) > 1 ) mixAndMatch( bq, terms ); minuses( bq, minus ); BooleanQuery q = new BooleanQuery( ); q.add( bq, BooleanClause.Occur.MUST ); return q; }
public BooleanQuery translate( String query ) { String[] splitOnQuotes = query.split( "[\"]" ); List<String> terms = new ArrayList<String>( 8 ); List<String> minus = new ArrayList<String>( 8 ); for ( int i = 0 ; i < splitOnQuotes.length ; i++ ) { String qterm = splitOnQuotes[i]; if ( i % 2 == 1 ) { // If a '-' appears inside a quoted phrase, remove it. qterm = qterm.replace( '-', ' ' ); } // HACK: To handle "don't" -> "dont" and such. qterm = qterm.replace( "'", "" ); // Use the Java regex syntax: // \p{L} -- All Unicode letters // \p{N} -- All Unicode numbers // Anything that is not a letter|number or '-' is stripped. qterm = qterm.replaceAll( "[^\\p{L}\\p{N}-']", " " ); for ( String t : qterm.split( "\\s+" ) ) { if ( t.length() == 0 ) continue; if ( t.charAt( 0 ) == '-' ) { String m = t.replaceFirst( "[-]+", "" ); if ( m.trim().length( ) > 0 ) { minus.add( m.toLowerCase( ) ); } } else { terms.add( t.toLowerCase( ) ); } } } BooleanQuery bq = new BooleanQuery( ); fieldGroup( bq, terms, "url" , (float) 4.0 ); fieldGroup( bq, terms, "title", (float) 3.0 ); fieldGroup( bq, terms, "content", (float) 1.5 ); if ( terms.size( ) > 1 ) mixAndMatch( bq, terms ); minuses( bq, minus ); BooleanQuery q = new BooleanQuery( ); q.add( bq, BooleanClause.Occur.MUST ); return q; }
diff --git a/AeroControl/src/com/aero/control/helpers/settingsHelper.java b/AeroControl/src/com/aero/control/helpers/settingsHelper.java index 1dbefb5..3524f38 100644 --- a/AeroControl/src/com/aero/control/helpers/settingsHelper.java +++ b/AeroControl/src/com/aero/control/helpers/settingsHelper.java @@ -1,440 +1,446 @@ package com.aero.control.helpers; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import java.io.File; import java.util.ArrayList; import java.util.HashSet; /** * Created by Alexander Christ on 05.01.14. */ public class settingsHelper { public static final String CPU_BASE_PATH = "/sys/devices/system/cpu/cpu"; public static final String CPU_GOV_BASE = "/sys/devices/system/cpu/cpufreq/"; public static final String CURRENT_GOV_AVAILABLE = "/cpufreq/scaling_governor"; public static final String CPU_MAX_FREQ = "/cpufreq/scaling_max_freq"; public static final String CPU_MIN_FREQ = "/cpufreq/scaling_min_freq"; public static final String[] GPU_FILES = {"/sys/kernel/gpu_control/max_freq", /* Defy 2.6 Kernel */ "/sys/class/kgsl/kgsl-3d0/max_gpuclk", /* Adreno GPUs */ "/sys/devices/platform/omap/pvrsrvkm.0/sgx_fck_rate" /* Defy 3.0 Kernel */}; public static final String GPU_CONTROL_ACTIVE = "/sys/kernel/gpu_control/gpu_control_active"; public static final String DISPLAY_COLOR = "/sys/class/misc/display_control/display_brightness_value"; public static final String SWEEP2WAKE = "/sys/android_touch/sweep2wake"; public static final String GOV_IO_FILE = "/sys/block/mmcblk0/queue/scheduler"; public static final String GOV_IO_PARAMETER = "/sys/block/mmcblk0/queue/iosched"; public static final String DYANMIC_FSYNC = "/sys/kernel/dyn_fsync/Dyn_fsync_active"; public static final String WRITEBACK = "/sys/devices/virtual/misc/writeback/writeback_enabled"; public static final String DALVIK_TWEAK = "/proc/sys/vm"; public static final String PREF_CURRENT_GOV_AVAILABLE = "set_governor"; public static final String PREF_CPU_MAX_FREQ = "max_frequency"; public static final String PREF_CPU_MIN_FREQ = "min_frequency"; public static final String PREF_CPU_COMMANDS = "cpu_commands"; public static final String PREF_GPU_FREQ_MAX = "gpu_max_freq"; public static final String PREF_GPU_CONTROL_ACTIVE = "gpu_control_enable"; public static final String PREF_DISPLAY_COLOR = "display_control"; public static final String PREF_SWEEP2WAKE = "sweeptowake"; public static final String PERF_COLOR_CONTROL = "/sys/devices/platform/kcal_ctrl.0/kcal"; public static final String PREF_GOV_IO_FILE = "io_scheduler_list"; public static final String PREF_DYANMIC_FSYNC = "dynFsync"; public static final String PREF_WRITEBACK = "writeback"; public static final String PREF_HOTPLUG = "/sys/kernel/hotplug_control"; public static final String PREF_GPU_GOV = "/sys/module/msm_kgsl_core/parameters"; public static final String PREF_VOLTAGE_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table"; public static final String MISC_VIBRATOR_CONTROL = "/sys/devices/virtual/timed_output/vibrator/vtg_level"; private static final String MISC_THERMAL_CONTROL = "/sys/module/msm_thermal/parameters/temp_threshold"; private SharedPreferences prefs; private String gpu_file; public static final int mNumCpus = Runtime.getRuntime().availableProcessors(); private static final shellHelper shell = new shellHelper(); private static final ArrayList<String> defaultProfile = new ArrayList<String>(); public void setSettings(final Context context, final String Profile) { new Thread(new Runnable() { @Override public void run() { // We need to sleep here for a short while for the kernel shell.setOverclockAddress(); try { Thread.sleep(2000); } catch (InterruptedException e) { Log.e("Aero", "Something went really wrong...", e); } // Apply all our saved values; doBackground(context, Profile); } }).start(); } private void doBackground(Context context, String Profile) { if (Profile == null) prefs = PreferenceManager.getDefaultSharedPreferences(context); else prefs = context.getSharedPreferences(Profile, Context.MODE_PRIVATE); // GET CPU VALUES AND COMMANDS FROM PREFERENCES String cpu_max = prefs.getString(PREF_CPU_MAX_FREQ, null); String cpu_min = prefs.getString(PREF_CPU_MIN_FREQ, null); String cpu_gov = prefs.getString(PREF_CURRENT_GOV_AVAILABLE, null); // Overclocking.... try { HashSet<String> hashcpu_cmd = (HashSet<String>) prefs.getStringSet(PREF_CPU_COMMANDS, null); if (hashcpu_cmd != null) { for (String cmd : hashcpu_cmd) { shell.queueWork(cmd); } } } catch (ClassCastException e) { // HashSet didn't work, so we make a fallback; String cpu_cmd = prefs.getString(PREF_CPU_COMMANDS, null); if (cpu_cmd != null) { // Since we can't cast to hashmap, little workaround; String[] array = cpu_cmd.substring(1, cpu_cmd.length() - 1).split(","); for (String cmd : array) { shell.queueWork(cmd); } } } String voltage = prefs.getString("voltage_values", null); if (voltage != null) shell.queueWork("echo " + voltage + " > " + PREF_VOLTAGE_PATH); // GET GPU VALUES FROM PREFERENCES String gpu_max = prefs.getString(PREF_GPU_FREQ_MAX, null); String display_color = prefs.getString(PREF_DISPLAY_COLOR, null); Boolean gpu_enb = prefs.getBoolean(PREF_GPU_CONTROL_ACTIVE, false); Boolean sweep = prefs.getBoolean(PREF_SWEEP2WAKE, false); String rgbValues = prefs.getString("rgbValues", null); // GET MEM VALUES FROM PREFERENCES String mem_ios = prefs.getString(PREF_GOV_IO_FILE, null); Boolean mem_dfs = prefs.getBoolean(PREF_DYANMIC_FSYNC, false); Boolean mem_wrb = prefs.getBoolean(PREF_WRITEBACK, false); // Get Misc Settings from preferences String misc_vib = prefs.getString(MISC_VIBRATOR_CONTROL, null); String misc_thm = prefs.getString(MISC_THERMAL_CONTROL, null); // ADD CPU COMMANDS TO THE ARRAY ArrayList<String> governorSettings = new ArrayList<String>(); + String max_freq = shell.getInfo(CPU_BASE_PATH + 0 + CPU_MAX_FREQ); + String min_freq = shell.getInfo(CPU_BASE_PATH + 0 + CPU_MIN_FREQ); for (int k = 0; k < mNumCpus; k++) { if (cpu_max != null) { shell.queueWork("echo 1 > " + CPU_BASE_PATH + k + "/online"); shell.queueWork("chmod 0666 " + CPU_BASE_PATH + k + CPU_MAX_FREQ); - if (Profile != null) - defaultProfile.add("echo " + shell.getInfo(CPU_BASE_PATH + k + CPU_MAX_FREQ) + " > " + CPU_BASE_PATH + k + CPU_MAX_FREQ); + if (Profile != null) { + defaultProfile.add("echo 1 > " + CPU_BASE_PATH + k + "/online"); + defaultProfile.add("echo " + max_freq + " > " + CPU_BASE_PATH + k + CPU_MAX_FREQ); + } shell.queueWork("echo " + cpu_max + " > " + CPU_BASE_PATH + k + CPU_MAX_FREQ); } if (cpu_min != null) { shell.queueWork("echo 1 > " + CPU_BASE_PATH + k + "/online"); shell.queueWork("chmod 0666 " + CPU_BASE_PATH + k + CPU_MIN_FREQ); - if (Profile != null) - defaultProfile.add("echo " + shell.getInfo(CPU_BASE_PATH + k + CPU_MIN_FREQ) + " > " + CPU_BASE_PATH + k + CPU_MIN_FREQ); + if (Profile != null) { + defaultProfile.add("echo 1 > " + CPU_BASE_PATH + k + "/online"); + defaultProfile.add("echo " + min_freq + " > " + CPU_BASE_PATH + k + CPU_MIN_FREQ); + } shell.queueWork("echo " + cpu_min + " > " + CPU_BASE_PATH + k + CPU_MIN_FREQ); } if (cpu_gov != null) { governorSettings.add("chmod 0666 " + CPU_BASE_PATH + k + CURRENT_GOV_AVAILABLE); /* * Needs to be executed first, otherwise we would get a NullPointer * For safety reasons we sleep this thread later */ if (Profile != null) defaultProfile.add("echo " + shell.getInfo(CPU_BASE_PATH + k + CURRENT_GOV_AVAILABLE) + " > " + CPU_BASE_PATH + k + CURRENT_GOV_AVAILABLE); governorSettings.add("echo " + cpu_gov + " > " + CPU_BASE_PATH + k + CURRENT_GOV_AVAILABLE); } } if (mem_ios != null) { governorSettings.add("chmod 0666 " + GOV_IO_FILE); if (Profile != null) defaultProfile.add("echo " + shell.getInfoString(shell.getInfo(GOV_IO_FILE)) + " > " + GOV_IO_FILE); governorSettings.add("echo " + mem_ios + " > " + GOV_IO_FILE); } if (cpu_gov != null || mem_ios != null) { // Seriously, we need to set this first because of dependencies; shell.setRootInfo(governorSettings.toArray(new String[0])); } // ADD GPU COMMANDS TO THE ARRAY if (gpu_max != null) { for (String a : GPU_FILES) { if (new File(a).exists()) { gpu_file = a; break; } } if (gpu_file != null) { shell.queueWork("chmod 0666 " + gpu_file); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(gpu_file) + " > " + gpu_file); shell.queueWork("echo " + gpu_max + " > " + gpu_file); } } if(new File(GPU_CONTROL_ACTIVE).exists()) { shell.queueWork("chmod 0666 " + GPU_CONTROL_ACTIVE); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(GPU_CONTROL_ACTIVE) + " > " + GPU_CONTROL_ACTIVE); shell.queueWork("echo " + (gpu_enb ? "1" : "0") + " > " + GPU_CONTROL_ACTIVE); } if(new File(SWEEP2WAKE).exists()) { shell.queueWork("chmod 0666 " + SWEEP2WAKE); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(SWEEP2WAKE) + " > " + SWEEP2WAKE); shell.queueWork("echo " + (sweep ? "1" : "0") + " > " + SWEEP2WAKE); } if (display_color != null) { shell.queueWork("chmod 0666 " + DISPLAY_COLOR); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(DISPLAY_COLOR) + " > " + DISPLAY_COLOR); shell.queueWork("echo " + display_color + " > " + DISPLAY_COLOR); } if (rgbValues != null) { shell.queueWork("chmod 0666 " + PERF_COLOR_CONTROL); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(PERF_COLOR_CONTROL) + " > " + PERF_COLOR_CONTROL); shell.queueWork("echo " + rgbValues + " > " + PERF_COLOR_CONTROL); } // ADD MEM COMMANDS TO THE ARRAY if (new File(DYANMIC_FSYNC).exists()) { shell.queueWork("chmod 0666 " + DYANMIC_FSYNC); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(DYANMIC_FSYNC) + " > " + DYANMIC_FSYNC); shell.queueWork("echo " + (mem_dfs ? "1" : "0") + " > " + DYANMIC_FSYNC); } if (new File(WRITEBACK).exists()) { shell.queueWork("chmod 0666 " + WRITEBACK); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(WRITEBACK) + " > " + WRITEBACK); shell.queueWork("echo " + (mem_wrb ? "1" : "0") + " > " + WRITEBACK); } // Add misc commands to array if (misc_vib != null) { shell.queueWork("chmod 0666 " + MISC_VIBRATOR_CONTROL); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(MISC_VIBRATOR_CONTROL) + " > " + MISC_VIBRATOR_CONTROL); shell.queueWork("echo " + misc_vib + " > " + MISC_VIBRATOR_CONTROL); } if (misc_thm != null) { shell.queueWork("chmod 0666 " + MISC_THERMAL_CONTROL); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(MISC_THERMAL_CONTROL) + " > " + MISC_THERMAL_CONTROL); shell.queueWork("echo " + misc_thm + " > " + MISC_THERMAL_CONTROL); } try { if (mem_ios != null) { try { Thread.sleep(200); } catch (InterruptedException e) { Log.e("Aero", "Something interrupted the main Thread, try again.", e); } String completeIOSchedulerSettings[] = shell.getDirInfo(GOV_IO_PARAMETER, true); /* IO Scheduler Specific Settings at boot */ for (String b : completeIOSchedulerSettings) { final String ioSettings = prefs.getString(GOV_IO_PARAMETER + "/" + b, null); if (ioSettings != null) { shell.queueWork("chmod 0666 " + GOV_IO_PARAMETER + "/" + b); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(GOV_IO_PARAMETER + "/" + b) + " > " + GOV_IO_PARAMETER + "/" + b); shell.queueWork("echo " + ioSettings + " > " + GOV_IO_PARAMETER + "/" + b); //Log.e("Aero", "Output: " + "echo " + ioSettings + " > " + GOV_IO_PARAMETER + "/" + b); } } } if (cpu_gov != null) { try { Thread.sleep(200); } catch (InterruptedException e) { Log.e("Aero", "Something interrupted the main Thread, try again.", e); } final String completeGovernorSettingList[] = shell.getDirInfo(CPU_GOV_BASE + cpu_gov, true); /* Governor Specific Settings at boot */ for (String b : completeGovernorSettingList) { final String governorSetting = prefs.getString(CPU_GOV_BASE + cpu_gov + "/" + b, null); if (governorSetting != null) { shell.queueWork("chmod 0666 " + CPU_GOV_BASE + cpu_gov + "/" + b); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(CPU_GOV_BASE + cpu_gov + "/" + b) + " > " + CPU_GOV_BASE + cpu_gov + "/" + b); shell.queueWork("echo " + governorSetting + " > " + CPU_GOV_BASE + cpu_gov + "/" + b); //Log.e("Aero", "Output: " + "echo " + governorSetting + " > " + CPU_GOV_BASE + cpu_gov + "/" + b); } } } final String completeVMSettings[] = shell.getDirInfo(DALVIK_TWEAK, true); /* VM specific settings at boot */ for (String c : completeVMSettings) { final String vmSettings = prefs.getString(DALVIK_TWEAK + "/" + c, null); if (vmSettings != null) { shell.queueWork("chmod 0666 " + DALVIK_TWEAK + "/" + c); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(DALVIK_TWEAK + "/" + c) + " > " + DALVIK_TWEAK + "/" + c); shell.queueWork("echo " + vmSettings + " > " + DALVIK_TWEAK + "/" + c); //Log.e("Aero", "Output: " + "echo " + vmSettings + " > " + DALVIK_TWEAK + "/" + c); } } if (new File(PREF_HOTPLUG). exists()) { final String completeHotplugSettings[] = shell.getDirInfo(PREF_HOTPLUG, true); /* Hotplug specific settings at boot */ for (String d : completeHotplugSettings) { final String hotplugSettings = prefs.getString(PREF_HOTPLUG + "/" + d, null); if (hotplugSettings != null) { shell.queueWork("chmod 0666 " + PREF_HOTPLUG + "/" + d); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(PREF_HOTPLUG + "/" + d) + " > " + PREF_HOTPLUG + "/" + d); shell.queueWork("echo " + hotplugSettings + " > " + PREF_HOTPLUG + "/" + d); //Log.e("Aero", "Output: " + "echo " + hotplugSettings + " > " + PREF_HOTPLUG + "/" + d); } } } if (new File(PREF_GPU_GOV).exists()) { final String completeGPUGovSettings[] = shell.getDirInfo(PREF_GPU_GOV, true); /* GPU Governor specific settings at boot */ for (String e : completeGPUGovSettings) { final String gpugovSettings = prefs.getString(PREF_GPU_GOV + "/" + e, null); if (gpugovSettings != null) { shell.queueWork("chmod 0666 " + PREF_GPU_GOV + "/" + e); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(PREF_GPU_GOV + "/" + e) + " > " + PREF_GPU_GOV + "/" + e); shell.queueWork("echo " + gpugovSettings + " > " + PREF_GPU_GOV + "/" + e); //Log.e("Aero", "Output: " + "echo " + gpugovSettings + " > " + PREF_GPU_GOV + "/" + e); } } } } catch (NullPointerException e) { Log.e("Aero", "This shouldn't happen.. Maybe a race condition. ", e); } // EXECUTE ALL THE COMMANDS COLLECTED shell.execWork(); shell.flushWork(); } public void executeDefault() { String[] abc = defaultProfile.toArray(new String[0]); shell.setRootInfo(abc); defaultProfile.clear(); } }
false
true
private void doBackground(Context context, String Profile) { if (Profile == null) prefs = PreferenceManager.getDefaultSharedPreferences(context); else prefs = context.getSharedPreferences(Profile, Context.MODE_PRIVATE); // GET CPU VALUES AND COMMANDS FROM PREFERENCES String cpu_max = prefs.getString(PREF_CPU_MAX_FREQ, null); String cpu_min = prefs.getString(PREF_CPU_MIN_FREQ, null); String cpu_gov = prefs.getString(PREF_CURRENT_GOV_AVAILABLE, null); // Overclocking.... try { HashSet<String> hashcpu_cmd = (HashSet<String>) prefs.getStringSet(PREF_CPU_COMMANDS, null); if (hashcpu_cmd != null) { for (String cmd : hashcpu_cmd) { shell.queueWork(cmd); } } } catch (ClassCastException e) { // HashSet didn't work, so we make a fallback; String cpu_cmd = prefs.getString(PREF_CPU_COMMANDS, null); if (cpu_cmd != null) { // Since we can't cast to hashmap, little workaround; String[] array = cpu_cmd.substring(1, cpu_cmd.length() - 1).split(","); for (String cmd : array) { shell.queueWork(cmd); } } } String voltage = prefs.getString("voltage_values", null); if (voltage != null) shell.queueWork("echo " + voltage + " > " + PREF_VOLTAGE_PATH); // GET GPU VALUES FROM PREFERENCES String gpu_max = prefs.getString(PREF_GPU_FREQ_MAX, null); String display_color = prefs.getString(PREF_DISPLAY_COLOR, null); Boolean gpu_enb = prefs.getBoolean(PREF_GPU_CONTROL_ACTIVE, false); Boolean sweep = prefs.getBoolean(PREF_SWEEP2WAKE, false); String rgbValues = prefs.getString("rgbValues", null); // GET MEM VALUES FROM PREFERENCES String mem_ios = prefs.getString(PREF_GOV_IO_FILE, null); Boolean mem_dfs = prefs.getBoolean(PREF_DYANMIC_FSYNC, false); Boolean mem_wrb = prefs.getBoolean(PREF_WRITEBACK, false); // Get Misc Settings from preferences String misc_vib = prefs.getString(MISC_VIBRATOR_CONTROL, null); String misc_thm = prefs.getString(MISC_THERMAL_CONTROL, null); // ADD CPU COMMANDS TO THE ARRAY ArrayList<String> governorSettings = new ArrayList<String>(); for (int k = 0; k < mNumCpus; k++) { if (cpu_max != null) { shell.queueWork("echo 1 > " + CPU_BASE_PATH + k + "/online"); shell.queueWork("chmod 0666 " + CPU_BASE_PATH + k + CPU_MAX_FREQ); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(CPU_BASE_PATH + k + CPU_MAX_FREQ) + " > " + CPU_BASE_PATH + k + CPU_MAX_FREQ); shell.queueWork("echo " + cpu_max + " > " + CPU_BASE_PATH + k + CPU_MAX_FREQ); } if (cpu_min != null) { shell.queueWork("echo 1 > " + CPU_BASE_PATH + k + "/online"); shell.queueWork("chmod 0666 " + CPU_BASE_PATH + k + CPU_MIN_FREQ); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(CPU_BASE_PATH + k + CPU_MIN_FREQ) + " > " + CPU_BASE_PATH + k + CPU_MIN_FREQ); shell.queueWork("echo " + cpu_min + " > " + CPU_BASE_PATH + k + CPU_MIN_FREQ); } if (cpu_gov != null) { governorSettings.add("chmod 0666 " + CPU_BASE_PATH + k + CURRENT_GOV_AVAILABLE); /* * Needs to be executed first, otherwise we would get a NullPointer * For safety reasons we sleep this thread later */ if (Profile != null) defaultProfile.add("echo " + shell.getInfo(CPU_BASE_PATH + k + CURRENT_GOV_AVAILABLE) + " > " + CPU_BASE_PATH + k + CURRENT_GOV_AVAILABLE); governorSettings.add("echo " + cpu_gov + " > " + CPU_BASE_PATH + k + CURRENT_GOV_AVAILABLE); } } if (mem_ios != null) { governorSettings.add("chmod 0666 " + GOV_IO_FILE); if (Profile != null) defaultProfile.add("echo " + shell.getInfoString(shell.getInfo(GOV_IO_FILE)) + " > " + GOV_IO_FILE); governorSettings.add("echo " + mem_ios + " > " + GOV_IO_FILE); } if (cpu_gov != null || mem_ios != null) { // Seriously, we need to set this first because of dependencies; shell.setRootInfo(governorSettings.toArray(new String[0])); } // ADD GPU COMMANDS TO THE ARRAY if (gpu_max != null) { for (String a : GPU_FILES) { if (new File(a).exists()) { gpu_file = a; break; } } if (gpu_file != null) { shell.queueWork("chmod 0666 " + gpu_file); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(gpu_file) + " > " + gpu_file); shell.queueWork("echo " + gpu_max + " > " + gpu_file); } } if(new File(GPU_CONTROL_ACTIVE).exists()) { shell.queueWork("chmod 0666 " + GPU_CONTROL_ACTIVE); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(GPU_CONTROL_ACTIVE) + " > " + GPU_CONTROL_ACTIVE); shell.queueWork("echo " + (gpu_enb ? "1" : "0") + " > " + GPU_CONTROL_ACTIVE); } if(new File(SWEEP2WAKE).exists()) { shell.queueWork("chmod 0666 " + SWEEP2WAKE); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(SWEEP2WAKE) + " > " + SWEEP2WAKE); shell.queueWork("echo " + (sweep ? "1" : "0") + " > " + SWEEP2WAKE); } if (display_color != null) { shell.queueWork("chmod 0666 " + DISPLAY_COLOR); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(DISPLAY_COLOR) + " > " + DISPLAY_COLOR); shell.queueWork("echo " + display_color + " > " + DISPLAY_COLOR); } if (rgbValues != null) { shell.queueWork("chmod 0666 " + PERF_COLOR_CONTROL); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(PERF_COLOR_CONTROL) + " > " + PERF_COLOR_CONTROL); shell.queueWork("echo " + rgbValues + " > " + PERF_COLOR_CONTROL); } // ADD MEM COMMANDS TO THE ARRAY if (new File(DYANMIC_FSYNC).exists()) { shell.queueWork("chmod 0666 " + DYANMIC_FSYNC); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(DYANMIC_FSYNC) + " > " + DYANMIC_FSYNC); shell.queueWork("echo " + (mem_dfs ? "1" : "0") + " > " + DYANMIC_FSYNC); } if (new File(WRITEBACK).exists()) { shell.queueWork("chmod 0666 " + WRITEBACK); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(WRITEBACK) + " > " + WRITEBACK); shell.queueWork("echo " + (mem_wrb ? "1" : "0") + " > " + WRITEBACK); } // Add misc commands to array if (misc_vib != null) { shell.queueWork("chmod 0666 " + MISC_VIBRATOR_CONTROL); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(MISC_VIBRATOR_CONTROL) + " > " + MISC_VIBRATOR_CONTROL); shell.queueWork("echo " + misc_vib + " > " + MISC_VIBRATOR_CONTROL); } if (misc_thm != null) { shell.queueWork("chmod 0666 " + MISC_THERMAL_CONTROL); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(MISC_THERMAL_CONTROL) + " > " + MISC_THERMAL_CONTROL); shell.queueWork("echo " + misc_thm + " > " + MISC_THERMAL_CONTROL); } try { if (mem_ios != null) { try { Thread.sleep(200); } catch (InterruptedException e) { Log.e("Aero", "Something interrupted the main Thread, try again.", e); } String completeIOSchedulerSettings[] = shell.getDirInfo(GOV_IO_PARAMETER, true); /* IO Scheduler Specific Settings at boot */ for (String b : completeIOSchedulerSettings) { final String ioSettings = prefs.getString(GOV_IO_PARAMETER + "/" + b, null); if (ioSettings != null) { shell.queueWork("chmod 0666 " + GOV_IO_PARAMETER + "/" + b); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(GOV_IO_PARAMETER + "/" + b) + " > " + GOV_IO_PARAMETER + "/" + b); shell.queueWork("echo " + ioSettings + " > " + GOV_IO_PARAMETER + "/" + b); //Log.e("Aero", "Output: " + "echo " + ioSettings + " > " + GOV_IO_PARAMETER + "/" + b); } } } if (cpu_gov != null) { try { Thread.sleep(200); } catch (InterruptedException e) { Log.e("Aero", "Something interrupted the main Thread, try again.", e); } final String completeGovernorSettingList[] = shell.getDirInfo(CPU_GOV_BASE + cpu_gov, true); /* Governor Specific Settings at boot */ for (String b : completeGovernorSettingList) { final String governorSetting = prefs.getString(CPU_GOV_BASE + cpu_gov + "/" + b, null); if (governorSetting != null) { shell.queueWork("chmod 0666 " + CPU_GOV_BASE + cpu_gov + "/" + b); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(CPU_GOV_BASE + cpu_gov + "/" + b) + " > " + CPU_GOV_BASE + cpu_gov + "/" + b); shell.queueWork("echo " + governorSetting + " > " + CPU_GOV_BASE + cpu_gov + "/" + b); //Log.e("Aero", "Output: " + "echo " + governorSetting + " > " + CPU_GOV_BASE + cpu_gov + "/" + b); } } } final String completeVMSettings[] = shell.getDirInfo(DALVIK_TWEAK, true); /* VM specific settings at boot */ for (String c : completeVMSettings) { final String vmSettings = prefs.getString(DALVIK_TWEAK + "/" + c, null); if (vmSettings != null) { shell.queueWork("chmod 0666 " + DALVIK_TWEAK + "/" + c); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(DALVIK_TWEAK + "/" + c) + " > " + DALVIK_TWEAK + "/" + c); shell.queueWork("echo " + vmSettings + " > " + DALVIK_TWEAK + "/" + c); //Log.e("Aero", "Output: " + "echo " + vmSettings + " > " + DALVIK_TWEAK + "/" + c); } } if (new File(PREF_HOTPLUG). exists()) { final String completeHotplugSettings[] = shell.getDirInfo(PREF_HOTPLUG, true); /* Hotplug specific settings at boot */ for (String d : completeHotplugSettings) { final String hotplugSettings = prefs.getString(PREF_HOTPLUG + "/" + d, null); if (hotplugSettings != null) { shell.queueWork("chmod 0666 " + PREF_HOTPLUG + "/" + d); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(PREF_HOTPLUG + "/" + d) + " > " + PREF_HOTPLUG + "/" + d); shell.queueWork("echo " + hotplugSettings + " > " + PREF_HOTPLUG + "/" + d); //Log.e("Aero", "Output: " + "echo " + hotplugSettings + " > " + PREF_HOTPLUG + "/" + d); } } } if (new File(PREF_GPU_GOV).exists()) { final String completeGPUGovSettings[] = shell.getDirInfo(PREF_GPU_GOV, true); /* GPU Governor specific settings at boot */ for (String e : completeGPUGovSettings) { final String gpugovSettings = prefs.getString(PREF_GPU_GOV + "/" + e, null); if (gpugovSettings != null) { shell.queueWork("chmod 0666 " + PREF_GPU_GOV + "/" + e); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(PREF_GPU_GOV + "/" + e) + " > " + PREF_GPU_GOV + "/" + e); shell.queueWork("echo " + gpugovSettings + " > " + PREF_GPU_GOV + "/" + e); //Log.e("Aero", "Output: " + "echo " + gpugovSettings + " > " + PREF_GPU_GOV + "/" + e); } } } } catch (NullPointerException e) { Log.e("Aero", "This shouldn't happen.. Maybe a race condition. ", e); } // EXECUTE ALL THE COMMANDS COLLECTED shell.execWork(); shell.flushWork(); }
private void doBackground(Context context, String Profile) { if (Profile == null) prefs = PreferenceManager.getDefaultSharedPreferences(context); else prefs = context.getSharedPreferences(Profile, Context.MODE_PRIVATE); // GET CPU VALUES AND COMMANDS FROM PREFERENCES String cpu_max = prefs.getString(PREF_CPU_MAX_FREQ, null); String cpu_min = prefs.getString(PREF_CPU_MIN_FREQ, null); String cpu_gov = prefs.getString(PREF_CURRENT_GOV_AVAILABLE, null); // Overclocking.... try { HashSet<String> hashcpu_cmd = (HashSet<String>) prefs.getStringSet(PREF_CPU_COMMANDS, null); if (hashcpu_cmd != null) { for (String cmd : hashcpu_cmd) { shell.queueWork(cmd); } } } catch (ClassCastException e) { // HashSet didn't work, so we make a fallback; String cpu_cmd = prefs.getString(PREF_CPU_COMMANDS, null); if (cpu_cmd != null) { // Since we can't cast to hashmap, little workaround; String[] array = cpu_cmd.substring(1, cpu_cmd.length() - 1).split(","); for (String cmd : array) { shell.queueWork(cmd); } } } String voltage = prefs.getString("voltage_values", null); if (voltage != null) shell.queueWork("echo " + voltage + " > " + PREF_VOLTAGE_PATH); // GET GPU VALUES FROM PREFERENCES String gpu_max = prefs.getString(PREF_GPU_FREQ_MAX, null); String display_color = prefs.getString(PREF_DISPLAY_COLOR, null); Boolean gpu_enb = prefs.getBoolean(PREF_GPU_CONTROL_ACTIVE, false); Boolean sweep = prefs.getBoolean(PREF_SWEEP2WAKE, false); String rgbValues = prefs.getString("rgbValues", null); // GET MEM VALUES FROM PREFERENCES String mem_ios = prefs.getString(PREF_GOV_IO_FILE, null); Boolean mem_dfs = prefs.getBoolean(PREF_DYANMIC_FSYNC, false); Boolean mem_wrb = prefs.getBoolean(PREF_WRITEBACK, false); // Get Misc Settings from preferences String misc_vib = prefs.getString(MISC_VIBRATOR_CONTROL, null); String misc_thm = prefs.getString(MISC_THERMAL_CONTROL, null); // ADD CPU COMMANDS TO THE ARRAY ArrayList<String> governorSettings = new ArrayList<String>(); String max_freq = shell.getInfo(CPU_BASE_PATH + 0 + CPU_MAX_FREQ); String min_freq = shell.getInfo(CPU_BASE_PATH + 0 + CPU_MIN_FREQ); for (int k = 0; k < mNumCpus; k++) { if (cpu_max != null) { shell.queueWork("echo 1 > " + CPU_BASE_PATH + k + "/online"); shell.queueWork("chmod 0666 " + CPU_BASE_PATH + k + CPU_MAX_FREQ); if (Profile != null) { defaultProfile.add("echo 1 > " + CPU_BASE_PATH + k + "/online"); defaultProfile.add("echo " + max_freq + " > " + CPU_BASE_PATH + k + CPU_MAX_FREQ); } shell.queueWork("echo " + cpu_max + " > " + CPU_BASE_PATH + k + CPU_MAX_FREQ); } if (cpu_min != null) { shell.queueWork("echo 1 > " + CPU_BASE_PATH + k + "/online"); shell.queueWork("chmod 0666 " + CPU_BASE_PATH + k + CPU_MIN_FREQ); if (Profile != null) { defaultProfile.add("echo 1 > " + CPU_BASE_PATH + k + "/online"); defaultProfile.add("echo " + min_freq + " > " + CPU_BASE_PATH + k + CPU_MIN_FREQ); } shell.queueWork("echo " + cpu_min + " > " + CPU_BASE_PATH + k + CPU_MIN_FREQ); } if (cpu_gov != null) { governorSettings.add("chmod 0666 " + CPU_BASE_PATH + k + CURRENT_GOV_AVAILABLE); /* * Needs to be executed first, otherwise we would get a NullPointer * For safety reasons we sleep this thread later */ if (Profile != null) defaultProfile.add("echo " + shell.getInfo(CPU_BASE_PATH + k + CURRENT_GOV_AVAILABLE) + " > " + CPU_BASE_PATH + k + CURRENT_GOV_AVAILABLE); governorSettings.add("echo " + cpu_gov + " > " + CPU_BASE_PATH + k + CURRENT_GOV_AVAILABLE); } } if (mem_ios != null) { governorSettings.add("chmod 0666 " + GOV_IO_FILE); if (Profile != null) defaultProfile.add("echo " + shell.getInfoString(shell.getInfo(GOV_IO_FILE)) + " > " + GOV_IO_FILE); governorSettings.add("echo " + mem_ios + " > " + GOV_IO_FILE); } if (cpu_gov != null || mem_ios != null) { // Seriously, we need to set this first because of dependencies; shell.setRootInfo(governorSettings.toArray(new String[0])); } // ADD GPU COMMANDS TO THE ARRAY if (gpu_max != null) { for (String a : GPU_FILES) { if (new File(a).exists()) { gpu_file = a; break; } } if (gpu_file != null) { shell.queueWork("chmod 0666 " + gpu_file); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(gpu_file) + " > " + gpu_file); shell.queueWork("echo " + gpu_max + " > " + gpu_file); } } if(new File(GPU_CONTROL_ACTIVE).exists()) { shell.queueWork("chmod 0666 " + GPU_CONTROL_ACTIVE); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(GPU_CONTROL_ACTIVE) + " > " + GPU_CONTROL_ACTIVE); shell.queueWork("echo " + (gpu_enb ? "1" : "0") + " > " + GPU_CONTROL_ACTIVE); } if(new File(SWEEP2WAKE).exists()) { shell.queueWork("chmod 0666 " + SWEEP2WAKE); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(SWEEP2WAKE) + " > " + SWEEP2WAKE); shell.queueWork("echo " + (sweep ? "1" : "0") + " > " + SWEEP2WAKE); } if (display_color != null) { shell.queueWork("chmod 0666 " + DISPLAY_COLOR); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(DISPLAY_COLOR) + " > " + DISPLAY_COLOR); shell.queueWork("echo " + display_color + " > " + DISPLAY_COLOR); } if (rgbValues != null) { shell.queueWork("chmod 0666 " + PERF_COLOR_CONTROL); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(PERF_COLOR_CONTROL) + " > " + PERF_COLOR_CONTROL); shell.queueWork("echo " + rgbValues + " > " + PERF_COLOR_CONTROL); } // ADD MEM COMMANDS TO THE ARRAY if (new File(DYANMIC_FSYNC).exists()) { shell.queueWork("chmod 0666 " + DYANMIC_FSYNC); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(DYANMIC_FSYNC) + " > " + DYANMIC_FSYNC); shell.queueWork("echo " + (mem_dfs ? "1" : "0") + " > " + DYANMIC_FSYNC); } if (new File(WRITEBACK).exists()) { shell.queueWork("chmod 0666 " + WRITEBACK); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(WRITEBACK) + " > " + WRITEBACK); shell.queueWork("echo " + (mem_wrb ? "1" : "0") + " > " + WRITEBACK); } // Add misc commands to array if (misc_vib != null) { shell.queueWork("chmod 0666 " + MISC_VIBRATOR_CONTROL); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(MISC_VIBRATOR_CONTROL) + " > " + MISC_VIBRATOR_CONTROL); shell.queueWork("echo " + misc_vib + " > " + MISC_VIBRATOR_CONTROL); } if (misc_thm != null) { shell.queueWork("chmod 0666 " + MISC_THERMAL_CONTROL); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(MISC_THERMAL_CONTROL) + " > " + MISC_THERMAL_CONTROL); shell.queueWork("echo " + misc_thm + " > " + MISC_THERMAL_CONTROL); } try { if (mem_ios != null) { try { Thread.sleep(200); } catch (InterruptedException e) { Log.e("Aero", "Something interrupted the main Thread, try again.", e); } String completeIOSchedulerSettings[] = shell.getDirInfo(GOV_IO_PARAMETER, true); /* IO Scheduler Specific Settings at boot */ for (String b : completeIOSchedulerSettings) { final String ioSettings = prefs.getString(GOV_IO_PARAMETER + "/" + b, null); if (ioSettings != null) { shell.queueWork("chmod 0666 " + GOV_IO_PARAMETER + "/" + b); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(GOV_IO_PARAMETER + "/" + b) + " > " + GOV_IO_PARAMETER + "/" + b); shell.queueWork("echo " + ioSettings + " > " + GOV_IO_PARAMETER + "/" + b); //Log.e("Aero", "Output: " + "echo " + ioSettings + " > " + GOV_IO_PARAMETER + "/" + b); } } } if (cpu_gov != null) { try { Thread.sleep(200); } catch (InterruptedException e) { Log.e("Aero", "Something interrupted the main Thread, try again.", e); } final String completeGovernorSettingList[] = shell.getDirInfo(CPU_GOV_BASE + cpu_gov, true); /* Governor Specific Settings at boot */ for (String b : completeGovernorSettingList) { final String governorSetting = prefs.getString(CPU_GOV_BASE + cpu_gov + "/" + b, null); if (governorSetting != null) { shell.queueWork("chmod 0666 " + CPU_GOV_BASE + cpu_gov + "/" + b); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(CPU_GOV_BASE + cpu_gov + "/" + b) + " > " + CPU_GOV_BASE + cpu_gov + "/" + b); shell.queueWork("echo " + governorSetting + " > " + CPU_GOV_BASE + cpu_gov + "/" + b); //Log.e("Aero", "Output: " + "echo " + governorSetting + " > " + CPU_GOV_BASE + cpu_gov + "/" + b); } } } final String completeVMSettings[] = shell.getDirInfo(DALVIK_TWEAK, true); /* VM specific settings at boot */ for (String c : completeVMSettings) { final String vmSettings = prefs.getString(DALVIK_TWEAK + "/" + c, null); if (vmSettings != null) { shell.queueWork("chmod 0666 " + DALVIK_TWEAK + "/" + c); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(DALVIK_TWEAK + "/" + c) + " > " + DALVIK_TWEAK + "/" + c); shell.queueWork("echo " + vmSettings + " > " + DALVIK_TWEAK + "/" + c); //Log.e("Aero", "Output: " + "echo " + vmSettings + " > " + DALVIK_TWEAK + "/" + c); } } if (new File(PREF_HOTPLUG). exists()) { final String completeHotplugSettings[] = shell.getDirInfo(PREF_HOTPLUG, true); /* Hotplug specific settings at boot */ for (String d : completeHotplugSettings) { final String hotplugSettings = prefs.getString(PREF_HOTPLUG + "/" + d, null); if (hotplugSettings != null) { shell.queueWork("chmod 0666 " + PREF_HOTPLUG + "/" + d); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(PREF_HOTPLUG + "/" + d) + " > " + PREF_HOTPLUG + "/" + d); shell.queueWork("echo " + hotplugSettings + " > " + PREF_HOTPLUG + "/" + d); //Log.e("Aero", "Output: " + "echo " + hotplugSettings + " > " + PREF_HOTPLUG + "/" + d); } } } if (new File(PREF_GPU_GOV).exists()) { final String completeGPUGovSettings[] = shell.getDirInfo(PREF_GPU_GOV, true); /* GPU Governor specific settings at boot */ for (String e : completeGPUGovSettings) { final String gpugovSettings = prefs.getString(PREF_GPU_GOV + "/" + e, null); if (gpugovSettings != null) { shell.queueWork("chmod 0666 " + PREF_GPU_GOV + "/" + e); if (Profile != null) defaultProfile.add("echo " + shell.getInfo(PREF_GPU_GOV + "/" + e) + " > " + PREF_GPU_GOV + "/" + e); shell.queueWork("echo " + gpugovSettings + " > " + PREF_GPU_GOV + "/" + e); //Log.e("Aero", "Output: " + "echo " + gpugovSettings + " > " + PREF_GPU_GOV + "/" + e); } } } } catch (NullPointerException e) { Log.e("Aero", "This shouldn't happen.. Maybe a race condition. ", e); } // EXECUTE ALL THE COMMANDS COLLECTED shell.execWork(); shell.flushWork(); }
diff --git a/src/Lihad/Conflict/Listeners/BeyondPlayerListener.java b/src/Lihad/Conflict/Listeners/BeyondPlayerListener.java index 1c8f1f5..b22b1d5 100644 --- a/src/Lihad/Conflict/Listeners/BeyondPlayerListener.java +++ b/src/Lihad/Conflict/Listeners/BeyondPlayerListener.java @@ -1,230 +1,233 @@ package Lihad.Conflict.Listeners; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Villager; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerExpChangeEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerPortalEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.inventory.ItemStack; import Lihad.Conflict.*; import Lihad.Conflict.Perk.*; import Lihad.Conflict.Util.BeyondUtil; public class BeyondPlayerListener implements Listener { public BeyondPlayerListener() { } @EventHandler public static void onPlayerMove(PlayerMoveEvent event){ if((event.getFrom().getBlockX() != event.getTo().getBlockX() || event.getFrom().getBlockY() != event.getTo().getBlockY() || event.getFrom().getBlockZ() != event.getTo().getBlockZ()) && event.getTo().getWorld().getName().equals("survival")) { if(Conflict.isUnassigned(event.getPlayer().getName())){ event.setTo(event.getFrom()); event.getPlayer().sendMessage(Conflict.NOTICECOLOR+"You need to join a Capital before continuing..."); event.getPlayer().sendMessage(Conflict.TEXTCOLOR+"Type "+ChatColor.GRAY+"/join <cityname> confirm"); event.getPlayer().sendMessage(Conflict.TEXTCOLOR+"You can choose one of: " + Conflict.CITYCOLOR + java.util.Arrays.asList(Conflict.cities).toString()); } for (City city: Conflict.cities) { if (city.getLocation().distance(event.getTo()) < 500.0 && city.getLocation().distance(event.getFrom()) >= 500.0){ event.getPlayer().sendMessage(Conflict.NOTICECOLOR + "You have entered the City of " + Conflict.CITYCOLOR + city.getName()); } else if(city.getLocation().distance(event.getTo()) > 500.0 && city.getLocation().distance(event.getFrom()) <= 500.0){ event.getPlayer().sendMessage(Conflict.NOTICECOLOR + "You have left the City of " + Conflict.CITYCOLOR + city.getName()); } } if(event.getPlayer().getWorld().getSpawnLocation().distance(event.getTo()) > 5000.0 && event.getPlayer().getWorld().getSpawnLocation().distance(event.getFrom()) <= 5000.0){ event.getPlayer().sendMessage(Conflict.NOTICECOLOR + "You have entered the Wilderness"); } else if(event.getPlayer().getWorld().getSpawnLocation().distance(event.getTo()) < 5000.0 && event.getPlayer().getWorld().getSpawnLocation().distance(event.getFrom()) >= 5000.0){ event.getPlayer().sendMessage(Conflict.NOTICECOLOR + "You have entered the Cityscape"); } } } @EventHandler public static void onPlayerJoin(PlayerJoinEvent event){ if(Conflict.getPlayerCity(event.getPlayer().getName()) == null && !Conflict.handler.inGroup(event.getPlayer().getWorld().getName(), event.getPlayer().getName(), "Drifter")){ if(!Conflict.isUnassigned(event.getPlayer().getName())) Conflict.addUnassigned(event.getPlayer().getName()); } Conflict.checkPlayerCityPermissions(event.getPlayer()); } // MystPortal code // @EventHandler(priority = EventPriority.HIGHEST) // public static void onPlayerPortal(PlayerPortalEvent event){ // if(event.getCause().equals(TeleportCause.NETHER_PORTAL) && event.getFrom().getWorld().getName().equals("survival") && Conflict.MystPortal.getNode().getLocation().distance(event.getFrom()) < 10){ // if( Conflict.playerCanUsePerk(event.getPlayer(), Conflict.MystPortal) ) { // event.getPlayer().sendMessage("Shaaaaazaaam!"); // event.getPlayer().teleport(new Location(Bukkit.getServer().getWorld("mystworld"), 0.0, 0.0, 0.0)); // event.setTo(new Location(Bukkit.getServer().getWorld("mystworld"), 0.0, 0.0, 0.0)); // event.setCancelled(true); // }else{ // event.getPlayer().sendMessage("Epic Fail"); // } // } // } @EventHandler public static void onPlayerTeleport(PlayerTeleportEvent event){ Location dest = event.getTo(); Location src = event.getFrom(); Player player = event.getPlayer(); if (Conflict.war != null) { // During wartime, cancel any tp in or out of nodes. if (Conflict.war.getPlayerTeam(player) != null) { for (Node n : Conflict.nodes) { //Try to fix exception spew. if (n.getLocation().getWorld().equals(dest.getWorld()) && dest.getWorld().equals(src.getWorld()) && (n.isInRadius(dest) || n.isInRadius(src))) { System.out.println("Attempting to cancel tp from " + src + " to " + dest + " for node at " + n.getLocation()); event.setCancelled(true); return; } } } } } @EventHandler /** * Think this adds xp to players near any player in the same city whose xp changes?? * @param event */ public static void onPlayerExpChange(PlayerExpChangeEvent event){ if(event.getAmount() > 0){ List<Entity> entities = event.getPlayer().getNearbyEntities(20, 20, 20); for(int i=0;i<entities.size();i++){ if(entities.get(i) instanceof Player) { Player player = (Player)entities.get(i); if (Conflict.getPlayerCity(player.getName()) != null && Conflict.getPlayerCity(event.getPlayer().getName()) != null) { player.giveExp(event.getAmount()); } } } } } @EventHandler public static void onPlayerInteract(PlayerInteractEvent event){ if (event.getClickedBlock() == null) { // WTF, Bukkit! return; } Block block = event.getClickedBlock(); Player player = event.getPlayer(); for (Node n : Conflict.nodes) { if (!block.getLocation().equals(n.getLocation())) { continue; } for (Perk p : n.getPerks()) { if (!(p instanceof BlockPerk)) { continue; } if (!Conflict.playerCanUsePerk(event.getPlayer(), p)) { event.getPlayer().sendMessage(Conflict.NOTICECOLOR + "You can't use this perk!"); continue; } ((BlockPerk)p).activate(event.getPlayer()); } } for (City city:Conflict.cities) { if(block.getLocation().equals(city.getLocation().getBlock().getLocation())){ if(player.getItemInHand().getType() == Material.GOLD_INGOT){ int number = 1; if(player.getItemInHand().getAmount() == 1){ player.getInventory().setItemInHand(null); }else if(player.isSneaking()){ number = player.getItemInHand().getAmount(); player.getInventory().setItemInHand(null); }else{ player.getItemInHand().setAmount(player.getItemInHand().getAmount()-1); player.getInventory().setItemInHand(player.getItemInHand()); } city.addMoney(number); player.sendMessage("You gave " + Conflict.MONEYCOLOR + number + " gold bar(s) to " + Conflict.CITYCOLOR + city.getName()); player.updateInventory(); } player.sendMessage(Conflict.CITYCOLOR + city.getName() + Conflict.TEXTCOLOR + " has " + Conflict.MONEYCOLOR + city.getMoney() + " gold!"); } else if(block.getLocation().equals(city.getSpongeLocation().getBlock().getLocation())){ try{ if(Conflict.handler.inGroup(player.getWorld().getName(), player.getName(), "Drifter") && !Conflict.handler.inGroup(player.getWorld().getName(), player.getName(), "Peasant")){ boolean successful = Conflict.joinCity(player, player.getName(), city.getName(), false); - if (!successful) + if (!successful){ player.sendMessage(Conflict.NOTICECOLOR + "Sorry you couldn't join a city, ask for help with the above error messages?"); + return; + } System.out.println("-------------------UPGRADE-DEBUG-----------"); System.out.println("Sponge hit by player: "+player); Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "pex promote "+player.getName()); if(city.getSpawn() != null) player.teleport(city.getSpawn()); player.sendMessage(Conflict.NOTICECOLOR + "Congrats! You've been accepted!!! You can leave this area now!"); player.getInventory().addItem(new ItemStack(Material.COOKED_BEEF,10)); player.getInventory().addItem(new ItemStack(Material.IRON_SWORD,1)); player.getInventory().addItem(new ItemStack(Material.WOOD,64)); player.getInventory().addItem(new ItemStack(Material.TORCH,20)); player.getInventory().addItem(new ItemStack(Material.IRON_PICKAXE,1)); player.getInventory().addItem(new ItemStack(Material.STONE,64)); player.getInventory().addItem(new ItemStack(Material.COBBLESTONE,64)); System.out.println("----------------------------------------------"); } }catch(NullPointerException e) { - // This is cute. + System.out.println("EXCEPTION - Player trying to join a city failed"); + e.printStackTrace(); } } } } @EventHandler public static void onInventoryClose(org.bukkit.event.inventory.InventoryCloseEvent event) { Player player = (Player)event.getPlayer(); if (event.getView().getType() == InventoryType.CRAFTING) { if (!player.isOp() && !Conflict.handler.has(player, "conflict.debug")) { BeyondUtil.nerfOverenchantedPlayerInventory(player); } } else if (event.getView().getType() == InventoryType.CHEST) { if (!player.isOp() && !Conflict.handler.has(player, "conflict.debug")) { BeyondUtil.nerfOverenchantedInventory(event.getInventory()); } } } @EventHandler public static void onPlayerItemPickup(org.bukkit.event.player.PlayerPickupItemEvent event) { Player player = (Player)event.getPlayer(); if (!player.isOp() && !Conflict.handler.has(player, "conflict.debug")) { ItemStack i = event.getItem().getItemStack(); BeyondUtil.nerfOverenchantedItem(i); } } }
false
true
public static void onPlayerInteract(PlayerInteractEvent event){ if (event.getClickedBlock() == null) { // WTF, Bukkit! return; } Block block = event.getClickedBlock(); Player player = event.getPlayer(); for (Node n : Conflict.nodes) { if (!block.getLocation().equals(n.getLocation())) { continue; } for (Perk p : n.getPerks()) { if (!(p instanceof BlockPerk)) { continue; } if (!Conflict.playerCanUsePerk(event.getPlayer(), p)) { event.getPlayer().sendMessage(Conflict.NOTICECOLOR + "You can't use this perk!"); continue; } ((BlockPerk)p).activate(event.getPlayer()); } } for (City city:Conflict.cities) { if(block.getLocation().equals(city.getLocation().getBlock().getLocation())){ if(player.getItemInHand().getType() == Material.GOLD_INGOT){ int number = 1; if(player.getItemInHand().getAmount() == 1){ player.getInventory().setItemInHand(null); }else if(player.isSneaking()){ number = player.getItemInHand().getAmount(); player.getInventory().setItemInHand(null); }else{ player.getItemInHand().setAmount(player.getItemInHand().getAmount()-1); player.getInventory().setItemInHand(player.getItemInHand()); } city.addMoney(number); player.sendMessage("You gave " + Conflict.MONEYCOLOR + number + " gold bar(s) to " + Conflict.CITYCOLOR + city.getName()); player.updateInventory(); } player.sendMessage(Conflict.CITYCOLOR + city.getName() + Conflict.TEXTCOLOR + " has " + Conflict.MONEYCOLOR + city.getMoney() + " gold!"); } else if(block.getLocation().equals(city.getSpongeLocation().getBlock().getLocation())){ try{ if(Conflict.handler.inGroup(player.getWorld().getName(), player.getName(), "Drifter") && !Conflict.handler.inGroup(player.getWorld().getName(), player.getName(), "Peasant")){ boolean successful = Conflict.joinCity(player, player.getName(), city.getName(), false); if (!successful) player.sendMessage(Conflict.NOTICECOLOR + "Sorry you couldn't join a city, ask for help with the above error messages?"); System.out.println("-------------------UPGRADE-DEBUG-----------"); System.out.println("Sponge hit by player: "+player); Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "pex promote "+player.getName()); if(city.getSpawn() != null) player.teleport(city.getSpawn()); player.sendMessage(Conflict.NOTICECOLOR + "Congrats! You've been accepted!!! You can leave this area now!"); player.getInventory().addItem(new ItemStack(Material.COOKED_BEEF,10)); player.getInventory().addItem(new ItemStack(Material.IRON_SWORD,1)); player.getInventory().addItem(new ItemStack(Material.WOOD,64)); player.getInventory().addItem(new ItemStack(Material.TORCH,20)); player.getInventory().addItem(new ItemStack(Material.IRON_PICKAXE,1)); player.getInventory().addItem(new ItemStack(Material.STONE,64)); player.getInventory().addItem(new ItemStack(Material.COBBLESTONE,64)); System.out.println("----------------------------------------------"); } }catch(NullPointerException e) { // This is cute. } } } }
public static void onPlayerInteract(PlayerInteractEvent event){ if (event.getClickedBlock() == null) { // WTF, Bukkit! return; } Block block = event.getClickedBlock(); Player player = event.getPlayer(); for (Node n : Conflict.nodes) { if (!block.getLocation().equals(n.getLocation())) { continue; } for (Perk p : n.getPerks()) { if (!(p instanceof BlockPerk)) { continue; } if (!Conflict.playerCanUsePerk(event.getPlayer(), p)) { event.getPlayer().sendMessage(Conflict.NOTICECOLOR + "You can't use this perk!"); continue; } ((BlockPerk)p).activate(event.getPlayer()); } } for (City city:Conflict.cities) { if(block.getLocation().equals(city.getLocation().getBlock().getLocation())){ if(player.getItemInHand().getType() == Material.GOLD_INGOT){ int number = 1; if(player.getItemInHand().getAmount() == 1){ player.getInventory().setItemInHand(null); }else if(player.isSneaking()){ number = player.getItemInHand().getAmount(); player.getInventory().setItemInHand(null); }else{ player.getItemInHand().setAmount(player.getItemInHand().getAmount()-1); player.getInventory().setItemInHand(player.getItemInHand()); } city.addMoney(number); player.sendMessage("You gave " + Conflict.MONEYCOLOR + number + " gold bar(s) to " + Conflict.CITYCOLOR + city.getName()); player.updateInventory(); } player.sendMessage(Conflict.CITYCOLOR + city.getName() + Conflict.TEXTCOLOR + " has " + Conflict.MONEYCOLOR + city.getMoney() + " gold!"); } else if(block.getLocation().equals(city.getSpongeLocation().getBlock().getLocation())){ try{ if(Conflict.handler.inGroup(player.getWorld().getName(), player.getName(), "Drifter") && !Conflict.handler.inGroup(player.getWorld().getName(), player.getName(), "Peasant")){ boolean successful = Conflict.joinCity(player, player.getName(), city.getName(), false); if (!successful){ player.sendMessage(Conflict.NOTICECOLOR + "Sorry you couldn't join a city, ask for help with the above error messages?"); return; } System.out.println("-------------------UPGRADE-DEBUG-----------"); System.out.println("Sponge hit by player: "+player); Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "pex promote "+player.getName()); if(city.getSpawn() != null) player.teleport(city.getSpawn()); player.sendMessage(Conflict.NOTICECOLOR + "Congrats! You've been accepted!!! You can leave this area now!"); player.getInventory().addItem(new ItemStack(Material.COOKED_BEEF,10)); player.getInventory().addItem(new ItemStack(Material.IRON_SWORD,1)); player.getInventory().addItem(new ItemStack(Material.WOOD,64)); player.getInventory().addItem(new ItemStack(Material.TORCH,20)); player.getInventory().addItem(new ItemStack(Material.IRON_PICKAXE,1)); player.getInventory().addItem(new ItemStack(Material.STONE,64)); player.getInventory().addItem(new ItemStack(Material.COBBLESTONE,64)); System.out.println("----------------------------------------------"); } }catch(NullPointerException e) { System.out.println("EXCEPTION - Player trying to join a city failed"); e.printStackTrace(); } } } }
diff --git a/src/org/tekkotsu/api/BehaviorWriter.java b/src/org/tekkotsu/api/BehaviorWriter.java index 3154936..cdbf276 100644 --- a/src/org/tekkotsu/api/BehaviorWriter.java +++ b/src/org/tekkotsu/api/BehaviorWriter.java @@ -1,383 +1,383 @@ package org.tekkotsu.api; import java.util.ArrayList; public class BehaviorWriter { //Attributes private NodeClass nodeClass; private String registerCall; private String include; private String comment; private SetupMachine setup; //Constructor public BehaviorWriter(NodeClass nodeClass){ this.nodeClass = nodeClass; this.registerCall = "\n\nREGISTER_BEHAVIOR(" + this.nodeClass.getName() + ");"; this.include = "#include \"Behaviors/StateMachine.h\" \n\n"; this.comment = "//" + nodeClass.getName() + " Node Class\n"; this.setup = nodeClass.getSetupMachine(); } //Method to get the fsm content as string. public String writeBehavior(){ //String for class header. String fsm = include; fsm += getClassDef(0); //Get the register call fsm += registerCall; System.out.println(fsm); return fsm; } //Method to get class definition code public String getClassDef(int depth){ String indent = ""; for(int i = 0; i < depth; i++){ indent += "\t"; } //String for class header. String fsm = getHeader(depth); //If the class has any variables, get the variables. if(nodeClass.getVariables().size() > 0){ fsm += getVariables(depth); } //If there are any method declarations get the code for them if(nodeClass.getMethods().size() > 0){ fsm += getMethods(depth); } //If there are any subclasses get them and print their code. if(nodeClass.getSubClasses().size() > 0){ //For every subclass get the fsm for(int i = 0; i < nodeClass.getSubClasses().size(); i++){ //Get the fsm fsm += new BehaviorWriter(nodeClass.getSubClasses().get(i)).getClassDef(depth+1); } } //if there is a setup machine get the setupmachine if(nodeClass.getSetupMachine() != null){ fsm += getSetup(); } fsm += "\n\n" + indent + "}\n\n"; return fsm; } //Method to set optional comment. public void setComment(String comment){ this.comment = comment; } //Method to get node declarations. public String getNodes(){ //Create string to return String nodes = ""; //Create list of nodeinstance objects from setup object. ArrayList<NodeInstance> nodeList = this.setup.getNodes(); //For every node in the setupmachine for(int i = 0; i < nodeList.size(); i++){ //Get the current node instance object. NodeInstance current = nodeList.get(i); //Print its label: constructorname nodes += "\n\t\t" + current.getLabel() + ": " + current.getType().getConstructor().getName(); //if any parameters if(current.getNumOfParameters() > 0){ //open parantheses nodes += "("; //for every parameter in the constructor for(int j = 0; j < current.getNumOfParameters(); j++){ //get the value of parameter and add to the string nodes += current.getParameters().get(j).getValue(); if(j != current.getNumOfParameters()-1){ nodes += ", "; } } //close paranteses of the constructor nodes += ")\n"; } } return nodes; } //Method to get the transitions public String getTransitions(){ //Create string to return String transitions = ""; //Create transition instance objects from the setup object. ArrayList<TransitionInstance> transList = this.setup.getTransitions(); //for every transition initialized for(int i = 0; i < transList.size(); i++){ transitions += "\t\t"; //Get current transition instance TransitionInstance current = transList.get(i); //Get sources and targets ArrayList<NodeInstance> sources = current.getSources(); ArrayList<NodeInstance> targets = current.getTargets(); //if there are multiple sources if(current.getNumOfSources() > 1){ //open curly braces to put labels of nodes in. transitions += "{"; //for every source for(int j = 0; j < current.getNumOfSources(); j++){ - transitions += sources.get(j).getLabel() + " "; + transitions += sources.get(j).getLabel(); if(j != current.getNumOfSources()-1){ transitions += ", "; } } //close curly braces transitions += "}"; }else{ //print label of the source transitions += current.getSources().get(0).getLabel(); } //get transition constructor. ConstructorCall currentTransitionConstructor = current.getType().getConstructor(); //Get current transition constructor name transitions += " =" + currentTransitionConstructor.getName(); //if current transition constructor has any parameters if(currentTransitionConstructor.getParameters().size() > 0){ transitions += "("; //for every parameter of transition. for(int h = 0; h < currentTransitionConstructor.getParameters().size(); h++){ transitions += currentTransitionConstructor.getParameters().get(h).getValue(); if(h != currentTransitionConstructor.getParameters().size()-1){ transitions += ", "; } } transitions += ")"; } transitions += "=> "; //if there are multiple targets if(current.getNumOfTargets() > 1){ //open curly braces to put labels of nodes in. transitions += "{"; //for every source for(int j = 0; j < current.getNumOfTargets(); j++){ //print the label transitions += targets.get(j).getLabel(); if(j != current.getNumOfTargets()-1){ transitions += ", "; } } //close curly braces transitions += "}"; }else{ //print label of the target transitions += current.getTargets().get(0).getLabel() + " "; } //go to the next line transitions += "\n"; } //return the transitions return transitions; } //Method to get meat. public String getMeat(){ //Add string to create the meat. String meat = getNodes() + "\n\n" + getTransitions(); return meat; } //get header method to get the class header public String getHeader(int depth){ String indent = ""; for(int i = 0; i < depth; i++){ indent += "\t"; } String classHeader = indent + comment; classHeader += indent + "$nodeclass " + nodeClass.getName() + " : " + "StateNode {\n\n"; return classHeader; } //getsetup method that calls get meat and other string to form the setupmachine block. public String getSetup(){ //String to store the the block. String setup = "\t//Setupmachine for the behavior\n"; //header setup += "\t$setupmachine {\n\n"; //meat setup += getMeat(); //close block setup += "\n\t}\n\n"; return setup; } //getVariables method to get the code of variable declarations. public String getVariables(int depth){ String indent = ""; for(int i = 0; i < depth+1; i++){ indent += "\t"; } //Initialize string with method and return String vars = indent + "//Variable declarations\n"; //For each variable, make a new line and print code. for(int i = 0; i < nodeClass.getVariables().size(); i++){ //Add provide keyword. vars += indent + "$provide "; //Add type name vars += nodeClass.getVariables().get(i).getType() + " "; //Add variable name vars += nodeClass.getVariables().get(i).getName() + ";"; } vars += "\n\n"; return vars; } //Method to get the method declarations including dostart etc if there is. public String getMethods(int depth){ String indent = ""; for(int i = 0; i < depth+1; i++){ indent += "\t"; } //Initialize holding string with comment and return String mets = indent + "//Method declarations\n"; //For each method print the code for(int i = 0; i < nodeClass.getMethods().size(); i++){ //Get the current method. Method met = nodeClass.getMethods().get(i); //Add keyword virtual mets += indent + "virtual "; //Add the returntype mets += met.getReturnType() + " "; //Add the name of the method and open paranthesis. mets += met.getName() + "("; //for each parameter in the method print the type and name. for(int j = 0; j < met.getParameters().size(); j++){ mets += met.getParameter(j).getType() + " "; mets += met.getParameter(j).getName(); //if not the last one put a comma after if(j != met.getParameters().size()-1){ mets += ", "; } }//End parameters //close the parameter open the curly braces and jump to the next line mets += "){\n"; //print the body of the method which will be edited as string in the editor. mets += "\n" + indent + met.getBody() + "\n\n"; //close method braces mets += "\n\n" + indent + "}\n\n"; }//End single method //return the code return mets; } }
true
true
public String getTransitions(){ //Create string to return String transitions = ""; //Create transition instance objects from the setup object. ArrayList<TransitionInstance> transList = this.setup.getTransitions(); //for every transition initialized for(int i = 0; i < transList.size(); i++){ transitions += "\t\t"; //Get current transition instance TransitionInstance current = transList.get(i); //Get sources and targets ArrayList<NodeInstance> sources = current.getSources(); ArrayList<NodeInstance> targets = current.getTargets(); //if there are multiple sources if(current.getNumOfSources() > 1){ //open curly braces to put labels of nodes in. transitions += "{"; //for every source for(int j = 0; j < current.getNumOfSources(); j++){ transitions += sources.get(j).getLabel() + " "; if(j != current.getNumOfSources()-1){ transitions += ", "; } } //close curly braces transitions += "}"; }else{ //print label of the source transitions += current.getSources().get(0).getLabel(); } //get transition constructor. ConstructorCall currentTransitionConstructor = current.getType().getConstructor(); //Get current transition constructor name transitions += " =" + currentTransitionConstructor.getName(); //if current transition constructor has any parameters if(currentTransitionConstructor.getParameters().size() > 0){ transitions += "("; //for every parameter of transition. for(int h = 0; h < currentTransitionConstructor.getParameters().size(); h++){ transitions += currentTransitionConstructor.getParameters().get(h).getValue(); if(h != currentTransitionConstructor.getParameters().size()-1){ transitions += ", "; } } transitions += ")"; } transitions += "=> "; //if there are multiple targets if(current.getNumOfTargets() > 1){ //open curly braces to put labels of nodes in. transitions += "{"; //for every source for(int j = 0; j < current.getNumOfTargets(); j++){ //print the label transitions += targets.get(j).getLabel(); if(j != current.getNumOfTargets()-1){ transitions += ", "; } } //close curly braces transitions += "}"; }else{ //print label of the target transitions += current.getTargets().get(0).getLabel() + " "; } //go to the next line transitions += "\n"; } //return the transitions return transitions; }
public String getTransitions(){ //Create string to return String transitions = ""; //Create transition instance objects from the setup object. ArrayList<TransitionInstance> transList = this.setup.getTransitions(); //for every transition initialized for(int i = 0; i < transList.size(); i++){ transitions += "\t\t"; //Get current transition instance TransitionInstance current = transList.get(i); //Get sources and targets ArrayList<NodeInstance> sources = current.getSources(); ArrayList<NodeInstance> targets = current.getTargets(); //if there are multiple sources if(current.getNumOfSources() > 1){ //open curly braces to put labels of nodes in. transitions += "{"; //for every source for(int j = 0; j < current.getNumOfSources(); j++){ transitions += sources.get(j).getLabel(); if(j != current.getNumOfSources()-1){ transitions += ", "; } } //close curly braces transitions += "}"; }else{ //print label of the source transitions += current.getSources().get(0).getLabel(); } //get transition constructor. ConstructorCall currentTransitionConstructor = current.getType().getConstructor(); //Get current transition constructor name transitions += " =" + currentTransitionConstructor.getName(); //if current transition constructor has any parameters if(currentTransitionConstructor.getParameters().size() > 0){ transitions += "("; //for every parameter of transition. for(int h = 0; h < currentTransitionConstructor.getParameters().size(); h++){ transitions += currentTransitionConstructor.getParameters().get(h).getValue(); if(h != currentTransitionConstructor.getParameters().size()-1){ transitions += ", "; } } transitions += ")"; } transitions += "=> "; //if there are multiple targets if(current.getNumOfTargets() > 1){ //open curly braces to put labels of nodes in. transitions += "{"; //for every source for(int j = 0; j < current.getNumOfTargets(); j++){ //print the label transitions += targets.get(j).getLabel(); if(j != current.getNumOfTargets()-1){ transitions += ", "; } } //close curly braces transitions += "}"; }else{ //print label of the target transitions += current.getTargets().get(0).getLabel() + " "; } //go to the next line transitions += "\n"; } //return the transitions return transitions; }
diff --git a/model/org/eclipse/cdt/internal/core/model/CModelBuilder2.java b/model/org/eclipse/cdt/internal/core/model/CModelBuilder2.java index 246a5c45b..3d7961b9e 100644 --- a/model/org/eclipse/cdt/internal/core/model/CModelBuilder2.java +++ b/model/org/eclipse/cdt/internal/core/model/CModelBuilder2.java @@ -1,1262 +1,1263 @@ /******************************************************************************* * Copyright (c) 2006 Wind River Systems, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Anton Leherbauer (Wind River Systems) - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.internal.core.model; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Stack; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ast.ASTSignatureUtil; import org.eclipse.cdt.core.dom.ast.DOMException; import org.eclipse.cdt.core.dom.ast.IASTASMDeclaration; import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier; import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier; import org.eclipse.cdt.core.dom.ast.IASTDeclaration; import org.eclipse.cdt.core.dom.ast.IASTDeclarator; import org.eclipse.cdt.core.dom.ast.IASTElaboratedTypeSpecifier; import org.eclipse.cdt.core.dom.ast.IASTEnumerationSpecifier; import org.eclipse.cdt.core.dom.ast.IASTExpression; import org.eclipse.cdt.core.dom.ast.IASTFieldDeclarator; import org.eclipse.cdt.core.dom.ast.IASTFileLocation; import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator; import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition; import org.eclipse.cdt.core.dom.ast.IASTMacroExpansion; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNamedTypeSpecifier; import org.eclipse.cdt.core.dom.ast.IASTNode; import org.eclipse.cdt.core.dom.ast.IASTNodeLocation; import org.eclipse.cdt.core.dom.ast.IASTPreprocessorIncludeStatement; import org.eclipse.cdt.core.dom.ast.IASTPreprocessorMacroDefinition; import org.eclipse.cdt.core.dom.ast.IASTProblem; import org.eclipse.cdt.core.dom.ast.IASTProblemDeclaration; import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclSpecifier; import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration; import org.eclipse.cdt.core.dom.ast.IASTStandardFunctionDeclarator; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.dom.ast.IScope; import org.eclipse.cdt.core.dom.ast.IASTEnumerationSpecifier.IASTEnumerator; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTDeclSpecifier; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTElaboratedTypeSpecifier; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTExplicitTemplateInstantiation; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionDeclarator; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTLinkageSpecification; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceAlias; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceDefinition; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTQualifiedName; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateDeclaration; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateId; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateSpecialization; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTUsingDeclaration; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTUsingDirective; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTVisiblityLabel; import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassScope; import org.eclipse.cdt.core.dom.ast.cpp.ICPPConstructor; import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier.ICPPASTBaseSpecifier; import org.eclipse.cdt.core.index.IIndex; import org.eclipse.cdt.core.model.CModelException; import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.IContributedModelBuilder; import org.eclipse.cdt.core.model.IProblemRequestor; import org.eclipse.cdt.core.model.IStructure; import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.parser.IProblem; import org.eclipse.cdt.core.parser.Keywords; import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; import org.eclipse.cdt.internal.core.dom.parser.IASTAmbiguousDeclaration; import org.eclipse.cdt.internal.core.dom.parser.IASTDeclarationAmbiguity; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPVisitor; /** * Build TranslationUnit structure from an <code>IASTTranslationUnit</code>. * * @since 4.0 */ public class CModelBuilder2 implements IContributedModelBuilder { private static final boolean PRINT_PROBLEMS= false; private static class ProblemPrinter implements IProblemRequestor { public void acceptProblem(IProblem problem) { System.err.println("PROBLEM: " + problem.getMessage()); //$NON-NLS-1$ } public void beginReporting() { } public void endReporting() { } public boolean isActive() { return true; } } /** * Adapts {@link IASTProblem} to {@link IProblem). */ private static class ProblemAdapter implements IProblem { private IASTProblem fASTProblem; /** * @param problem */ public ProblemAdapter(IASTProblem problem) { fASTProblem= problem; } /* * @see org.eclipse.cdt.core.parser.IProblem#checkCategory(int) */ public boolean checkCategory(int bitmask) { return fASTProblem.checkCategory(bitmask); } /* * @see org.eclipse.cdt.core.parser.IProblem#getArguments() */ public String getArguments() { return fASTProblem.getArguments(); } /* * @see org.eclipse.cdt.core.parser.IProblem#getID() */ public int getID() { return fASTProblem.getID(); } /* * @see org.eclipse.cdt.core.parser.IProblem#getMessage() */ public String getMessage() { return fASTProblem.getMessage(); } /* * @see org.eclipse.cdt.core.parser.IProblem#getOriginatingFileName() */ public char[] getOriginatingFileName() { return fASTProblem.getContainingFilename().toCharArray(); } /* * @see org.eclipse.cdt.core.parser.IProblem#getSourceEnd() */ public int getSourceEnd() { IASTFileLocation location= fASTProblem.getFileLocation(); if (location != null) { return location.getNodeOffset() + location.getNodeLength() - 1; } return -1; } /* * @see org.eclipse.cdt.core.parser.IProblem#getSourceLineNumber() */ public int getSourceLineNumber() { IASTFileLocation location= fASTProblem.getFileLocation(); if (location != null) { return location.getStartingLineNumber(); } return -1; } /* * @see org.eclipse.cdt.core.parser.IProblem#getSourceStart() */ public int getSourceStart() { IASTFileLocation location= fASTProblem.getFileLocation(); if (location != null) { return location.getNodeOffset(); } return -1; } /* * @see org.eclipse.cdt.core.parser.IProblem#isError() */ public boolean isError() { return fASTProblem.isError(); } /* * @see org.eclipse.cdt.core.parser.IProblem#isWarning() */ public boolean isWarning() { return fASTProblem.isWarning(); } } private final TranslationUnit fTranslationUnit; private String fTranslationUnitFileName; private ASTAccessVisibility fCurrentVisibility; private Stack fVisibilityStack; /** * Create a model builder for the given translation unit. * * @param tu the translation unit (must be a {@link TranslationUnit} */ public CModelBuilder2(ITranslationUnit tu) { fTranslationUnit= (TranslationUnit)tu; } /* * @see org.eclipse.cdt.core.model.IContributedModelBuilder#parse(boolean) */ public void parse(boolean quickParseMode) throws Exception { IIndex index= CCorePlugin.getIndexManager().getIndex(fTranslationUnit.getCProject()); try { if (index != null) { try { index.acquireReadLock(); } catch (InterruptedException ie) { index= null; } } long startTime= System.currentTimeMillis(); final IASTTranslationUnit ast= fTranslationUnit.getAST(index, quickParseMode ? ITranslationUnit.AST_SKIP_ALL_HEADERS : 0); if (ast == null) { return; } Util.debugLog("CModelBuilder2: parsing " //$NON-NLS-1$ + fTranslationUnit.getElementName() + " mode="+ (quickParseMode ? "fast " : "full ") //$NON-NLS-1$ //$NON-NLS-2$ + " time="+ ( System.currentTimeMillis() - startTime ) + "ms", //$NON-NLS-1$ //$NON-NLS-2$ IDebugLogConstants.MODEL, false); startTime= System.currentTimeMillis(); buildModel(ast); fTranslationUnit.getElementInfo().setIsStructureKnown(true); Util.debugLog("CModelBuilder2: building " //$NON-NLS-1$ +"children="+ fTranslationUnit.getElementInfo().internalGetChildren().size() //$NON-NLS-1$ +" time="+ (System.currentTimeMillis() - startTime) + "ms", //$NON-NLS-1$ //$NON-NLS-2$ IDebugLogConstants.MODEL, false); } finally { if (index != null) { index.releaseReadLock(); } } } /** * Build the model from the given AST. * @param ast * @throws CModelException * @throws DOMException */ private void buildModel(IASTTranslationUnit ast) throws CModelException, DOMException { fTranslationUnitFileName= ast.getFilePath(); fVisibilityStack= new Stack(); // includes final IASTPreprocessorIncludeStatement[] includeDirectives= ast.getIncludeDirectives(); for (int i= 0; i < includeDirectives.length; i++) { IASTPreprocessorIncludeStatement includeDirective= includeDirectives[i]; if (isLocalToFile(includeDirective)) { createInclusion(fTranslationUnit, includeDirective); } } // problem includes final IASTProblem[] ppProblems= ast.getPreprocessorProblems(); for (int i= 0; i < ppProblems.length; i++) { IASTProblem problem= ppProblems[i]; if (problem.getID() == IASTProblem.PREPROCESSOR_INCLUSION_NOT_FOUND) { if (isLocalToFile(problem)) { createProblemInclusion(fTranslationUnit, problem); } } } // macros final IASTPreprocessorMacroDefinition[] macroDefinitions= ast.getMacroDefinitions(); for (int i= 0; i < macroDefinitions.length; i++) { IASTPreprocessorMacroDefinition macroDefinition= macroDefinitions[i]; if (isLocalToFile(macroDefinition)) { createMacro(fTranslationUnit, macroDefinition); } } // declarations final IASTDeclaration[] declarations= ast.getDeclarations(); for (int i= 0; i < declarations.length; i++) { IASTDeclaration declaration= declarations[i]; if (isLocalToFile(declaration)) { createDeclaration(fTranslationUnit, declaration); } } // sort by offset final List children= fTranslationUnit.getElementInfo().internalGetChildren(); Collections.sort(children, new Comparator() { public int compare(Object o1, Object o2) { try { final SourceManipulation element1= (SourceManipulation)o1; final SourceManipulation element2= (SourceManipulation)o2; return element1.getSourceManipulationInfo().getStartPos() - element2.getSourceManipulationInfo().getStartPos(); } catch (CModelException exc) { return 0; } }}); // report problems IProblemRequestor problemRequestor= fTranslationUnit.getProblemRequestor(); if (problemRequestor == null && PRINT_PROBLEMS) { problemRequestor= new ProblemPrinter(); } if (problemRequestor != null && problemRequestor.isActive()) { problemRequestor.beginReporting(); IASTProblem[] problems= ppProblems; for (int i= 0; i < problems.length; i++) { IASTProblem problem= problems[i]; if (isLocalToFile(problem)) { problemRequestor.acceptProblem(new ProblemAdapter(problem)); } else if (PRINT_PROBLEMS) { System.err.println("PREPROCESSOR PROBLEM: " + problem.getMessage()); //$NON-NLS-1$ } } problems= CPPVisitor.getProblems(ast); for (int i= 0; i < problems.length; i++) { IASTProblem problem= problems[i]; if (isLocalToFile(problem)) { problemRequestor.acceptProblem(new ProblemAdapter(problem)); } else if (PRINT_PROBLEMS) { System.err.println("PROBLEM: " + problem.getMessage()); //$NON-NLS-1$ } } problemRequestor.endReporting(); } } private boolean isLocalToFile(IASTNode node) { return fTranslationUnitFileName.equals(node.getContainingFilename()); } private Include createInclusion(Parent parent, IASTPreprocessorIncludeStatement inclusion) throws CModelException{ // create element final IASTName name= inclusion.getName(); Include element= new Include(parent, ASTStringUtil.getSimpleName(name), inclusion.isSystemInclude()); element.setFullPathName(inclusion.getPath()); // add to parent parent.addChild(element); // set positions setIdentifierPosition(element, name); setBodyPosition(element, inclusion); return element; } private Include createProblemInclusion(Parent parent, IASTProblem problem) throws CModelException { // create element String name= problem.getArguments(); if (name == null || name.length() == 0) { return null; } String signature= problem.getRawSignature(); int nameIdx= signature.indexOf(name); boolean isStandard= false; if (nameIdx > 0) { isStandard= signature.charAt(nameIdx-1) == '<'; } Include element= new Include(parent, name, isStandard); // add to parent parent.addChild(element); // set positions if (nameIdx > 0) { final IASTFileLocation problemLocation= problem.getFileLocation(); if (problemLocation != null) { final int startOffset= problemLocation.getNodeOffset(); element.setIdPos(startOffset + nameIdx, name.length()); } } else { setIdentifierPosition(element, problem); } setBodyPosition(element, problem); return element; } private Macro createMacro(Parent parent, IASTPreprocessorMacroDefinition macro) throws CModelException{ // create element final IASTName name= macro.getName(); Macro element= new Macro(parent, ASTStringUtil.getSimpleName(name)); // add to parent parent.addChild(element); // set positions setIdentifierPosition(element, name); setBodyPosition(element, macro); return element; } private void createDeclaration(Parent parent, IASTDeclaration declaration) throws CModelException, DOMException { if (declaration instanceof IASTFunctionDefinition) { createFunctionDefinition(parent, (IASTFunctionDefinition)declaration, false); } else if (declaration instanceof IASTSimpleDeclaration) { createSimpleDeclarations(parent, (IASTSimpleDeclaration)declaration, false); } else if (declaration instanceof ICPPASTVisiblityLabel) { handleVisibilityLabel((ICPPASTVisiblityLabel)declaration); } else if(declaration instanceof ICPPASTNamespaceDefinition) { createNamespace(parent, (ICPPASTNamespaceDefinition) declaration); } else if (declaration instanceof ICPPASTNamespaceAlias) { // TODO [cmodel] namespace alias? } else if (declaration instanceof ICPPASTTemplateDeclaration) { createTemplateDeclaration(parent, (ICPPASTTemplateDeclaration)declaration); } else if (declaration instanceof ICPPASTTemplateSpecialization) { // TODO [cmodel] template specialization? } else if (declaration instanceof ICPPASTExplicitTemplateInstantiation) { // TODO [cmodel] explicit template instantiation? } else if (declaration instanceof ICPPASTUsingDeclaration) { createUsingDeclaration(parent, (ICPPASTUsingDeclaration)declaration); } else if (declaration instanceof ICPPASTUsingDirective) { createUsingDirective(parent, (ICPPASTUsingDirective)declaration); } else if (declaration instanceof ICPPASTLinkageSpecification) { createLinkageSpecification(parent, (ICPPASTLinkageSpecification)declaration); } else if (declaration instanceof IASTASMDeclaration) { // TODO [cmodel] asm declaration? } else if (declaration instanceof IASTProblemDeclaration) { // TODO [cmodel] problem declaration? } else if (declaration instanceof IASTAmbiguousDeclaration) { // TODO [cmodel] ambiguous declaration? } else if (declaration instanceof IASTDeclarationAmbiguity) { // TODO [cmodel] declaration ambiguity? } else { assert false : "TODO: " + declaration.getClass().getName(); //$NON-NLS-1$ } } private void createTemplateDeclaration(Parent parent, ICPPASTTemplateDeclaration templateDeclaration) throws CModelException, DOMException { IASTDeclaration declaration= templateDeclaration.getDeclaration(); if (declaration instanceof IASTFunctionDefinition) { CElement element= createFunctionDefinition(parent, (IASTFunctionDefinition)declaration, true); String[] parameterTypes= ASTStringUtil.getTemplateParameterArray(templateDeclaration.getTemplateParameters()); // set the template parameters if (element instanceof FunctionTemplate) { FunctionTemplate functionTemplate= (FunctionTemplate) element; functionTemplate.setTemplateParameterTypes(parameterTypes); } else if (element instanceof MethodTemplate) { MethodTemplate methodTemplate= (MethodTemplate) element; methodTemplate.setTemplateParameterTypes(parameterTypes); } // set the body position if (element instanceof SourceManipulation) { setBodyPosition((SourceManipulation)element, templateDeclaration); } } else if (declaration instanceof IASTSimpleDeclaration) { CElement[] elements= createSimpleDeclarations(parent, (IASTSimpleDeclaration)declaration, true); String[] parameterTypes= ASTStringUtil.getTemplateParameterArray(templateDeclaration.getTemplateParameters()); for (int i= 0; i < elements.length; i++) { CElement element= elements[i]; // set the template parameters if (element instanceof StructureTemplate) { StructureTemplate classTemplate= (StructureTemplate) element; classTemplate.setTemplateParameterTypes(parameterTypes); } else if (element instanceof StructureTemplateDeclaration) { StructureTemplateDeclaration classTemplate= (StructureTemplateDeclaration) element; classTemplate.setTemplateParameterTypes(parameterTypes); } else if (element instanceof VariableTemplate) { VariableTemplate varTemplate= (VariableTemplate) element; varTemplate.setTemplateParameterTypes(parameterTypes); } else if (element instanceof FunctionTemplateDeclaration) { FunctionTemplateDeclaration functionTemplate= (FunctionTemplateDeclaration) element; functionTemplate.setTemplateParameterTypes(parameterTypes); } else if (element instanceof MethodTemplateDeclaration) { MethodTemplateDeclaration methodTemplate= (MethodTemplateDeclaration) element; methodTemplate.setTemplateParameterTypes(parameterTypes); } else if (element instanceof FunctionTemplate) { FunctionTemplate functionTemplate= (FunctionTemplate) element; functionTemplate.setTemplateParameterTypes(parameterTypes); } else if (element instanceof MethodTemplate) { MethodTemplate methodTemplate= (MethodTemplate) element; methodTemplate.setTemplateParameterTypes(parameterTypes); } // set the body position if (element instanceof SourceManipulation) { setBodyPosition((SourceManipulation)element, templateDeclaration); } } } else if (declaration instanceof IASTProblemDeclaration) { // ignore problem declarations } else { assert false : "TODO: " + declaration.getClass().getName(); //$NON-NLS-1$ } } /** * Handle extern "C" and related kinds. * * @param parent * @param declaration * @throws CModelException * @throws DOMException */ private void createLinkageSpecification(Parent parent, ICPPASTLinkageSpecification linkageDeclaration) throws CModelException, DOMException { IASTDeclaration[] declarations= linkageDeclaration.getDeclarations(); for (int i= 0; i < declarations.length; i++) { IASTDeclaration declaration= declarations[i]; createDeclaration(parent, declaration); } } private CElement[] createSimpleDeclarations(Parent parent, IASTSimpleDeclaration declaration, boolean isTemplate) throws CModelException, DOMException { final IASTDeclSpecifier declSpecifier= declaration.getDeclSpecifier(); final IASTDeclarator[] declarators= declaration.getDeclarators(); final CElement[] elements; if (declarators.length > 0) { elements= new CElement[declarators.length]; for (int i= 0; i < declarators.length; i++) { final IASTDeclarator declarator= declarators[i]; final CElement element= createSimpleDeclaration(parent, declSpecifier, declarator, isTemplate); // if (!isTemplate && element instanceof SourceManipulation) { // setBodyPosition((SourceManipulation)element, declaration); // } elements[i]= element; } } else { elements= new CElement[1]; final CElement element= createSimpleDeclaration(parent, declSpecifier, null, isTemplate); elements[0]= element; } return elements; } private CElement createSimpleDeclaration(Parent parent, IASTDeclSpecifier declSpecifier, IASTDeclarator declarator, boolean isTemplate) throws CModelException, DOMException { if (declSpecifier instanceof IASTCompositeTypeSpecifier) { final CElement compositeType= createCompositeType(parent, (IASTCompositeTypeSpecifier)declSpecifier, isTemplate); if (declarator != null) { return createTypedefOrFunctionOrVariable(parent, declSpecifier, declarator, isTemplate); } return compositeType; } else if (declSpecifier instanceof IASTElaboratedTypeSpecifier) { if (declarator == null) { return createElaboratedTypeDeclaration(parent, (IASTElaboratedTypeSpecifier)declSpecifier, isTemplate); } else { return createTypedefOrFunctionOrVariable(parent, declSpecifier, declarator, isTemplate); } } else if (declSpecifier instanceof IASTEnumerationSpecifier) { return createEnumeration(parent, (IASTEnumerationSpecifier)declSpecifier); } else if (declSpecifier instanceof IASTNamedTypeSpecifier) { return createTypedefOrFunctionOrVariable(parent, declSpecifier, declarator, isTemplate); } else if (declSpecifier instanceof IASTSimpleDeclSpecifier) { return createTypedefOrFunctionOrVariable(parent, declSpecifier, declarator, isTemplate); } else { assert false : "TODO: " + declSpecifier.getClass().getName(); //$NON-NLS-1$ } return null; } private CElement createTypedefOrFunctionOrVariable(Parent parent, IASTDeclSpecifier declSpecifier, IASTDeclarator declarator, boolean isTemplate) throws CModelException { if (declSpecifier.getStorageClass() == IASTDeclSpecifier.sc_typedef) { return createTypeDef(parent, declSpecifier, declarator); } if (declarator != null) { IASTDeclarator nestedDeclarator= declarator.getNestedDeclarator(); if (nestedDeclarator == null && declarator instanceof IASTFunctionDeclarator) { return createFunctionDeclaration(parent, declSpecifier, (IASTFunctionDeclarator)declarator, isTemplate); } } return createVariable(parent, declSpecifier, declarator, isTemplate); } private void createNamespace(Parent parent, ICPPASTNamespaceDefinition declaration) throws CModelException, DOMException{ // create element final String type= Keywords.NAMESPACE; final IASTName name= declaration.getName(); String nsName= ASTStringUtil.getQualifiedName(name); final Namespace element= new Namespace (parent, nsName); // add to parent parent.addChild(element); // set positions if (name != null && nsName.length() > 0) { setIdentifierPosition(element, name); } else { final IASTFileLocation nsLocation= getMinFileLocation(declaration.getNodeLocations()); if (nsLocation != null) { element.setIdPos(nsLocation.getNodeOffset(), type.length()); } } setBodyPosition(element, declaration); element.setTypeName(type); IASTDeclaration[] nsDeclarations= declaration.getDeclarations(); for (int i= 0; i < nsDeclarations.length; i++) { IASTDeclaration nsDeclaration= nsDeclarations[i]; createDeclaration(element, nsDeclaration); } } private StructureDeclaration createElaboratedTypeDeclaration(Parent parent, IASTElaboratedTypeSpecifier elaboratedTypeSpecifier, boolean isTemplate) throws CModelException{ // create element final String type; final int kind; switch (elaboratedTypeSpecifier.getKind()) { case IASTElaboratedTypeSpecifier.k_struct: kind= (isTemplate) ? ICElement.C_TEMPLATE_STRUCT : ICElement.C_STRUCT; type= Keywords.STRUCT; break; case IASTElaboratedTypeSpecifier.k_union: kind= (isTemplate) ? ICElement.C_TEMPLATE_UNION : ICElement.C_UNION; type= Keywords.UNION; break; case ICPPASTElaboratedTypeSpecifier.k_class: kind= (isTemplate) ? ICElement.C_TEMPLATE_CLASS : ICElement.C_CLASS; type= Keywords.CLASS; break; default: kind= ICElement.C_CLASS; type= ""; //$NON-NLS-1$ break; } final IASTName astClassName= elaboratedTypeSpecifier.getName(); final String className= ASTStringUtil.getSimpleName(astClassName); StructureDeclaration element; if (isTemplate) { element= new StructureTemplateDeclaration(parent, kind, className); } else { element= new StructureDeclaration(parent, className, kind); } element.setTypeName(type); // add to parent parent.addChild(element); // set positions if (className.length() > 0) { setIdentifierPosition(element, astClassName); } else { final IASTFileLocation classLocation= getMinFileLocation(elaboratedTypeSpecifier.getNodeLocations()); if (classLocation != null) { element.setIdPos(classLocation.getNodeOffset(), type.length()); } } setBodyPosition(element, elaboratedTypeSpecifier); return element; } private Enumeration createEnumeration(Parent parent, IASTEnumerationSpecifier enumSpecifier) throws CModelException{ // create element final String type= Keywords.ENUM; final IASTName astEnumName= enumSpecifier.getName(); final String enumName= ASTStringUtil.getSimpleName(astEnumName); final Enumeration element= new Enumeration (parent, enumName); // add to parent parent.addChild(element); final IASTEnumerator[] enumerators= enumSpecifier.getEnumerators(); for (int i= 0; i < enumerators.length; i++) { final IASTEnumerator enumerator= enumerators[i]; createEnumerator(element, enumerator); } // set enumeration position if (astEnumName != null && enumName.length() > 0) { setIdentifierPosition(element, astEnumName); } else { final IASTFileLocation enumLocation= enumSpecifier.getFileLocation(); element.setIdPos(enumLocation.getNodeOffset(), type.length()); } setBodyPosition(element, enumSpecifier); element.setTypeName(type); return element; } private Enumerator createEnumerator(Parent enumarator, IASTEnumerator enumDef) throws CModelException{ final IASTName astEnumName= enumDef.getName(); final Enumerator element= new Enumerator (enumarator, ASTStringUtil.getSimpleName(astEnumName)); IASTExpression initialValue= enumDef.getValue(); if(initialValue != null){ element.setConstantExpression(ASTSignatureUtil.getExpressionString(initialValue)); } // add to parent enumarator.addChild(element); // set positions setIdentifierPosition(element, astEnumName); setBodyPosition(element, enumDef); return element; } private Structure createCompositeType(Parent parent, IASTCompositeTypeSpecifier compositeTypeSpecifier, boolean isTemplate) throws CModelException, DOMException{ // create element final String type; final int kind; final ASTAccessVisibility defaultVisibility; switch (compositeTypeSpecifier.getKey()) { case IASTCompositeTypeSpecifier.k_struct: kind= (isTemplate) ? ICElement.C_TEMPLATE_STRUCT : ICElement.C_STRUCT; type= Keywords.STRUCT; defaultVisibility= ASTAccessVisibility.PUBLIC; break; case IASTCompositeTypeSpecifier.k_union: kind= (isTemplate) ? ICElement.C_TEMPLATE_UNION : ICElement.C_UNION; type= Keywords.UNION; defaultVisibility= ASTAccessVisibility.PUBLIC; break; case ICPPASTCompositeTypeSpecifier.k_class: kind= (isTemplate) ? ICElement.C_TEMPLATE_CLASS : ICElement.C_CLASS; type= Keywords.CLASS; defaultVisibility= ASTAccessVisibility.PRIVATE; break; default: kind= ICElement.C_CLASS; type= ""; //$NON-NLS-1$ defaultVisibility= ASTAccessVisibility.PUBLIC; break; } final IASTName astClassName= compositeTypeSpecifier.getName(); final String className= ASTStringUtil.getSimpleName(astClassName);; final Structure element; if (!isTemplate) { Structure classElement= new Structure(parent, kind, className); element= classElement; } else { StructureTemplate classTemplate= new StructureTemplate(parent, kind, className); element= classTemplate; } if (compositeTypeSpecifier instanceof ICPPASTCompositeTypeSpecifier) { // store super classes names final ICPPASTCompositeTypeSpecifier cppCompositeTypeSpecifier= (ICPPASTCompositeTypeSpecifier)compositeTypeSpecifier; ICPPASTBaseSpecifier[] baseSpecifiers= cppCompositeTypeSpecifier.getBaseSpecifiers(); for (int i= 0; i < baseSpecifiers.length; i++) { final ICPPASTBaseSpecifier baseSpecifier= baseSpecifiers[i]; final IASTName baseName= baseSpecifier.getName(); final ASTAccessVisibility visibility; switch(baseSpecifier.getVisibility()) { case ICPPASTBaseSpecifier.v_public: visibility= ASTAccessVisibility.PUBLIC; break; case ICPPASTBaseSpecifier.v_protected: visibility= ASTAccessVisibility.PROTECTED; break; case ICPPASTBaseSpecifier.v_private: visibility= ASTAccessVisibility.PRIVATE; break; default: visibility= ASTAccessVisibility.PUBLIC; } element.addSuperClass(ASTStringUtil.getSimpleName(baseName), visibility); } } element.setTypeName(type); // add to parent parent.addChild(element); // set positions if(!isTemplate){ setBodyPosition(element, compositeTypeSpecifier); } if (className.length() > 0) { setIdentifierPosition(element, astClassName); } else { final IASTFileLocation classLocation= getMinFileLocation(compositeTypeSpecifier.getNodeLocations()); if (classLocation != null) { if (compositeTypeSpecifier.getStorageClass() == IASTDeclSpecifier.sc_typedef) { // fix positions for typedef struct (heuristically) final int delta= Keywords.TYPEDEF.length() + 1; element.setIdPos(classLocation.getNodeOffset() + delta, type.length()); if(!isTemplate){ final SourceManipulationInfo info= element.getSourceManipulationInfo(); info.setPos(info.getStartPos() + delta, info.getLength() - delta); } } else { element.setIdPos(classLocation.getNodeOffset(), type.length()); } } } // add members pushDefaultVisibility(defaultVisibility); try { final IASTDeclaration[] memberDeclarations= compositeTypeSpecifier.getMembers(); for (int i= 0; i < memberDeclarations.length; i++) { IASTDeclaration member= memberDeclarations[i]; createDeclaration(element, member); } } finally { popDefaultVisibility(); } return element; } private TypeDef createTypeDef(Parent parent, IASTDeclSpecifier declSpecifier, IASTDeclarator declarator) throws CModelException{ IASTDeclarator nestedDeclarator= declarator; while (nestedDeclarator.getNestedDeclarator() != null) { nestedDeclarator= nestedDeclarator.getNestedDeclarator(); } final IASTName astTypedefName= nestedDeclarator.getName(); if (astTypedefName == null) { return null; } // create the element String name= ASTStringUtil.getSimpleName(astTypedefName); TypeDef element= new TypeDef(parent, name); String typeName= ASTStringUtil.getSignatureString(declSpecifier, declarator); element.setTypeName(typeName); // add to parent parent.addChild(element); // set positions if (name.length() > 0) { setIdentifierPosition(element, astTypedefName); } else { setIdentifierPosition(element, declSpecifier); } setBodyPosition(element, declSpecifier.getParent()); return element; } private VariableDeclaration createVariable(Parent parent, IASTDeclSpecifier specifier, IASTDeclarator declarator, boolean isTemplate) throws CModelException { if (declarator == null) { return null; } IASTDeclarator nestedDeclarator= declarator; while (nestedDeclarator.getNestedDeclarator() != null) { nestedDeclarator= nestedDeclarator.getNestedDeclarator(); } final IASTName astVariableName= nestedDeclarator.getName(); if (astVariableName == null) { return null; } final String variableName= ASTStringUtil.getQualifiedName(astVariableName); final VariableDeclaration element; if (declarator instanceof IASTFieldDeclarator || parent instanceof IStructure || CModelBuilder2.getScope(astVariableName) instanceof ICPPClassScope) { // field Field newElement= new Field(parent, variableName); if (specifier instanceof ICPPASTDeclSpecifier) { final ICPPASTDeclSpecifier cppSpecifier= (ICPPASTDeclSpecifier)specifier; newElement.setMutable(cppSpecifier.getStorageClass() == ICPPASTDeclSpecifier.sc_mutable); } newElement.setVisibility(getCurrentVisibility()); element= newElement; } else { if (isTemplate) { // template variable VariableTemplate newElement= new VariableTemplate(parent, variableName); element= newElement; } else { if (specifier.getStorageClass() == IASTDeclSpecifier.sc_extern) { // variable declaration VariableDeclaration newElement= new VariableDeclaration(parent, variableName); element= newElement; } else { // variable Variable newElement= new Variable(parent, variableName); element= newElement; } } } element.setTypeName(ASTStringUtil.getSignatureString(specifier, declarator)); element.setConst(specifier.isConst()); element.setVolatile(specifier.isVolatile()); // TODO [cmodel] correctly resolve isStatic element.setStatic(specifier.getStorageClass() == IASTDeclSpecifier.sc_static); // add to parent parent.addChild(element); // set positions setIdentifierPosition(element, astVariableName); if (!isTemplate) { setBodyPosition(element, declarator); } return element; } private FunctionDeclaration createFunctionDefinition(Parent parent, IASTFunctionDefinition functionDeclaration, boolean isTemplate) throws CModelException, DOMException { final IASTFunctionDeclarator declarator= functionDeclaration.getDeclarator(); IASTDeclarator nestedDeclarator= declarator; while (nestedDeclarator.getNestedDeclarator() != null) { nestedDeclarator= nestedDeclarator.getNestedDeclarator(); } final IASTName name= nestedDeclarator.getName(); if (name == null) { // Something is wrong, skip this element return null; } final IASTDeclSpecifier declSpecifier= functionDeclaration.getDeclSpecifier(); final String functionName= ASTStringUtil.getSimpleName(name); final String[] parameterTypes= ASTStringUtil.getParameterSignatureArray(declarator); final String returnType= ASTStringUtil.getTypeString(declSpecifier, declarator); final FunctionDeclaration element; if(declarator instanceof ICPPASTFunctionDeclarator) { final ICPPASTFunctionDeclarator cppFunctionDeclarator= (ICPPASTFunctionDeclarator)declarator; final IASTName simpleName; if (name instanceof ICPPASTQualifiedName) { final ICPPASTQualifiedName quName= (ICPPASTQualifiedName)name; simpleName= quName.getLastName(); } else { simpleName= name; } IScope scope= null; // try to avoid expensive resolution of scope and binding boolean isMethod= parent instanceof IStructure; if (!isMethod && name instanceof ICPPASTQualifiedName) { final IASTName[] names= ((ICPPASTQualifiedName)name).getNames(); if (isTemplate) { for (int i= 0; i < names.length; i++) { if (names[i] instanceof ICPPASTTemplateId) { isMethod= true; break; } } } if (!isMethod) { scope= CPPVisitor.getContainingScope(simpleName); isMethod= scope instanceof ICPPClassScope; } } if (isMethod) { // method final MethodDeclaration methodElement; if (isTemplate) { methodElement= new MethodTemplate(parent, ASTStringUtil.getQualifiedName(name)); } else { methodElement= new Method(parent, ASTStringUtil.getQualifiedName(name)); } element= methodElement; - final ICPPMethod methodBinding; + ICPPMethod methodBinding= null; if (scope != null) { - methodBinding= (ICPPMethod)simpleName.getBinding(); - } else { - methodBinding= null; + final IBinding binding= simpleName.getBinding(); + if (binding instanceof ICPPMethod) { + methodBinding= (ICPPMethod)binding; + } } if (methodBinding != null) { methodElement.setVirtual(methodBinding.isVirtual()); methodElement.setInline(methodBinding.isInline()); methodElement.setFriend(((ICPPASTDeclSpecifier)declSpecifier).isFriend()); methodElement.setVolatile(cppFunctionDeclarator.isVolatile()); methodElement.setVisibility(adaptVisibilityConstant(methodBinding.getVisibility())); methodElement.setConst(cppFunctionDeclarator.isConst()); methodElement.setPureVirtual(false); methodElement.setConstructor(methodBinding instanceof ICPPConstructor); methodElement.setDestructor(methodBinding.isDestructor()); } else { if (declSpecifier instanceof ICPPASTDeclSpecifier) { final ICPPASTDeclSpecifier cppDeclSpecifier= (ICPPASTDeclSpecifier)declSpecifier; methodElement.setVirtual(cppDeclSpecifier.isVirtual()); methodElement.setInline(cppDeclSpecifier.isInline()); methodElement.setFriend(cppDeclSpecifier.isFriend()); } methodElement.setVolatile(cppFunctionDeclarator.isVolatile()); methodElement.setVisibility(getCurrentVisibility()); methodElement.setConst(cppFunctionDeclarator.isConst()); methodElement.setPureVirtual(false); final boolean isConstructor; if (scope != null) { isConstructor= CPPVisitor.isConstructor(scope, declarator); } else { isConstructor= parent.getElementName().equals(functionName); } methodElement.setConstructor(isConstructor); methodElement.setDestructor(functionName.charAt(0) == '~'); } } else { if (isTemplate) { // template function element= new FunctionTemplate(parent, ASTStringUtil.getQualifiedName(name)); } else { // function element= new Function(parent, ASTStringUtil.getQualifiedName(name)); } } } else { element= new Function(parent, functionName); } element.setParameterTypes(parameterTypes); element.setReturnType(returnType); // TODO [cmodel] correctly resolve isStatic element.setStatic(declSpecifier.getStorageClass() == IASTDeclSpecifier.sc_static); // add to parent parent.addChild(element); // set positions setIdentifierPosition(element, name); if (!isTemplate) { setBodyPosition(element, functionDeclaration); } return element; } private FunctionDeclaration createFunctionDeclaration(Parent parent, IASTDeclSpecifier declSpecifier, IASTFunctionDeclarator declarator, boolean isTemplate) throws CModelException { IASTDeclarator nestedDeclarator= declarator; while (nestedDeclarator.getNestedDeclarator() != null) { nestedDeclarator= nestedDeclarator.getNestedDeclarator(); } final IASTName name= nestedDeclarator.getName(); if (name == null) { // Something is wrong, skip this element return null; } final String functionName= ASTStringUtil.getSimpleName(name); final String[] parameterTypes= ASTStringUtil.getParameterSignatureArray(declarator); final String returnType= ASTStringUtil.getTypeString(declSpecifier, declarator); final FunctionDeclaration element; if(declarator instanceof ICPPASTFunctionDeclarator) { final ICPPASTFunctionDeclarator cppFunctionDeclarator= (ICPPASTFunctionDeclarator)declarator; if (parent instanceof IStructure) { // method final MethodDeclaration methodElement; if (isTemplate) { methodElement= new MethodTemplateDeclaration(parent, functionName); } else { methodElement= new MethodDeclaration(parent, functionName); } element= methodElement; if (declSpecifier instanceof ICPPASTDeclSpecifier) { final ICPPASTDeclSpecifier cppDeclSpecifier= (ICPPASTDeclSpecifier)declSpecifier; methodElement.setVirtual(cppDeclSpecifier.isVirtual()); methodElement.setInline(cppDeclSpecifier.isInline()); methodElement.setFriend(cppDeclSpecifier.isFriend()); } methodElement.setVolatile(cppFunctionDeclarator.isVolatile()); methodElement.setVisibility(getCurrentVisibility()); methodElement.setConst(cppFunctionDeclarator.isConst()); methodElement.setPureVirtual(cppFunctionDeclarator.isPureVirtual()); methodElement.setConstructor(functionName.equals(parent.getElementName())); methodElement.setDestructor(functionName.charAt(0) == '~'); } else { if (isTemplate) { element= new FunctionTemplateDeclaration(parent, functionName); } else { element= new FunctionDeclaration(parent, functionName); } } } else if (declarator instanceof IASTStandardFunctionDeclarator) { if (isTemplate) { element= new FunctionTemplateDeclaration(parent, functionName); } else { element= new FunctionDeclaration(parent, functionName); } } else { assert false; return null; } element.setParameterTypes(parameterTypes); element.setReturnType(returnType); // TODO [cmodel] correctly resolve isStatic element.setStatic(declSpecifier.getStorageClass() == IASTDeclSpecifier.sc_static); // add to parent parent.addChild(element); // hook up the offsets setIdentifierPosition(element, name); if (!isTemplate) { setBodyPosition(element, declarator); } return element; } private Using createUsingDirective(Parent parent, ICPPASTUsingDirective usingDirDeclaration) throws CModelException{ // create the element IASTName name= usingDirDeclaration.getQualifiedName(); Using element= new Using(parent, ASTStringUtil.getQualifiedName(name), true); // add to parent parent.addChild(element); // set positions setIdentifierPosition(element, name); setBodyPosition(element, usingDirDeclaration); return element; } private Using createUsingDeclaration(Parent parent, ICPPASTUsingDeclaration usingDeclaration) throws CModelException{ // create the element IASTName name= usingDeclaration.getName(); Using element= new Using(parent, ASTStringUtil.getSimpleName(name), false); // add to parent parent.addChild(element); // set positions setIdentifierPosition(element, name); setBodyPosition(element, usingDeclaration); return element; } /** * Utility method to set the body position of an element from an AST node. * * @param element * @param astNode */ private void setBodyPosition(SourceManipulation element, IASTNode astNode) { final IASTFileLocation location= astNode.getFileLocation(); if (location != null) { element.setPos(location.getNodeOffset(), location.getNodeLength()); element.setLines(location.getStartingLineNumber(), location.getEndingLineNumber()); } else { final IASTNodeLocation[] locations= astNode.getNodeLocations(); final IASTFileLocation minLocation= getMinFileLocation(locations); if (minLocation != null) { final IASTFileLocation maxLocation= getMaxFileLocation(locations); if (maxLocation != null) { final int startOffset= minLocation.getNodeOffset(); final int endOffset= maxLocation.getNodeOffset() + maxLocation.getNodeLength(); element.setPos(startOffset, endOffset - startOffset); final int startLine= minLocation.getStartingLineNumber(); final int endLine= maxLocation.getEndingLineNumber(); element.setLines(startLine, endLine); } } } } /** * Utility method to set the identifier position of an element from an AST name. * * @param element * @param astName */ private void setIdentifierPosition(SourceManipulation element, IASTNode astName) { final IASTFileLocation location= astName.getFileLocation(); if (location != null) { element.setIdPos(location.getNodeOffset(), location.getNodeLength()); } else { final IASTNodeLocation[] locations= astName.getNodeLocations(); final IASTFileLocation minLocation= getMinFileLocation(locations); if (minLocation != null) { final IASTFileLocation maxLocation= getMaxFileLocation(locations); if (maxLocation != null) { final int startOffset= minLocation.getNodeOffset(); final int endOffset= maxLocation.getNodeOffset() + maxLocation.getNodeLength(); element.setIdPos(startOffset, endOffset - startOffset); } } } } private static IASTFileLocation getMaxFileLocation(IASTNodeLocation[] locations) { if (locations == null || locations.length == 0) { return null; } final IASTNodeLocation nodeLocation= locations[locations.length-1]; if (nodeLocation instanceof IASTFileLocation) { return (IASTFileLocation)nodeLocation; } else if (nodeLocation instanceof IASTMacroExpansion) { IASTNodeLocation[] macroLocations= ((IASTMacroExpansion)nodeLocation).getExpansionLocations(); return getMaxFileLocation(macroLocations); } return null; } private static IASTFileLocation getMinFileLocation(IASTNodeLocation[] locations) { if (locations == null || locations.length == 0) { return null; } final IASTNodeLocation nodeLocation= locations[0]; if (nodeLocation instanceof IASTFileLocation) { return (IASTFileLocation)nodeLocation; } else if (nodeLocation instanceof IASTMacroExpansion) { IASTNodeLocation[] macroLocations= ((IASTMacroExpansion)nodeLocation).getExpansionLocations(); return getMinFileLocation(macroLocations); } return null; } /** * Handle the special "declaration" visibility label * @param visibilityLabel */ private void handleVisibilityLabel(ICPPASTVisiblityLabel visibilityLabel) { setCurrentVisibility(adaptVisibilityConstant(visibilityLabel.getVisibility())); } /** * Convert the given <code>ICPPASTVisiblityLabel</code> visibility constant * into an <code>ASTAccessVisibility</code>. * * @param visibility * @return the corresponding <code>ASTAccessVisibility</code> */ private ASTAccessVisibility adaptVisibilityConstant(int visibility) { switch(visibility) { case ICPPASTVisiblityLabel.v_public: return ASTAccessVisibility.PUBLIC; case ICPPASTVisiblityLabel.v_protected: return ASTAccessVisibility.PROTECTED; case ICPPASTVisiblityLabel.v_private: return ASTAccessVisibility.PRIVATE; } assert false : "Unknown visibility"; //$NON-NLS-1$ return ASTAccessVisibility.PUBLIC; } private void setCurrentVisibility(ASTAccessVisibility visibility) { fCurrentVisibility= visibility; } private ASTAccessVisibility getCurrentVisibility() { if (fCurrentVisibility == null) { return ASTAccessVisibility.PUBLIC; } return fCurrentVisibility; } /** * Pop the default visibility from the outer scope. */ private void popDefaultVisibility() { if (!fVisibilityStack.isEmpty()) { setCurrentVisibility((ASTAccessVisibility)fVisibilityStack.pop()); } } /** * Push given visibility as default class/struct/union visibility. * * @param visibility */ private void pushDefaultVisibility(ASTAccessVisibility visibility) { fVisibilityStack.push(getCurrentVisibility()); setCurrentVisibility(visibility); } /** * Determine the scope for given name. * * @param astName * @return the scope or <code>null</code> */ private static IScope getScope(IASTName astName) { IBinding binding= astName.getBinding(); if (binding != null) { try { return binding.getScope(); } catch (DOMException e) { return null; } } return null; } }
false
true
private FunctionDeclaration createFunctionDefinition(Parent parent, IASTFunctionDefinition functionDeclaration, boolean isTemplate) throws CModelException, DOMException { final IASTFunctionDeclarator declarator= functionDeclaration.getDeclarator(); IASTDeclarator nestedDeclarator= declarator; while (nestedDeclarator.getNestedDeclarator() != null) { nestedDeclarator= nestedDeclarator.getNestedDeclarator(); } final IASTName name= nestedDeclarator.getName(); if (name == null) { // Something is wrong, skip this element return null; } final IASTDeclSpecifier declSpecifier= functionDeclaration.getDeclSpecifier(); final String functionName= ASTStringUtil.getSimpleName(name); final String[] parameterTypes= ASTStringUtil.getParameterSignatureArray(declarator); final String returnType= ASTStringUtil.getTypeString(declSpecifier, declarator); final FunctionDeclaration element; if(declarator instanceof ICPPASTFunctionDeclarator) { final ICPPASTFunctionDeclarator cppFunctionDeclarator= (ICPPASTFunctionDeclarator)declarator; final IASTName simpleName; if (name instanceof ICPPASTQualifiedName) { final ICPPASTQualifiedName quName= (ICPPASTQualifiedName)name; simpleName= quName.getLastName(); } else { simpleName= name; } IScope scope= null; // try to avoid expensive resolution of scope and binding boolean isMethod= parent instanceof IStructure; if (!isMethod && name instanceof ICPPASTQualifiedName) { final IASTName[] names= ((ICPPASTQualifiedName)name).getNames(); if (isTemplate) { for (int i= 0; i < names.length; i++) { if (names[i] instanceof ICPPASTTemplateId) { isMethod= true; break; } } } if (!isMethod) { scope= CPPVisitor.getContainingScope(simpleName); isMethod= scope instanceof ICPPClassScope; } } if (isMethod) { // method final MethodDeclaration methodElement; if (isTemplate) { methodElement= new MethodTemplate(parent, ASTStringUtil.getQualifiedName(name)); } else { methodElement= new Method(parent, ASTStringUtil.getQualifiedName(name)); } element= methodElement; final ICPPMethod methodBinding; if (scope != null) { methodBinding= (ICPPMethod)simpleName.getBinding(); } else { methodBinding= null; } if (methodBinding != null) { methodElement.setVirtual(methodBinding.isVirtual()); methodElement.setInline(methodBinding.isInline()); methodElement.setFriend(((ICPPASTDeclSpecifier)declSpecifier).isFriend()); methodElement.setVolatile(cppFunctionDeclarator.isVolatile()); methodElement.setVisibility(adaptVisibilityConstant(methodBinding.getVisibility())); methodElement.setConst(cppFunctionDeclarator.isConst()); methodElement.setPureVirtual(false); methodElement.setConstructor(methodBinding instanceof ICPPConstructor); methodElement.setDestructor(methodBinding.isDestructor()); } else { if (declSpecifier instanceof ICPPASTDeclSpecifier) { final ICPPASTDeclSpecifier cppDeclSpecifier= (ICPPASTDeclSpecifier)declSpecifier; methodElement.setVirtual(cppDeclSpecifier.isVirtual()); methodElement.setInline(cppDeclSpecifier.isInline()); methodElement.setFriend(cppDeclSpecifier.isFriend()); } methodElement.setVolatile(cppFunctionDeclarator.isVolatile()); methodElement.setVisibility(getCurrentVisibility()); methodElement.setConst(cppFunctionDeclarator.isConst()); methodElement.setPureVirtual(false); final boolean isConstructor; if (scope != null) { isConstructor= CPPVisitor.isConstructor(scope, declarator); } else { isConstructor= parent.getElementName().equals(functionName); } methodElement.setConstructor(isConstructor); methodElement.setDestructor(functionName.charAt(0) == '~'); } } else { if (isTemplate) { // template function element= new FunctionTemplate(parent, ASTStringUtil.getQualifiedName(name)); } else { // function element= new Function(parent, ASTStringUtil.getQualifiedName(name)); } } } else { element= new Function(parent, functionName); } element.setParameterTypes(parameterTypes); element.setReturnType(returnType); // TODO [cmodel] correctly resolve isStatic element.setStatic(declSpecifier.getStorageClass() == IASTDeclSpecifier.sc_static); // add to parent parent.addChild(element); // set positions setIdentifierPosition(element, name); if (!isTemplate) { setBodyPosition(element, functionDeclaration); } return element; }
private FunctionDeclaration createFunctionDefinition(Parent parent, IASTFunctionDefinition functionDeclaration, boolean isTemplate) throws CModelException, DOMException { final IASTFunctionDeclarator declarator= functionDeclaration.getDeclarator(); IASTDeclarator nestedDeclarator= declarator; while (nestedDeclarator.getNestedDeclarator() != null) { nestedDeclarator= nestedDeclarator.getNestedDeclarator(); } final IASTName name= nestedDeclarator.getName(); if (name == null) { // Something is wrong, skip this element return null; } final IASTDeclSpecifier declSpecifier= functionDeclaration.getDeclSpecifier(); final String functionName= ASTStringUtil.getSimpleName(name); final String[] parameterTypes= ASTStringUtil.getParameterSignatureArray(declarator); final String returnType= ASTStringUtil.getTypeString(declSpecifier, declarator); final FunctionDeclaration element; if(declarator instanceof ICPPASTFunctionDeclarator) { final ICPPASTFunctionDeclarator cppFunctionDeclarator= (ICPPASTFunctionDeclarator)declarator; final IASTName simpleName; if (name instanceof ICPPASTQualifiedName) { final ICPPASTQualifiedName quName= (ICPPASTQualifiedName)name; simpleName= quName.getLastName(); } else { simpleName= name; } IScope scope= null; // try to avoid expensive resolution of scope and binding boolean isMethod= parent instanceof IStructure; if (!isMethod && name instanceof ICPPASTQualifiedName) { final IASTName[] names= ((ICPPASTQualifiedName)name).getNames(); if (isTemplate) { for (int i= 0; i < names.length; i++) { if (names[i] instanceof ICPPASTTemplateId) { isMethod= true; break; } } } if (!isMethod) { scope= CPPVisitor.getContainingScope(simpleName); isMethod= scope instanceof ICPPClassScope; } } if (isMethod) { // method final MethodDeclaration methodElement; if (isTemplate) { methodElement= new MethodTemplate(parent, ASTStringUtil.getQualifiedName(name)); } else { methodElement= new Method(parent, ASTStringUtil.getQualifiedName(name)); } element= methodElement; ICPPMethod methodBinding= null; if (scope != null) { final IBinding binding= simpleName.getBinding(); if (binding instanceof ICPPMethod) { methodBinding= (ICPPMethod)binding; } } if (methodBinding != null) { methodElement.setVirtual(methodBinding.isVirtual()); methodElement.setInline(methodBinding.isInline()); methodElement.setFriend(((ICPPASTDeclSpecifier)declSpecifier).isFriend()); methodElement.setVolatile(cppFunctionDeclarator.isVolatile()); methodElement.setVisibility(adaptVisibilityConstant(methodBinding.getVisibility())); methodElement.setConst(cppFunctionDeclarator.isConst()); methodElement.setPureVirtual(false); methodElement.setConstructor(methodBinding instanceof ICPPConstructor); methodElement.setDestructor(methodBinding.isDestructor()); } else { if (declSpecifier instanceof ICPPASTDeclSpecifier) { final ICPPASTDeclSpecifier cppDeclSpecifier= (ICPPASTDeclSpecifier)declSpecifier; methodElement.setVirtual(cppDeclSpecifier.isVirtual()); methodElement.setInline(cppDeclSpecifier.isInline()); methodElement.setFriend(cppDeclSpecifier.isFriend()); } methodElement.setVolatile(cppFunctionDeclarator.isVolatile()); methodElement.setVisibility(getCurrentVisibility()); methodElement.setConst(cppFunctionDeclarator.isConst()); methodElement.setPureVirtual(false); final boolean isConstructor; if (scope != null) { isConstructor= CPPVisitor.isConstructor(scope, declarator); } else { isConstructor= parent.getElementName().equals(functionName); } methodElement.setConstructor(isConstructor); methodElement.setDestructor(functionName.charAt(0) == '~'); } } else { if (isTemplate) { // template function element= new FunctionTemplate(parent, ASTStringUtil.getQualifiedName(name)); } else { // function element= new Function(parent, ASTStringUtil.getQualifiedName(name)); } } } else { element= new Function(parent, functionName); } element.setParameterTypes(parameterTypes); element.setReturnType(returnType); // TODO [cmodel] correctly resolve isStatic element.setStatic(declSpecifier.getStorageClass() == IASTDeclSpecifier.sc_static); // add to parent parent.addChild(element); // set positions setIdentifierPosition(element, name); if (!isTemplate) { setBodyPosition(element, functionDeclaration); } return element; }
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/src/main/java/com/authdb/scripts/forum/MyBB.java b/src/main/java/com/authdb/scripts/forum/MyBB.java index 2cc2026..3329d6c 100644 --- a/src/main/java/com/authdb/scripts/forum/MyBB.java +++ b/src/main/java/com/authdb/scripts/forum/MyBB.java @@ -1,104 +1,104 @@ /** (C) Copyright 2011 CraftFire <[email protected]> Contex <[email protected]>, Wulfspider <[email protected]> This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/ or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. **/ package com.authdb.scripts.forum; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.sql.PreparedStatement; import java.sql.SQLException; import com.authdb.util.Config; import com.authdb.util.encryption.Encryption; import com.authdb.util.Util; import com.authdb.util.databases.MySQL; import com.authdb.util.databases.EBean; public class MyBB { public static String VersionRange = "1.6.0-1.6.4"; public static String LatestVersionRange = VersionRange; public static String Name = "mybb"; public static String ShortName = "mybb"; public static void adduser(int checkid, String player, String email, String password, String ipAddress) throws SQLException { if (checkid == 1) { long timestamp = System.currentTimeMillis()/1000; String salt = Encryption.hash(8, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 0, 0); String hash = hash("create", player, password, salt); // PreparedStatement ps; // ps = MySQL.mysql.prepareStatement("INSERT INTO `" + Config.script_tableprefix + "users" + "` (`username`, `password`, `salt`, `email`, `regdate`, `lastactive`, `lastvisit`, `regip`, `longregip`, `signature`, `buddylist`, `ignorelist`, `pmfolders`, `notepad`, `usernotes`, `usergroup`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", 1); ps.setString(1, player.toLowerCase()); //username ps.setString(2, hash); // password ps.setString(3, salt); //salt ps.setString(4, email); //email ps.setLong(5, timestamp); //regdate ps.setLong(6, timestamp); //lastactive ps.setLong(7, timestamp); //lastvisit ps.setString(8, ipAddress); //regip ps.setLong(9, Util.ip2Long(ipAddress)); //need to add these, it's complaining about not default is set. ps.setString(10, ""); //signature ps.setString(11, ""); //buddylist ps.setString(12, ""); //ignorelist ps.setString(13, ""); //pmfolders ps.setString(14, ""); //notepad ps.setString(15, ""); //usernotes ps.setString(16, "5");//usergroup Util.logging.mySQL(ps.toString()); ps.executeUpdate(); ps.close(); int userid = MySQL.countitall(Config.script_tableprefix + "users"); - String oldcache = MySQL.getfromtable(Config.script_tableprefix + "datastore", "`data`", "title", "userstats"); + String oldcache = MySQL.getfromtable(Config.script_tableprefix + "datacache", "`cache`", "title", "stats"); String newcache = Util.forumCache(oldcache, player, userid, "numusers", null, "lastusername", "lastuid", null); ps = MySQL.mysql.prepareStatement("UPDATE `" + Config.script_tableprefix + "datacache" + "` SET `cache` = '" + newcache + "' WHERE `title` = 'stats'"); Util.logging.mySQL(ps.toString()); ps.executeUpdate(); ps.close(); } } public static String hash(String action, String player, String password, String thesalt) throws SQLException { if (action.equalsIgnoreCase("find")) { try { EBean eBeanClass = EBean.checkPlayer(player, true); String StoredSalt = eBeanClass.getSalt(); return passwordHash(password, StoredSalt); } catch (NoSuchAlgorithmException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } catch (UnsupportedEncodingException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } } else if (action.equalsIgnoreCase("create")) { try { return passwordHash(password, thesalt); } catch (NoSuchAlgorithmException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } catch (UnsupportedEncodingException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } } return "fail"; } public static boolean check_hash(String passwordhash, String hash) { if (passwordhash.equals(hash)) { return true; } else { return false; } } public static String passwordHash(String password, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException { return Encryption.md5(Encryption.md5(salt) + Encryption.md5(password)); } }
true
true
public static void adduser(int checkid, String player, String email, String password, String ipAddress) throws SQLException { if (checkid == 1) { long timestamp = System.currentTimeMillis()/1000; String salt = Encryption.hash(8, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 0, 0); String hash = hash("create", player, password, salt); // PreparedStatement ps; // ps = MySQL.mysql.prepareStatement("INSERT INTO `" + Config.script_tableprefix + "users" + "` (`username`, `password`, `salt`, `email`, `regdate`, `lastactive`, `lastvisit`, `regip`, `longregip`, `signature`, `buddylist`, `ignorelist`, `pmfolders`, `notepad`, `usernotes`, `usergroup`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", 1); ps.setString(1, player.toLowerCase()); //username ps.setString(2, hash); // password ps.setString(3, salt); //salt ps.setString(4, email); //email ps.setLong(5, timestamp); //regdate ps.setLong(6, timestamp); //lastactive ps.setLong(7, timestamp); //lastvisit ps.setString(8, ipAddress); //regip ps.setLong(9, Util.ip2Long(ipAddress)); //need to add these, it's complaining about not default is set. ps.setString(10, ""); //signature ps.setString(11, ""); //buddylist ps.setString(12, ""); //ignorelist ps.setString(13, ""); //pmfolders ps.setString(14, ""); //notepad ps.setString(15, ""); //usernotes ps.setString(16, "5");//usergroup Util.logging.mySQL(ps.toString()); ps.executeUpdate(); ps.close(); int userid = MySQL.countitall(Config.script_tableprefix + "users"); String oldcache = MySQL.getfromtable(Config.script_tableprefix + "datastore", "`data`", "title", "userstats"); String newcache = Util.forumCache(oldcache, player, userid, "numusers", null, "lastusername", "lastuid", null); ps = MySQL.mysql.prepareStatement("UPDATE `" + Config.script_tableprefix + "datacache" + "` SET `cache` = '" + newcache + "' WHERE `title` = 'stats'"); Util.logging.mySQL(ps.toString()); ps.executeUpdate(); ps.close(); } }
public static void adduser(int checkid, String player, String email, String password, String ipAddress) throws SQLException { if (checkid == 1) { long timestamp = System.currentTimeMillis()/1000; String salt = Encryption.hash(8, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 0, 0); String hash = hash("create", player, password, salt); // PreparedStatement ps; // ps = MySQL.mysql.prepareStatement("INSERT INTO `" + Config.script_tableprefix + "users" + "` (`username`, `password`, `salt`, `email`, `regdate`, `lastactive`, `lastvisit`, `regip`, `longregip`, `signature`, `buddylist`, `ignorelist`, `pmfolders`, `notepad`, `usernotes`, `usergroup`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", 1); ps.setString(1, player.toLowerCase()); //username ps.setString(2, hash); // password ps.setString(3, salt); //salt ps.setString(4, email); //email ps.setLong(5, timestamp); //regdate ps.setLong(6, timestamp); //lastactive ps.setLong(7, timestamp); //lastvisit ps.setString(8, ipAddress); //regip ps.setLong(9, Util.ip2Long(ipAddress)); //need to add these, it's complaining about not default is set. ps.setString(10, ""); //signature ps.setString(11, ""); //buddylist ps.setString(12, ""); //ignorelist ps.setString(13, ""); //pmfolders ps.setString(14, ""); //notepad ps.setString(15, ""); //usernotes ps.setString(16, "5");//usergroup Util.logging.mySQL(ps.toString()); ps.executeUpdate(); ps.close(); int userid = MySQL.countitall(Config.script_tableprefix + "users"); String oldcache = MySQL.getfromtable(Config.script_tableprefix + "datacache", "`cache`", "title", "stats"); String newcache = Util.forumCache(oldcache, player, userid, "numusers", null, "lastusername", "lastuid", null); ps = MySQL.mysql.prepareStatement("UPDATE `" + Config.script_tableprefix + "datacache" + "` SET `cache` = '" + newcache + "' WHERE `title` = 'stats'"); Util.logging.mySQL(ps.toString()); ps.executeUpdate(); ps.close(); } }
diff --git a/EcosurEJB/src/main/java/mx/ecosur/multigame/jms/AgentListener.java b/EcosurEJB/src/main/java/mx/ecosur/multigame/jms/AgentListener.java index 8a2cd51..40e2b5f 100644 --- a/EcosurEJB/src/main/java/mx/ecosur/multigame/jms/AgentListener.java +++ b/EcosurEJB/src/main/java/mx/ecosur/multigame/jms/AgentListener.java @@ -1,122 +1,128 @@ /* * Copyright (C) 2010 ECOSUR, Andrew Waterman and Max Pimm * * Licensed under the Academic Free License v. 3.0. * http://www.opensource.org/licenses/afl-3.0.php */ /** * @author [email protected] */ package mx.ecosur.multigame.jms; import java.util.List; import java.util.Set; import java.util.logging.Logger; import javax.annotation.Resource; import javax.annotation.security.RunAs; import javax.ejb.*; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.ObjectMessage; import mx.ecosur.multigame.ejb.interfaces.SharedBoardLocal; import mx.ecosur.multigame.enums.GameEvent; import mx.ecosur.multigame.enums.MoveStatus; import mx.ecosur.multigame.enums.SuggestionStatus; import mx.ecosur.multigame.exception.InvalidMoveException; import mx.ecosur.multigame.exception.InvalidSuggestionException; import mx.ecosur.multigame.model.interfaces.*; @RunAs("j2ee") @MessageDriven(mappedName = "MultiGame") @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public class AgentListener implements MessageListener { @EJB private SharedBoardLocal sharedBoard; private static Logger logger = Logger.getLogger(AgentListener.class.getCanonicalName()); private static GameEvent[] suggestionEvents = { GameEvent.SUGGESTION_APPLIED, GameEvent.SUGGESTION_EVALUATED}; private static final long serialVersionUID = -312450142866686545L; public void onMessage(Message message) { boolean matched = false; Move moved = null; try { String gameEvent = message.getStringProperty("GAME_EVENT"); GameEvent event = GameEvent.valueOf(gameEvent); ObjectMessage msg = (ObjectMessage) message; if (event.equals(GameEvent.PLAYER_CHANGE)) { matched = true; Game game = (Game) msg.getObject(); List<GamePlayer> players = game.listPlayers(); Agent agent = null; for (GamePlayer p : players) { if (p instanceof Agent) { Agent a = (Agent) p; if (a.ready()) { agent = a; break; } } } if (agent != null) { List<Move> moves = agent.determineMoves(game); if (moves.isEmpty()) throw new RuntimeException ("Agent unable to find move!"); - Move move = moves.get(0); - move.setPlayerModel(agent); - moved = sharedBoard.doMove(game, move); + for (Move move : moves) { + move.setPlayerModel(agent); + try { + moved = sharedBoard.doMove(game, move); + } catch (InvalidMoveException e) { + /* If an invalid move exception is thrown we try the next move in the stack */ + continue; + } + /* Break out of the loop and continue, move was okay */ + break; + } } } for (GameEvent possible : suggestionEvents) { if (event.equals(possible)) { matched = true; Suggestion suggestion = (Suggestion) msg.getObject(); SuggestionStatus oldStatus = suggestion.getStatus(); int gameId = new Integer (message.getStringProperty("GAME_ID")).intValue(); Game game = sharedBoard.getGame(gameId); List<GamePlayer> players = game.listPlayers(); for (GamePlayer p : players) { if (p instanceof Agent) { Agent agent = (Agent) p; suggestion = (agent.processSuggestion (game, suggestion)); SuggestionStatus newStatus = suggestion.getStatus(); if (oldStatus != newStatus && ( newStatus.equals(SuggestionStatus.ACCEPT) || newStatus.equals(SuggestionStatus.REJECT))) { sharedBoard.makeSuggestion (game, suggestion); } } } } } } catch (JMSException e) { logger.warning("Not able to process game message: " + e.getMessage()); e.printStackTrace(); throw new RuntimeException (e); } catch (RuntimeException e) { logger.warning ("RuntimeException generated! " + e.getMessage()); e.printStackTrace(); } catch (InvalidSuggestionException e) { logger.severe(e.getMessage()); e.printStackTrace(); - } catch (InvalidMoveException e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }
false
true
public void onMessage(Message message) { boolean matched = false; Move moved = null; try { String gameEvent = message.getStringProperty("GAME_EVENT"); GameEvent event = GameEvent.valueOf(gameEvent); ObjectMessage msg = (ObjectMessage) message; if (event.equals(GameEvent.PLAYER_CHANGE)) { matched = true; Game game = (Game) msg.getObject(); List<GamePlayer> players = game.listPlayers(); Agent agent = null; for (GamePlayer p : players) { if (p instanceof Agent) { Agent a = (Agent) p; if (a.ready()) { agent = a; break; } } } if (agent != null) { List<Move> moves = agent.determineMoves(game); if (moves.isEmpty()) throw new RuntimeException ("Agent unable to find move!"); Move move = moves.get(0); move.setPlayerModel(agent); moved = sharedBoard.doMove(game, move); } } for (GameEvent possible : suggestionEvents) { if (event.equals(possible)) { matched = true; Suggestion suggestion = (Suggestion) msg.getObject(); SuggestionStatus oldStatus = suggestion.getStatus(); int gameId = new Integer (message.getStringProperty("GAME_ID")).intValue(); Game game = sharedBoard.getGame(gameId); List<GamePlayer> players = game.listPlayers(); for (GamePlayer p : players) { if (p instanceof Agent) { Agent agent = (Agent) p; suggestion = (agent.processSuggestion (game, suggestion)); SuggestionStatus newStatus = suggestion.getStatus(); if (oldStatus != newStatus && ( newStatus.equals(SuggestionStatus.ACCEPT) || newStatus.equals(SuggestionStatus.REJECT))) { sharedBoard.makeSuggestion (game, suggestion); } } } } } } catch (JMSException e) { logger.warning("Not able to process game message: " + e.getMessage()); e.printStackTrace(); throw new RuntimeException (e); } catch (RuntimeException e) { logger.warning ("RuntimeException generated! " + e.getMessage()); e.printStackTrace(); } catch (InvalidSuggestionException e) { logger.severe(e.getMessage()); e.printStackTrace(); } catch (InvalidMoveException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } }
public void onMessage(Message message) { boolean matched = false; Move moved = null; try { String gameEvent = message.getStringProperty("GAME_EVENT"); GameEvent event = GameEvent.valueOf(gameEvent); ObjectMessage msg = (ObjectMessage) message; if (event.equals(GameEvent.PLAYER_CHANGE)) { matched = true; Game game = (Game) msg.getObject(); List<GamePlayer> players = game.listPlayers(); Agent agent = null; for (GamePlayer p : players) { if (p instanceof Agent) { Agent a = (Agent) p; if (a.ready()) { agent = a; break; } } } if (agent != null) { List<Move> moves = agent.determineMoves(game); if (moves.isEmpty()) throw new RuntimeException ("Agent unable to find move!"); for (Move move : moves) { move.setPlayerModel(agent); try { moved = sharedBoard.doMove(game, move); } catch (InvalidMoveException e) { /* If an invalid move exception is thrown we try the next move in the stack */ continue; } /* Break out of the loop and continue, move was okay */ break; } } } for (GameEvent possible : suggestionEvents) { if (event.equals(possible)) { matched = true; Suggestion suggestion = (Suggestion) msg.getObject(); SuggestionStatus oldStatus = suggestion.getStatus(); int gameId = new Integer (message.getStringProperty("GAME_ID")).intValue(); Game game = sharedBoard.getGame(gameId); List<GamePlayer> players = game.listPlayers(); for (GamePlayer p : players) { if (p instanceof Agent) { Agent agent = (Agent) p; suggestion = (agent.processSuggestion (game, suggestion)); SuggestionStatus newStatus = suggestion.getStatus(); if (oldStatus != newStatus && ( newStatus.equals(SuggestionStatus.ACCEPT) || newStatus.equals(SuggestionStatus.REJECT))) { sharedBoard.makeSuggestion (game, suggestion); } } } } } } catch (JMSException e) { logger.warning("Not able to process game message: " + e.getMessage()); e.printStackTrace(); throw new RuntimeException (e); } catch (RuntimeException e) { logger.warning ("RuntimeException generated! " + e.getMessage()); e.printStackTrace(); } catch (InvalidSuggestionException e) { logger.severe(e.getMessage()); e.printStackTrace(); } }
diff --git a/src/main/java/edu/umd/lib/wstrack/client/ClientTracking.java b/src/main/java/edu/umd/lib/wstrack/client/ClientTracking.java index 2d328f1..0ee8997 100644 --- a/src/main/java/edu/umd/lib/wstrack/client/ClientTracking.java +++ b/src/main/java/edu/umd/lib/wstrack/client/ClientTracking.java @@ -1,140 +1,140 @@ package edu.umd.lib.wstrack.client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.security.MessageDigest; import org.apache.log4j.Appender; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.varia.NullAppender; import sun.misc.BASE64Encoder; public class ClientTracking { public static final Logger log = Logger.getLogger(ClientTracking.class); /** * @param args */ public static String generateHash(String input) { String hash = ""; try { MessageDigest sha = MessageDigest.getInstance("MD5"); byte[] hashedBytes = sha.digest(input.getBytes()); hash = (new BASE64Encoder().encode(hashedBytes)); } catch (Exception e) { log.debug("The exception is " + e); } return hash; } /* * @Javadoc - Main method to retrieve the workstation tracking details. */ public static void main(String[] args) throws MalformedURLException, IOException { // configure logging boolean debug = System.getProperty("wstrack.debug", "false").equals("true"); if (debug) { // debug logging to the console Appender console = new ConsoleAppender(new PatternLayout( "%d [%-5p]: (%c)%n%m%n%n")); Logger.getRootLogger().addAppender(console); Logger.getRootLogger().setLevel(Level.DEBUG); } else { Logger.getRootLogger().addAppender(new NullAppender()); } try { // map environment to baseUrl String env = System.getProperty("wstrack.env", "local"); String baseUrl = null; if (env.equals("prod")) { baseUrl = "http://www.lib.umd.edu/wstrack/track"; } else if (env.equals("stage")) { baseUrl = "http://wwwstage.lib.umd.edu/wstrack/track"; } else if (env.equals("dev")) { baseUrl = "http://wwwdev.lib.umd.edu/wstrack/track"; } else { baseUrl = "http://localhost:8080/wstrack-server/track"; } log.debug("base url: " + baseUrl); // gather params String username = System.getProperty("wstrack.username"); if (username == null) { throw new Exception("wstrack.username property is required"); } log.debug("username: " + username); String hostname = System.getProperty("wstrack.hostname"); if (hostname == null) { throw new Exception("wstrack.hostname property is required"); } log.debug("hostname: " + hostname); String status = System.getProperty("wstrack.status"); if (status == null) { throw new Exception("wstrack.status property is required"); } - log.debug("status: " + username); + log.debug("status: " + status); String ip = System.getProperty("wstrack.ip"); if (ip == null) { throw new Exception("wstrack.ip property is required"); } - log.debug("username: " + ip); + log.debug("ip: " + ip); String os = System.getProperty("wstrack.os"); if (os == null) { throw new Exception("wstrack.os property is required"); } log.debug("os: " + os); boolean guestFlag = username.startsWith("libguest"); // build tracking url StringBuffer sb = new StringBuffer(baseUrl); sb.append("/" + URLEncoder.encode(ip, "UTF-8")); sb.append("/" + status); sb.append("/" + URLEncoder.encode(hostname, "UTF-8")); sb.append("/" + URLEncoder.encode(os, "UTF-8")); sb.append("/" + guestFlag); sb.append("/" + URLEncoder.encode(generateHash(username), "UTF-8")); // open the connection URL url = new URL(sb.toString()); URLConnection conn = url.openConnection(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { log.debug("response: " + line); } // wr.close(); rd.close(); } catch (Exception e) { log.error("Error in ClientTracking", e); } } }
false
true
public static void main(String[] args) throws MalformedURLException, IOException { // configure logging boolean debug = System.getProperty("wstrack.debug", "false").equals("true"); if (debug) { // debug logging to the console Appender console = new ConsoleAppender(new PatternLayout( "%d [%-5p]: (%c)%n%m%n%n")); Logger.getRootLogger().addAppender(console); Logger.getRootLogger().setLevel(Level.DEBUG); } else { Logger.getRootLogger().addAppender(new NullAppender()); } try { // map environment to baseUrl String env = System.getProperty("wstrack.env", "local"); String baseUrl = null; if (env.equals("prod")) { baseUrl = "http://www.lib.umd.edu/wstrack/track"; } else if (env.equals("stage")) { baseUrl = "http://wwwstage.lib.umd.edu/wstrack/track"; } else if (env.equals("dev")) { baseUrl = "http://wwwdev.lib.umd.edu/wstrack/track"; } else { baseUrl = "http://localhost:8080/wstrack-server/track"; } log.debug("base url: " + baseUrl); // gather params String username = System.getProperty("wstrack.username"); if (username == null) { throw new Exception("wstrack.username property is required"); } log.debug("username: " + username); String hostname = System.getProperty("wstrack.hostname"); if (hostname == null) { throw new Exception("wstrack.hostname property is required"); } log.debug("hostname: " + hostname); String status = System.getProperty("wstrack.status"); if (status == null) { throw new Exception("wstrack.status property is required"); } log.debug("status: " + username); String ip = System.getProperty("wstrack.ip"); if (ip == null) { throw new Exception("wstrack.ip property is required"); } log.debug("username: " + ip); String os = System.getProperty("wstrack.os"); if (os == null) { throw new Exception("wstrack.os property is required"); } log.debug("os: " + os); boolean guestFlag = username.startsWith("libguest"); // build tracking url StringBuffer sb = new StringBuffer(baseUrl); sb.append("/" + URLEncoder.encode(ip, "UTF-8")); sb.append("/" + status); sb.append("/" + URLEncoder.encode(hostname, "UTF-8")); sb.append("/" + URLEncoder.encode(os, "UTF-8")); sb.append("/" + guestFlag); sb.append("/" + URLEncoder.encode(generateHash(username), "UTF-8")); // open the connection URL url = new URL(sb.toString()); URLConnection conn = url.openConnection(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { log.debug("response: " + line); } // wr.close(); rd.close(); } catch (Exception e) { log.error("Error in ClientTracking", e); } }
public static void main(String[] args) throws MalformedURLException, IOException { // configure logging boolean debug = System.getProperty("wstrack.debug", "false").equals("true"); if (debug) { // debug logging to the console Appender console = new ConsoleAppender(new PatternLayout( "%d [%-5p]: (%c)%n%m%n%n")); Logger.getRootLogger().addAppender(console); Logger.getRootLogger().setLevel(Level.DEBUG); } else { Logger.getRootLogger().addAppender(new NullAppender()); } try { // map environment to baseUrl String env = System.getProperty("wstrack.env", "local"); String baseUrl = null; if (env.equals("prod")) { baseUrl = "http://www.lib.umd.edu/wstrack/track"; } else if (env.equals("stage")) { baseUrl = "http://wwwstage.lib.umd.edu/wstrack/track"; } else if (env.equals("dev")) { baseUrl = "http://wwwdev.lib.umd.edu/wstrack/track"; } else { baseUrl = "http://localhost:8080/wstrack-server/track"; } log.debug("base url: " + baseUrl); // gather params String username = System.getProperty("wstrack.username"); if (username == null) { throw new Exception("wstrack.username property is required"); } log.debug("username: " + username); String hostname = System.getProperty("wstrack.hostname"); if (hostname == null) { throw new Exception("wstrack.hostname property is required"); } log.debug("hostname: " + hostname); String status = System.getProperty("wstrack.status"); if (status == null) { throw new Exception("wstrack.status property is required"); } log.debug("status: " + status); String ip = System.getProperty("wstrack.ip"); if (ip == null) { throw new Exception("wstrack.ip property is required"); } log.debug("ip: " + ip); String os = System.getProperty("wstrack.os"); if (os == null) { throw new Exception("wstrack.os property is required"); } log.debug("os: " + os); boolean guestFlag = username.startsWith("libguest"); // build tracking url StringBuffer sb = new StringBuffer(baseUrl); sb.append("/" + URLEncoder.encode(ip, "UTF-8")); sb.append("/" + status); sb.append("/" + URLEncoder.encode(hostname, "UTF-8")); sb.append("/" + URLEncoder.encode(os, "UTF-8")); sb.append("/" + guestFlag); sb.append("/" + URLEncoder.encode(generateHash(username), "UTF-8")); // open the connection URL url = new URL(sb.toString()); URLConnection conn = url.openConnection(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { log.debug("response: " + line); } // wr.close(); rd.close(); } catch (Exception e) { log.error("Error in ClientTracking", e); } }
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java index d5651c9b..cdbda0fb 100644 --- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java +++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java @@ -1,235 +1,244 @@ /******************************************************************************* * Copyright (C) 2008, 2009 Robin Rosenberg <[email protected]> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.egit.ui.internal.decorators; import java.io.IOException; import java.util.Map; import java.util.WeakHashMap; import org.eclipse.core.resources.IResource; import org.eclipse.egit.core.GitProvider; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.internal.CompareUtils; import org.eclipse.egit.ui.internal.trace.GitTraceLocation; import org.eclipse.jface.text.Document; import org.eclipse.jgit.events.ListenerHandle; import org.eclipse.jgit.events.RefsChangedEvent; import org.eclipse.jgit.events.RefsChangedListener; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.osgi.util.NLS; import org.eclipse.team.core.RepositoryProvider; class GitDocument extends Document implements RefsChangedListener { private final IResource resource; private ObjectId lastCommit; private ObjectId lastTree; private ObjectId lastBlob; private ListenerHandle myRefsChangedHandle; static Map<GitDocument, Repository> doc2repo = new WeakHashMap<GitDocument, Repository>(); static GitDocument create(final IResource resource) throws IOException { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) create: " + resource); //$NON-NLS-1$ GitDocument ret = null; if (RepositoryProvider.getProvider(resource.getProject()) instanceof GitProvider) { ret = new GitDocument(resource); ret.populate(); final Repository repository = ret.getRepository(); if (repository != null) ret.myRefsChangedHandle = repository.getListenerList() .addRefsChangedListener(ret); } return ret; } private GitDocument(IResource resource) { this.resource = resource; GitDocument.doc2repo.put(this, getRepository()); } private void setResolved(final AnyObjectId commit, final AnyObjectId tree, final AnyObjectId blob, final String value) { lastCommit = commit != null ? commit.copy() : null; lastTree = tree != null ? tree.copy() : null; lastBlob = blob != null ? blob.copy() : null; set(value); if (blob != null) if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) resolved " + resource + " to " + lastBlob + " in " + lastCommit + "/" + lastTree); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ else if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) unresolved " + resource); //$NON-NLS-1$ } void populate() throws IOException { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.QUICKDIFF.getLocation(), resource); TreeWalk tw = null; RevWalk rw = null; try { RepositoryMapping mapping = RepositoryMapping.getMapping(resource); if (mapping == null) { setResolved(null, null, null, ""); //$NON-NLS-1$ return; } final String gitPath = mapping.getRepoRelativePath(resource); final Repository repository = mapping.getRepository(); String baseline = GitQuickDiffProvider.baseline.get(repository); if (baseline == null) baseline = Constants.HEAD; ObjectId commitId = repository.resolve(baseline); if (commitId != null) { if (commitId.equals(lastCommit)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } } else { String msg = NLS.bind(UIText.GitDocument_errorResolveQuickdiff, new Object[] { baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } rw = new RevWalk(repository); RevCommit baselineCommit; try { baselineCommit = rw.parseCommit(commitId); } catch (IOException err) { String msg = NLS .bind(UIText.GitDocument_errorLoadCommit, new Object[] { commitId, baseline, resource, repository }); Activator.logError(msg, err); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } RevTree treeId = baselineCommit.getTree(); if (treeId.equals(lastTree)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } tw = TreeWalk.forPath(repository, gitPath, treeId); + if (tw == null) { + setResolved(null, null, null, ""); //$NON-NLS-1$ + String msg = NLS + .bind(UIText.GitDocument_errorLoadTree, new Object[] { + treeId, baseline, resource, repository }); + Activator.logError(msg, new Throwable()); + setResolved(null, null, null, ""); //$NON-NLS-1$ + return; + } ObjectId id = tw.getObjectId(0); if (id.equals(ObjectId.zeroId())) { setResolved(null, null, null, ""); //$NON-NLS-1$ String msg = NLS .bind(UIText.GitDocument_errorLoadTree, new Object[] { treeId, baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } if (!id.equals(lastBlob)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) compareTo: " + baseline); //$NON-NLS-1$ ObjectLoader loader = repository.open(id, Constants.OBJ_BLOB); byte[] bytes = loader.getBytes(); String charset; charset = CompareUtils.getResourceEncoding(resource); // Finally we could consider validating the content with respect // to the content. We don't do that here. String s = new String(bytes, charset); setResolved(commitId, treeId, id, s); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) has reference doc, size=" + s.length() + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$ } else { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ } } finally { if (tw != null) tw.release(); if (rw != null) rw.release(); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceExit( GitTraceLocation.QUICKDIFF.getLocation()); } } void dispose() { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) dispose: " + resource); //$NON-NLS-1$ doc2repo.remove(this); if (myRefsChangedHandle != null) { myRefsChangedHandle.remove(); myRefsChangedHandle = null; } } public void onRefsChanged(final RefsChangedEvent e) { try { populate(); } catch (IOException e1) { Activator.logError(UIText.GitDocument_errorRefreshQuickdiff, e1); } } private Repository getRepository() { RepositoryMapping mapping = RepositoryMapping.getMapping(resource); return (mapping != null) ? mapping.getRepository() : null; } /** * A change occurred to a repository. Update any GitDocument instances * referring to such repositories. * * @param repository * Repository which changed * @throws IOException */ static void refreshRelevant(final Repository repository) throws IOException { for (Map.Entry<GitDocument, Repository> i : doc2repo.entrySet()) { if (i.getValue() == repository) { i.getKey().populate(); } } } }
true
true
void populate() throws IOException { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.QUICKDIFF.getLocation(), resource); TreeWalk tw = null; RevWalk rw = null; try { RepositoryMapping mapping = RepositoryMapping.getMapping(resource); if (mapping == null) { setResolved(null, null, null, ""); //$NON-NLS-1$ return; } final String gitPath = mapping.getRepoRelativePath(resource); final Repository repository = mapping.getRepository(); String baseline = GitQuickDiffProvider.baseline.get(repository); if (baseline == null) baseline = Constants.HEAD; ObjectId commitId = repository.resolve(baseline); if (commitId != null) { if (commitId.equals(lastCommit)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } } else { String msg = NLS.bind(UIText.GitDocument_errorResolveQuickdiff, new Object[] { baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } rw = new RevWalk(repository); RevCommit baselineCommit; try { baselineCommit = rw.parseCommit(commitId); } catch (IOException err) { String msg = NLS .bind(UIText.GitDocument_errorLoadCommit, new Object[] { commitId, baseline, resource, repository }); Activator.logError(msg, err); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } RevTree treeId = baselineCommit.getTree(); if (treeId.equals(lastTree)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } tw = TreeWalk.forPath(repository, gitPath, treeId); ObjectId id = tw.getObjectId(0); if (id.equals(ObjectId.zeroId())) { setResolved(null, null, null, ""); //$NON-NLS-1$ String msg = NLS .bind(UIText.GitDocument_errorLoadTree, new Object[] { treeId, baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } if (!id.equals(lastBlob)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) compareTo: " + baseline); //$NON-NLS-1$ ObjectLoader loader = repository.open(id, Constants.OBJ_BLOB); byte[] bytes = loader.getBytes(); String charset; charset = CompareUtils.getResourceEncoding(resource); // Finally we could consider validating the content with respect // to the content. We don't do that here. String s = new String(bytes, charset); setResolved(commitId, treeId, id, s); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) has reference doc, size=" + s.length() + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$ } else { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ } } finally { if (tw != null) tw.release(); if (rw != null) rw.release(); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceExit( GitTraceLocation.QUICKDIFF.getLocation()); } }
void populate() throws IOException { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.QUICKDIFF.getLocation(), resource); TreeWalk tw = null; RevWalk rw = null; try { RepositoryMapping mapping = RepositoryMapping.getMapping(resource); if (mapping == null) { setResolved(null, null, null, ""); //$NON-NLS-1$ return; } final String gitPath = mapping.getRepoRelativePath(resource); final Repository repository = mapping.getRepository(); String baseline = GitQuickDiffProvider.baseline.get(repository); if (baseline == null) baseline = Constants.HEAD; ObjectId commitId = repository.resolve(baseline); if (commitId != null) { if (commitId.equals(lastCommit)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } } else { String msg = NLS.bind(UIText.GitDocument_errorResolveQuickdiff, new Object[] { baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } rw = new RevWalk(repository); RevCommit baselineCommit; try { baselineCommit = rw.parseCommit(commitId); } catch (IOException err) { String msg = NLS .bind(UIText.GitDocument_errorLoadCommit, new Object[] { commitId, baseline, resource, repository }); Activator.logError(msg, err); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } RevTree treeId = baselineCommit.getTree(); if (treeId.equals(lastTree)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } tw = TreeWalk.forPath(repository, gitPath, treeId); if (tw == null) { setResolved(null, null, null, ""); //$NON-NLS-1$ String msg = NLS .bind(UIText.GitDocument_errorLoadTree, new Object[] { treeId, baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } ObjectId id = tw.getObjectId(0); if (id.equals(ObjectId.zeroId())) { setResolved(null, null, null, ""); //$NON-NLS-1$ String msg = NLS .bind(UIText.GitDocument_errorLoadTree, new Object[] { treeId, baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } if (!id.equals(lastBlob)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) compareTo: " + baseline); //$NON-NLS-1$ ObjectLoader loader = repository.open(id, Constants.OBJ_BLOB); byte[] bytes = loader.getBytes(); String charset; charset = CompareUtils.getResourceEncoding(resource); // Finally we could consider validating the content with respect // to the content. We don't do that here. String s = new String(bytes, charset); setResolved(commitId, treeId, id, s); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) has reference doc, size=" + s.length() + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$ } else { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ } } finally { if (tw != null) tw.release(); if (rw != null) rw.release(); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceExit( GitTraceLocation.QUICKDIFF.getLocation()); } }
diff --git a/src/test/java/javax/jmdns/test/DNSStatefulObjectTest.java b/src/test/java/javax/jmdns/test/DNSStatefulObjectTest.java index 599b00c..3cea27f 100644 --- a/src/test/java/javax/jmdns/test/DNSStatefulObjectTest.java +++ b/src/test/java/javax/jmdns/test/DNSStatefulObjectTest.java @@ -1,82 +1,82 @@ /** * */ package javax.jmdns.test; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import javax.jmdns.impl.DNSStatefulObject.DNSStatefulObjectSemaphore; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * */ public class DNSStatefulObjectTest { public static final class WaitingThread extends Thread { private final DNSStatefulObjectSemaphore _semaphore; private final long _timeout; private boolean _hasFinished; public WaitingThread(DNSStatefulObjectSemaphore semaphore, long timeout) { super("Waiting thread"); _semaphore = semaphore; _timeout = timeout; _hasFinished = false; } @Override public void run() { _semaphore.waitForEvent(_timeout); _hasFinished = true; } /** * @return the hasFinished */ public boolean hasFinished() { return _hasFinished; } } DNSStatefulObjectSemaphore _semaphore; @Before public void setup() { _semaphore = new DNSStatefulObjectSemaphore("test"); } @After public void teardown() { _semaphore = null; } @Test public void testWaitAndSignal() throws InterruptedException { - WaitingThread thread = new WaitingThread(_semaphore, 0); + WaitingThread thread = new WaitingThread(_semaphore, Long.MAX_VALUE); thread.start(); - Thread.sleep(2); + Thread.sleep(1); assertFalse("The thread should be waiting.", thread.hasFinished()); _semaphore.signalEvent(); - Thread.sleep(2); + Thread.sleep(1); assertTrue("The thread should have finished.", thread.hasFinished()); } @Test public void testWaitAndTimeout() throws InterruptedException { WaitingThread thread = new WaitingThread(_semaphore, 100); thread.start(); Thread.sleep(1); assertFalse("The thread should be waiting.", thread.hasFinished()); Thread.sleep(150); assertTrue("The thread should have finished.", thread.hasFinished()); } }
false
true
public void testWaitAndSignal() throws InterruptedException { WaitingThread thread = new WaitingThread(_semaphore, 0); thread.start(); Thread.sleep(2); assertFalse("The thread should be waiting.", thread.hasFinished()); _semaphore.signalEvent(); Thread.sleep(2); assertTrue("The thread should have finished.", thread.hasFinished()); }
public void testWaitAndSignal() throws InterruptedException { WaitingThread thread = new WaitingThread(_semaphore, Long.MAX_VALUE); thread.start(); Thread.sleep(1); assertFalse("The thread should be waiting.", thread.hasFinished()); _semaphore.signalEvent(); Thread.sleep(1); assertTrue("The thread should have finished.", thread.hasFinished()); }
diff --git a/src/nu/nerd/modmode/ModMode.java b/src/nu/nerd/modmode/ModMode.java index 1bf553c..5608627 100644 --- a/src/nu/nerd/modmode/ModMode.java +++ b/src/nu/nerd/modmode/ModMode.java @@ -1,412 +1,412 @@ package nu.nerd.modmode; import de.bananaco.bpermissions.api.ApiLayer; import de.bananaco.bpermissions.api.util.CalculableType; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import net.minecraft.server.v1_6_R2.EntityPlayer; import net.minecraft.server.v1_6_R2.MinecraftServer; import net.minecraft.server.v1_6_R2.MobEffect; import net.minecraft.server.v1_6_R2.Packet; import net.minecraft.server.v1_6_R2.Packet3Chat; import net.minecraft.server.v1_6_R2.Packet41MobEffect; import net.minecraft.server.v1_6_R2.WorldServer; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.craftbukkit.v1_6_R2.CraftServer; import org.bukkit.craftbukkit.v1_6_R2.entity.CraftPlayer; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; public class ModMode extends JavaPlugin { private final ModModeListener listener = new ModModeListener(this); public List<String> vanished; public List<String> fullvanished; public List<String> modmode; public boolean allowFlight; public boolean usingbperms; public String bPermsModGroup; public String bPermsModModeGroup; public HashMap<String, Collection<PotionEffect>> potionMap; public boolean isInvisible(Player player) { return vanished.contains(player.getName()) || fullvanished.contains(player.getName()); } public boolean isModMode(Player player) { return modmode.contains(player.getDisplayName()); } public void enableVanish(Player player) { for (Player other : getServer().getOnlinePlayers()) { if (Permissions.hasPermission(other, Permissions.SHOWVANISHED)) { continue; } if (Permissions.hasPermission(other, Permissions.SHOWMODS)) { continue; } other.hidePlayer(player); } player.sendMessage(ChatColor.RED + "Poof!"); } public void enableFullVanish(Player player) { for (Player other : getServer().getOnlinePlayers()) { if (Permissions.hasPermission(other, Permissions.SHOWVANISHED)) { continue; } other.hidePlayer(player); } player.sendMessage(ChatColor.RED + "You are fully vanished!"); } public void disableVanish(Player player) { if (vanished.remove(player.getName()) || fullvanished.remove(player.getName())) { for (Player other : getServer().getOnlinePlayers()) { other.showPlayer(player); } player.sendMessage(ChatColor.RED + "You have reappeared!"); } else { player.sendMessage(ChatColor.RED + "You are not vanished!"); } } public void showVanishList(Player player) { String result = ""; boolean first = true; for (String hidden : vanished) { if (getServer().getPlayerExact(hidden) == null) { continue; } if (first) { result += hidden + ChatColor.RED; first = false; continue; } result += ", " + hidden + ChatColor.RED; } for (String hidden : fullvanished) { if (getServer().getPlayerExact(hidden) == null) { continue; } if (first) { result += hidden + ChatColor.RED; first = false; continue; } result += ", " + hidden + ChatColor.RED; } if (result.length() == 0) { player.sendMessage(ChatColor.RED + "All players are visible!"); } else { player.sendMessage(ChatColor.RED + "Vanished players: " + result); } } public void toggleModMode(final Player player, boolean toggle, boolean onJoin) { String displayName = player.getName(); String name = ChatColor.GREEN + player.getDisplayName() + ChatColor.WHITE; if (!toggle) { displayName = player.getDisplayName(); name = displayName; if (usingbperms) { List<org.bukkit.World> worlds = getServer().getWorlds(); for (org.bukkit.World world : worlds) { ApiLayer.removeGroup(world.getName(), CalculableType.USER, name, bPermsModModeGroup); List<String> groups = Arrays.asList(ApiLayer.getGroups(world.getName(), CalculableType.USER, name)); if (!groups.contains(bPermsModGroup)) { ApiLayer.addGroup(world.getName(), CalculableType.USER, name, bPermsModGroup); } } } player.sendMessage(ChatColor.RED + "You are no longer in ModMode!"); } else { if (usingbperms) { List<org.bukkit.World> worlds = getServer().getWorlds(); for (org.bukkit.World world : worlds) { ApiLayer.addGroup(world.getName(), CalculableType.USER, name, bPermsModModeGroup); List<String> groups = Arrays.asList(ApiLayer.getGroups(world.getName(), CalculableType.USER, name)); if (groups.contains(bPermsModGroup)) { ApiLayer.removeGroup(world.getName(), CalculableType.USER, name, bPermsModGroup); } } } player.sendMessage(ChatColor.RED + "You are now in ModMode!"); } Location loc = player.getLocation(); final EntityPlayer entityplayer = ((CraftPlayer) player).getHandle(); final MinecraftServer server = entityplayer.server; //send fake quit message if (!onJoin) { - PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(player, "\u00A7e" + entityplayer.name + " left the game."); + PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(player, "\u00A7e" + entityplayer.listName + " left the game."); getServer().getPluginManager().callEvent(playerQuitEvent); if ((playerQuitEvent.getQuitMessage() != null) && (playerQuitEvent.getQuitMessage().length() > 0)) { sendPacketToAll(new Packet3Chat(playerQuitEvent.getQuitMessage())); } } // Save current potion effects Collection<PotionEffect> activeEffects = player.getActivePotionEffects(); - potionMap.put(entityplayer.name, activeEffects); + potionMap.put(entityplayer.listName, activeEffects); //save with the old name, change it, then load with the new name server.getPlayerList().playerFileData.save(entityplayer); - entityplayer.name = name; + entityplayer.listName = name; entityplayer.displayName = displayName; server.getPlayerList().playerFileData.load(entityplayer); //send fake join message - PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(player, "\u00A7e" + entityplayer.name + " joined the game."); + PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(player, "\u00A7e" + entityplayer.listName + " joined the game."); getServer().getPluginManager().callEvent(playerJoinEvent); if ((playerJoinEvent.getJoinMessage() != null) && (playerJoinEvent.getJoinMessage().length() > 0)) { sendPacketToAll(new Packet3Chat(playerJoinEvent.getJoinMessage())); } //untrack and track to show new name to clients ((WorldServer) entityplayer.world).tracker.untrackEntity(entityplayer); ((WorldServer) entityplayer.world).tracker.track(entityplayer); //teleport to avoid speedhack if (!toggle || onJoin) { loc = new Location(entityplayer.world.getWorld(), entityplayer.locX, entityplayer.locY, entityplayer.locZ, entityplayer.yaw, entityplayer.pitch); } player.teleport(loc); // Hopefully stop some minor falls player.setFallDistance(0F); // Chunk error ( resend to all clients ) World w = player.getWorld(); Chunk c = w.getChunkAt(player.getLocation()); w.refreshChunk(c.getX(), c.getZ()); //unvanish the player when they leave modmode if (!toggle) { for (Player other : getServer().getOnlinePlayers()) { other.showPlayer(player); } } // Load new potion effects for (PotionEffect effect : activeEffects){ player.removePotionEffect(effect.getType()); } - Collection<PotionEffect> newEffects = potionMap.get(entityplayer.name); + Collection<PotionEffect> newEffects = potionMap.get(entityplayer.listName); if (newEffects != null) { for (PotionEffect effect : newEffects){ player.addPotionEffect(effect); // addPotionEffect doesn't send this packet for some reason, so we'll do it manually entityplayer.playerConnection.sendPacket(new Packet41MobEffect(entityplayer.id, new MobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier()))); } } - potionMap.remove(entityplayer.name); + potionMap.remove(entityplayer.listName); // final Location loc2 = loc.clone(); // // getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { // public void run() { // Packet20NamedEntitySpawn packet = new Packet20NamedEntitySpawn(entityplayer); // server.getServerConfigurationManager().sendPacketNearby(loc2.getX(), loc2.getY(), loc2.getZ(), 128, ((CraftWorld) loc2.getWorld()).getHandle().dimension, packet); // Packet29DestroyEntity destroy = new Packet29DestroyEntity(entityplayer.id); // server.getServerConfigurationManager().sendPacketNearby(loc2.getX(), loc2.getY(), loc2.getZ(), 1, ((CraftWorld) loc2.getWorld()).getHandle().dimension, destroy); // } // }, 10); //toggle flight, set via the config path "allow.flight" if (allowFlight) { player.setAllowFlight(toggle); } /* * EntityPlayer oldplayer = ((CraftPlayer) player).getHandle(); * MinecraftServer server = oldplayer.server; NetServerHandler * netServerHandler = oldplayer.netServerHandler; * * // remove old entity String quitMessage = * server.serverConfigurationManager.disconnect(oldplayer); if * ((quitMessage != null) && (quitMessage.length() > 0)) { * server.serverConfigurationManager.sendAll(new * Packet3Chat(quitMessage)); } * * // ((WorldServer) oldplayer.world).tracker.untrackPlayer(oldplayer); * // oldplayer.die(); * * // make new one with same NetServerHandler and ItemInWorldManager * EntityPlayer entityplayer = new EntityPlayer(server, * server.getWorldServer(0), name, oldplayer.itemInWorldManager); Player * newplayer = entityplayer.getBukkitEntity(); * * entityplayer.displayName = displayName; entityplayer.listName = * displayName; entityplayer.netServerHandler = netServerHandler; * entityplayer.netServerHandler.player = entityplayer; entityplayer.id * = oldplayer.id; * server.serverConfigurationManager.playerFileData.load(entityplayer); * if (toggle) { entityplayer.locX = oldplayer.locX; entityplayer.locY = * oldplayer.locY; entityplayer.locZ = oldplayer.locZ; entityplayer.yaw * = oldplayer.yaw; entityplayer.pitch = oldplayer.pitch; } * server.serverConfigurationManager.c(entityplayer); * entityplayer.syncInventory(); * * // untrack and track to make sure we can see everyone ((WorldServer) * entityplayer.world).tracker.untrackEntity(entityplayer); * ((WorldServer) entityplayer.world).tracker.track(entityplayer); * * // teleport to the player's location to avoid speedhack kick if * (!toggle) { Location loc = new * Location(entityplayer.world.getWorld(), entityplayer.locX, * entityplayer.locY, entityplayer.locZ, entityplayer.yaw, * entityplayer.pitch); newplayer.teleport(loc); } */ } private static void sendPacketToAll(Packet p){ MinecraftServer server = ((CraftServer)Bukkit.getServer()).getServer(); for (int i = 0; i < server.getPlayerList().players.size(); ++i) { EntityPlayer ep = (EntityPlayer) server.getPlayerList().players.get(i); ep.playerConnection.sendPacket(p); } } public void updateVanishLists(Player player) { //first show everyone, then decide who to hide for (Player other : getServer().getOnlinePlayers()) { player.showPlayer(other); } if (Permissions.hasPermission(player, Permissions.SHOWVANISHED)) { return; } for (String hidden : fullvanished) { Player hiddenPlayer = getServer().getPlayerExact(hidden); if (hiddenPlayer != null) { player.hidePlayer(hiddenPlayer); } } if (Permissions.hasPermission(player, Permissions.SHOWMODS)) { return; } for (String hidden : vanished) { Player hiddenPlayer = getServer().getPlayerExact(hidden); if (hiddenPlayer != null) { player.hidePlayer(hiddenPlayer); } } } @Override public void onEnable() { getServer().getPluginManager().registerEvents(listener, this); vanished = getConfig().getStringList("vanished"); fullvanished = getConfig().getStringList("fullvanished"); modmode = getConfig().getStringList("modmode"); allowFlight = getConfig().getBoolean("allow.flight", true); usingbperms = getConfig().getBoolean("bperms.enabled", false); bPermsModGroup = getConfig().getString("bperms.modgroup", "Moderators"); bPermsModModeGroup = getConfig().getString("bperms.modmodegroup", "ModMode"); potionMap = new HashMap<String, Collection<PotionEffect>>(); if (usingbperms) { de.bananaco.bpermissions.imp.Permissions bPermsPlugin = null; bPermsPlugin = (de.bananaco.bpermissions.imp.Permissions)getServer().getPluginManager().getPlugin("bPermissions"); if (bPermsPlugin == null || !(bPermsPlugin instanceof de.bananaco.bpermissions.imp.Permissions)) { if (!bPermsPlugin.isEnabled()) { getPluginLoader().enablePlugin(bPermsPlugin); } getLogger().log(Level.INFO, "bperms turned on, but plugin could not be loaded."); getPluginLoader().disablePlugin(this); } } } @Override public void onDisable() { getConfig().set("vanished", vanished); getConfig().set("fullvanished", fullvanished); getConfig().set("modmode", modmode); getConfig().set("allow.flight", allowFlight); getConfig().set("bperms.enabled", usingbperms); getConfig().set("bperms.modgroup", bPermsModGroup); getConfig().set("bperms.modmodegroup", bPermsModModeGroup); saveConfig(); } @Override public boolean onCommand(CommandSender sender, Command command, String name, String[] args) { if (!(sender instanceof Player)) { return false; } Player player = (Player) sender; if (command.getName().equalsIgnoreCase("vanish")) { if (args.length == 1 && args[0].equalsIgnoreCase("list")) { showVanishList(player); } else { if (vanished.contains(player.getName())) { player.sendMessage(ChatColor.RED + "You are already vanished!"); } else { // special case, we need to appear to mods but not everyone if (fullvanished.remove(player.getName())) { for (Player other : getServer().getOnlinePlayers()) { if (Permissions.hasPermission(other, Permissions.SHOWMODS)) { other.showPlayer(player); } } } vanished.add(player.getName()); enableVanish(player); } } } else if (command.getName().equalsIgnoreCase("fullvanish")) { if (fullvanished.contains(player.getName())) { player.sendMessage(ChatColor.RED + "You are already vanished!"); } else { fullvanished.add(player.getName()); vanished.remove(player.getName()); enableFullVanish(player); } } else if (command.getName().equalsIgnoreCase("unvanish")) { disableVanish(player); } else if (command.getName().equalsIgnoreCase("modmode")) { if (modmode.remove(player.getDisplayName())) { toggleModMode(player, false, false); } else { modmode.add(player.getDisplayName()); toggleModMode(player, true, false); } } return true; } }
false
true
public void toggleModMode(final Player player, boolean toggle, boolean onJoin) { String displayName = player.getName(); String name = ChatColor.GREEN + player.getDisplayName() + ChatColor.WHITE; if (!toggle) { displayName = player.getDisplayName(); name = displayName; if (usingbperms) { List<org.bukkit.World> worlds = getServer().getWorlds(); for (org.bukkit.World world : worlds) { ApiLayer.removeGroup(world.getName(), CalculableType.USER, name, bPermsModModeGroup); List<String> groups = Arrays.asList(ApiLayer.getGroups(world.getName(), CalculableType.USER, name)); if (!groups.contains(bPermsModGroup)) { ApiLayer.addGroup(world.getName(), CalculableType.USER, name, bPermsModGroup); } } } player.sendMessage(ChatColor.RED + "You are no longer in ModMode!"); } else { if (usingbperms) { List<org.bukkit.World> worlds = getServer().getWorlds(); for (org.bukkit.World world : worlds) { ApiLayer.addGroup(world.getName(), CalculableType.USER, name, bPermsModModeGroup); List<String> groups = Arrays.asList(ApiLayer.getGroups(world.getName(), CalculableType.USER, name)); if (groups.contains(bPermsModGroup)) { ApiLayer.removeGroup(world.getName(), CalculableType.USER, name, bPermsModGroup); } } } player.sendMessage(ChatColor.RED + "You are now in ModMode!"); } Location loc = player.getLocation(); final EntityPlayer entityplayer = ((CraftPlayer) player).getHandle(); final MinecraftServer server = entityplayer.server; //send fake quit message if (!onJoin) { PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(player, "\u00A7e" + entityplayer.name + " left the game."); getServer().getPluginManager().callEvent(playerQuitEvent); if ((playerQuitEvent.getQuitMessage() != null) && (playerQuitEvent.getQuitMessage().length() > 0)) { sendPacketToAll(new Packet3Chat(playerQuitEvent.getQuitMessage())); } } // Save current potion effects Collection<PotionEffect> activeEffects = player.getActivePotionEffects(); potionMap.put(entityplayer.name, activeEffects); //save with the old name, change it, then load with the new name server.getPlayerList().playerFileData.save(entityplayer); entityplayer.name = name; entityplayer.displayName = displayName; server.getPlayerList().playerFileData.load(entityplayer); //send fake join message PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(player, "\u00A7e" + entityplayer.name + " joined the game."); getServer().getPluginManager().callEvent(playerJoinEvent); if ((playerJoinEvent.getJoinMessage() != null) && (playerJoinEvent.getJoinMessage().length() > 0)) { sendPacketToAll(new Packet3Chat(playerJoinEvent.getJoinMessage())); } //untrack and track to show new name to clients ((WorldServer) entityplayer.world).tracker.untrackEntity(entityplayer); ((WorldServer) entityplayer.world).tracker.track(entityplayer); //teleport to avoid speedhack if (!toggle || onJoin) { loc = new Location(entityplayer.world.getWorld(), entityplayer.locX, entityplayer.locY, entityplayer.locZ, entityplayer.yaw, entityplayer.pitch); } player.teleport(loc); // Hopefully stop some minor falls player.setFallDistance(0F); // Chunk error ( resend to all clients ) World w = player.getWorld(); Chunk c = w.getChunkAt(player.getLocation()); w.refreshChunk(c.getX(), c.getZ()); //unvanish the player when they leave modmode if (!toggle) { for (Player other : getServer().getOnlinePlayers()) { other.showPlayer(player); } } // Load new potion effects for (PotionEffect effect : activeEffects){ player.removePotionEffect(effect.getType()); } Collection<PotionEffect> newEffects = potionMap.get(entityplayer.name); if (newEffects != null) { for (PotionEffect effect : newEffects){ player.addPotionEffect(effect); // addPotionEffect doesn't send this packet for some reason, so we'll do it manually entityplayer.playerConnection.sendPacket(new Packet41MobEffect(entityplayer.id, new MobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier()))); } } potionMap.remove(entityplayer.name); // final Location loc2 = loc.clone(); // // getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { // public void run() { // Packet20NamedEntitySpawn packet = new Packet20NamedEntitySpawn(entityplayer); // server.getServerConfigurationManager().sendPacketNearby(loc2.getX(), loc2.getY(), loc2.getZ(), 128, ((CraftWorld) loc2.getWorld()).getHandle().dimension, packet); // Packet29DestroyEntity destroy = new Packet29DestroyEntity(entityplayer.id); // server.getServerConfigurationManager().sendPacketNearby(loc2.getX(), loc2.getY(), loc2.getZ(), 1, ((CraftWorld) loc2.getWorld()).getHandle().dimension, destroy); // } // }, 10); //toggle flight, set via the config path "allow.flight" if (allowFlight) { player.setAllowFlight(toggle); } /* * EntityPlayer oldplayer = ((CraftPlayer) player).getHandle(); * MinecraftServer server = oldplayer.server; NetServerHandler * netServerHandler = oldplayer.netServerHandler; * * // remove old entity String quitMessage = * server.serverConfigurationManager.disconnect(oldplayer); if * ((quitMessage != null) && (quitMessage.length() > 0)) { * server.serverConfigurationManager.sendAll(new * Packet3Chat(quitMessage)); } * * // ((WorldServer) oldplayer.world).tracker.untrackPlayer(oldplayer); * // oldplayer.die(); * * // make new one with same NetServerHandler and ItemInWorldManager * EntityPlayer entityplayer = new EntityPlayer(server, * server.getWorldServer(0), name, oldplayer.itemInWorldManager); Player * newplayer = entityplayer.getBukkitEntity(); * * entityplayer.displayName = displayName; entityplayer.listName = * displayName; entityplayer.netServerHandler = netServerHandler; * entityplayer.netServerHandler.player = entityplayer; entityplayer.id * = oldplayer.id; * server.serverConfigurationManager.playerFileData.load(entityplayer); * if (toggle) { entityplayer.locX = oldplayer.locX; entityplayer.locY = * oldplayer.locY; entityplayer.locZ = oldplayer.locZ; entityplayer.yaw * = oldplayer.yaw; entityplayer.pitch = oldplayer.pitch; } * server.serverConfigurationManager.c(entityplayer); * entityplayer.syncInventory(); * * // untrack and track to make sure we can see everyone ((WorldServer) * entityplayer.world).tracker.untrackEntity(entityplayer); * ((WorldServer) entityplayer.world).tracker.track(entityplayer); * * // teleport to the player's location to avoid speedhack kick if * (!toggle) { Location loc = new * Location(entityplayer.world.getWorld(), entityplayer.locX, * entityplayer.locY, entityplayer.locZ, entityplayer.yaw, * entityplayer.pitch); newplayer.teleport(loc); }
public void toggleModMode(final Player player, boolean toggle, boolean onJoin) { String displayName = player.getName(); String name = ChatColor.GREEN + player.getDisplayName() + ChatColor.WHITE; if (!toggle) { displayName = player.getDisplayName(); name = displayName; if (usingbperms) { List<org.bukkit.World> worlds = getServer().getWorlds(); for (org.bukkit.World world : worlds) { ApiLayer.removeGroup(world.getName(), CalculableType.USER, name, bPermsModModeGroup); List<String> groups = Arrays.asList(ApiLayer.getGroups(world.getName(), CalculableType.USER, name)); if (!groups.contains(bPermsModGroup)) { ApiLayer.addGroup(world.getName(), CalculableType.USER, name, bPermsModGroup); } } } player.sendMessage(ChatColor.RED + "You are no longer in ModMode!"); } else { if (usingbperms) { List<org.bukkit.World> worlds = getServer().getWorlds(); for (org.bukkit.World world : worlds) { ApiLayer.addGroup(world.getName(), CalculableType.USER, name, bPermsModModeGroup); List<String> groups = Arrays.asList(ApiLayer.getGroups(world.getName(), CalculableType.USER, name)); if (groups.contains(bPermsModGroup)) { ApiLayer.removeGroup(world.getName(), CalculableType.USER, name, bPermsModGroup); } } } player.sendMessage(ChatColor.RED + "You are now in ModMode!"); } Location loc = player.getLocation(); final EntityPlayer entityplayer = ((CraftPlayer) player).getHandle(); final MinecraftServer server = entityplayer.server; //send fake quit message if (!onJoin) { PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(player, "\u00A7e" + entityplayer.listName + " left the game."); getServer().getPluginManager().callEvent(playerQuitEvent); if ((playerQuitEvent.getQuitMessage() != null) && (playerQuitEvent.getQuitMessage().length() > 0)) { sendPacketToAll(new Packet3Chat(playerQuitEvent.getQuitMessage())); } } // Save current potion effects Collection<PotionEffect> activeEffects = player.getActivePotionEffects(); potionMap.put(entityplayer.listName, activeEffects); //save with the old name, change it, then load with the new name server.getPlayerList().playerFileData.save(entityplayer); entityplayer.listName = name; entityplayer.displayName = displayName; server.getPlayerList().playerFileData.load(entityplayer); //send fake join message PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(player, "\u00A7e" + entityplayer.listName + " joined the game."); getServer().getPluginManager().callEvent(playerJoinEvent); if ((playerJoinEvent.getJoinMessage() != null) && (playerJoinEvent.getJoinMessage().length() > 0)) { sendPacketToAll(new Packet3Chat(playerJoinEvent.getJoinMessage())); } //untrack and track to show new name to clients ((WorldServer) entityplayer.world).tracker.untrackEntity(entityplayer); ((WorldServer) entityplayer.world).tracker.track(entityplayer); //teleport to avoid speedhack if (!toggle || onJoin) { loc = new Location(entityplayer.world.getWorld(), entityplayer.locX, entityplayer.locY, entityplayer.locZ, entityplayer.yaw, entityplayer.pitch); } player.teleport(loc); // Hopefully stop some minor falls player.setFallDistance(0F); // Chunk error ( resend to all clients ) World w = player.getWorld(); Chunk c = w.getChunkAt(player.getLocation()); w.refreshChunk(c.getX(), c.getZ()); //unvanish the player when they leave modmode if (!toggle) { for (Player other : getServer().getOnlinePlayers()) { other.showPlayer(player); } } // Load new potion effects for (PotionEffect effect : activeEffects){ player.removePotionEffect(effect.getType()); } Collection<PotionEffect> newEffects = potionMap.get(entityplayer.listName); if (newEffects != null) { for (PotionEffect effect : newEffects){ player.addPotionEffect(effect); // addPotionEffect doesn't send this packet for some reason, so we'll do it manually entityplayer.playerConnection.sendPacket(new Packet41MobEffect(entityplayer.id, new MobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier()))); } } potionMap.remove(entityplayer.listName); // final Location loc2 = loc.clone(); // // getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { // public void run() { // Packet20NamedEntitySpawn packet = new Packet20NamedEntitySpawn(entityplayer); // server.getServerConfigurationManager().sendPacketNearby(loc2.getX(), loc2.getY(), loc2.getZ(), 128, ((CraftWorld) loc2.getWorld()).getHandle().dimension, packet); // Packet29DestroyEntity destroy = new Packet29DestroyEntity(entityplayer.id); // server.getServerConfigurationManager().sendPacketNearby(loc2.getX(), loc2.getY(), loc2.getZ(), 1, ((CraftWorld) loc2.getWorld()).getHandle().dimension, destroy); // } // }, 10); //toggle flight, set via the config path "allow.flight" if (allowFlight) { player.setAllowFlight(toggle); } /* * EntityPlayer oldplayer = ((CraftPlayer) player).getHandle(); * MinecraftServer server = oldplayer.server; NetServerHandler * netServerHandler = oldplayer.netServerHandler; * * // remove old entity String quitMessage = * server.serverConfigurationManager.disconnect(oldplayer); if * ((quitMessage != null) && (quitMessage.length() > 0)) { * server.serverConfigurationManager.sendAll(new * Packet3Chat(quitMessage)); } * * // ((WorldServer) oldplayer.world).tracker.untrackPlayer(oldplayer); * // oldplayer.die(); * * // make new one with same NetServerHandler and ItemInWorldManager * EntityPlayer entityplayer = new EntityPlayer(server, * server.getWorldServer(0), name, oldplayer.itemInWorldManager); Player * newplayer = entityplayer.getBukkitEntity(); * * entityplayer.displayName = displayName; entityplayer.listName = * displayName; entityplayer.netServerHandler = netServerHandler; * entityplayer.netServerHandler.player = entityplayer; entityplayer.id * = oldplayer.id; * server.serverConfigurationManager.playerFileData.load(entityplayer); * if (toggle) { entityplayer.locX = oldplayer.locX; entityplayer.locY = * oldplayer.locY; entityplayer.locZ = oldplayer.locZ; entityplayer.yaw * = oldplayer.yaw; entityplayer.pitch = oldplayer.pitch; } * server.serverConfigurationManager.c(entityplayer); * entityplayer.syncInventory(); * * // untrack and track to make sure we can see everyone ((WorldServer) * entityplayer.world).tracker.untrackEntity(entityplayer); * ((WorldServer) entityplayer.world).tracker.track(entityplayer); * * // teleport to the player's location to avoid speedhack kick if * (!toggle) { Location loc = new * Location(entityplayer.world.getWorld(), entityplayer.locX, * entityplayer.locY, entityplayer.locZ, entityplayer.yaw, * entityplayer.pitch); newplayer.teleport(loc); }
diff --git a/example/com/anteambulo/SeleniumJQuery/example/Example.java b/example/com/anteambulo/SeleniumJQuery/example/Example.java index 3bf68ee..eedb107 100644 --- a/example/com/anteambulo/SeleniumJQuery/example/Example.java +++ b/example/com/anteambulo/SeleniumJQuery/example/Example.java @@ -1,30 +1,30 @@ package com.anteambulo.SeleniumJQuery.example; import java.util.concurrent.TimeoutException; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import com.anteambulo.SeleniumJQuery.jQueryFactory; import com.gargoylesoftware.htmlunit.BrowserVersion; public class Example extends jQueryFactory { public static void main(String[] args) throws TimeoutException { // HtmlUnitDriver is loud... System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.log.com.gargoylesoftware.htmlunit", "fatal"); HtmlUnitDriver drv = new HtmlUnitDriver(BrowserVersion.FIREFOX_3_6); drv.setJavascriptEnabled(true); try { Example jq = new Example(); jq.setJs(drv); drv.get("http://google.com"); jq.query("[name=q]").val("SeleniumJQuery").parents("form:first").submit(); String results = jq.queryUntil("#resultStats:contains(results)").text(); System.out.println(results.split(" ")[1] + " results found!"); } finally { - drv.close(); + drv.quit(); } } }
true
true
public static void main(String[] args) throws TimeoutException { // HtmlUnitDriver is loud... System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.log.com.gargoylesoftware.htmlunit", "fatal"); HtmlUnitDriver drv = new HtmlUnitDriver(BrowserVersion.FIREFOX_3_6); drv.setJavascriptEnabled(true); try { Example jq = new Example(); jq.setJs(drv); drv.get("http://google.com"); jq.query("[name=q]").val("SeleniumJQuery").parents("form:first").submit(); String results = jq.queryUntil("#resultStats:contains(results)").text(); System.out.println(results.split(" ")[1] + " results found!"); } finally { drv.close(); } }
public static void main(String[] args) throws TimeoutException { // HtmlUnitDriver is loud... System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.log.com.gargoylesoftware.htmlunit", "fatal"); HtmlUnitDriver drv = new HtmlUnitDriver(BrowserVersion.FIREFOX_3_6); drv.setJavascriptEnabled(true); try { Example jq = new Example(); jq.setJs(drv); drv.get("http://google.com"); jq.query("[name=q]").val("SeleniumJQuery").parents("form:first").submit(); String results = jq.queryUntil("#resultStats:contains(results)").text(); System.out.println(results.split(" ")[1] + " results found!"); } finally { drv.quit(); } }
diff --git a/SABS/StartSABS.java b/SABS/StartSABS.java index b19de9d..fa9e77e 100644 --- a/SABS/StartSABS.java +++ b/SABS/StartSABS.java @@ -1,53 +1,53 @@ package SABS; import resources.SABS.StartSABSHelper; import com.rational.test.ft.*; import com.rational.test.ft.object.interfaces.*; import com.rational.test.ft.object.interfaces.SAP.*; import com.rational.test.ft.object.interfaces.WPF.*; import com.rational.test.ft.object.interfaces.dojo.*; import com.rational.test.ft.object.interfaces.siebel.*; import com.rational.test.ft.object.interfaces.flex.*; import com.rational.test.ft.object.interfaces.generichtmlsubdomain.*; import com.rational.test.ft.script.*; import com.rational.test.ft.value.*; import com.rational.test.ft.vp.*; import com.ibm.rational.test.ft.object.interfaces.sapwebportal.*; import ru.sabstest.*; public class StartSABS extends StartSABSHelper { public void testMain(Object[] args) { try{ String user = (String) args[0]; String pwd = (String) args[1]; String sign = (String) args[2]; - run(Settings.path + "\\purs_loader.exe",Settings.path + "\\bin"); + run(Settings.path + "\\bin\\purs_loader.exe",Settings.path + "\\bin"); Log.msg("���� �������."); Loginwindow().inputKeys(user + "{ENTER}" + pwd + "{ENTER}"); Log.msg("������ ������."); logTestResult("Login", true); SignComnfirmbutton().click(); SigncomboBox().select(sign); Signokbutton().click(); sleep(3); LoadSignwindow().inputKeys("{ENTER}"); //SignNextbutton().click(); sleep(3); LoadSignwindow().inputKeys("{ENTER}"); //SignDonebutton().click(); Log.msg("��������� �������������������."); // Window: purs_loader.exe: 044582002 �� ����� ������ �������� SABSwindow().waitForExistence(15.0, 2.0); SABSwindow().maximize(); } catch(Exception e) { e.printStackTrace(); Log.msg(e); } } }
true
true
public void testMain(Object[] args) { try{ String user = (String) args[0]; String pwd = (String) args[1]; String sign = (String) args[2]; run(Settings.path + "\\purs_loader.exe",Settings.path + "\\bin"); Log.msg("���� �������."); Loginwindow().inputKeys(user + "{ENTER}" + pwd + "{ENTER}"); Log.msg("������ ������."); logTestResult("Login", true); SignComnfirmbutton().click(); SigncomboBox().select(sign); Signokbutton().click(); sleep(3); LoadSignwindow().inputKeys("{ENTER}"); //SignNextbutton().click(); sleep(3); LoadSignwindow().inputKeys("{ENTER}"); //SignDonebutton().click(); Log.msg("��������� �������������������."); // Window: purs_loader.exe: 044582002 �� ����� ������ �������� SABSwindow().waitForExistence(15.0, 2.0); SABSwindow().maximize(); } catch(Exception e) { e.printStackTrace(); Log.msg(e); } }
public void testMain(Object[] args) { try{ String user = (String) args[0]; String pwd = (String) args[1]; String sign = (String) args[2]; run(Settings.path + "\\bin\\purs_loader.exe",Settings.path + "\\bin"); Log.msg("���� �������."); Loginwindow().inputKeys(user + "{ENTER}" + pwd + "{ENTER}"); Log.msg("������ ������."); logTestResult("Login", true); SignComnfirmbutton().click(); SigncomboBox().select(sign); Signokbutton().click(); sleep(3); LoadSignwindow().inputKeys("{ENTER}"); //SignNextbutton().click(); sleep(3); LoadSignwindow().inputKeys("{ENTER}"); //SignDonebutton().click(); Log.msg("��������� �������������������."); // Window: purs_loader.exe: 044582002 �� ����� ������ �������� SABSwindow().waitForExistence(15.0, 2.0); SABSwindow().maximize(); } catch(Exception e) { e.printStackTrace(); Log.msg(e); } }
diff --git a/src/utils/PrintInvoice.java b/src/utils/PrintInvoice.java index 405e5a6..557c1b3 100644 --- a/src/utils/PrintInvoice.java +++ b/src/utils/PrintInvoice.java @@ -1,251 +1,251 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package utils; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Chunk; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.Font.FontFamily; import com.itextpdf.text.PageSize; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import pojos.SaleBillPharma; import utils.MyLogger; import com.itextpdf.text.Element; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.ColumnText; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import java.text.SimpleDateFormat; import java.util.List; import pojos.Customer; import pojos.SaleBillPharmaItem; /** * * @author ashutoshsingh */ public class PrintInvoice { private Document document = new Document(PageSize.A4); private SaleBillPharma salebill ; public static final Font[] FONT = new Font[5]; static { FONT[0] = new Font(FontFamily.HELVETICA, 24); FONT[1] = new Font(FontFamily.HELVETICA, 18); FONT[2] = new Font(FontFamily.HELVETICA, 10); FONT[3] = new Font(FontFamily.HELVETICA, 12, Font.BOLD); FONT[4] = new Font(FontFamily.TIMES_ROMAN, 12, Font.ITALIC | Font.UNDERLINE); } public static final Font BOLD_UNDERLINED = new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLD | Font.UNDERLINE); public static final Font ITALICS = new Font(FontFamily.TIMES_ROMAN, 12, Font.ITALIC | Font.UNDERLINE); private SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy"); public PrintInvoice(SaleBillPharma salebill){ this.salebill = salebill; } public void getDocument(){ try{ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("SaleBill#"+salebill.getId()+".pdf")); document.open(); //////////////////////////////////////////////////////////////////////////////////// ///////////////////Start Document Here///////////////////////////////// PdfContentByte directContent = writer.getDirectContent(); Paragraph p1 = new Paragraph("SALE BILL"); p1.setFont(FONT[4]); p1.setAlignment(Element.ALIGN_CENTER); document.add(p1); //show the company details here. Phrase company = new Phrase(new Chunk("BIO PHARMA\nAKOT 444101(M.S)", FONT[3])); document.add(company); document.add(new Phrase("\nLicense No : 20B : AK-88888\n 21B : AK-88889",FONT[2])); System.out.println(dateFormatter.format(salebill.getBillDate())); //show the invoice details // String txt = "Bill No. : " + salebill.getId()+"\nBill Date : " + dateFormatter.format(salebill.getBillDate()) +; Phrase invoiceDetails = new Phrase( "Bill No. : " + salebill.getId()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, invoiceDetails , 400, 693,0); invoiceDetails = new Phrase("Bill Date : " + dateFormatter.format(salebill.getBillDate())); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, invoiceDetails , 400, 681,0); invoiceDetails = new Phrase("Mode of Payment : " + salebill.getMode()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, invoiceDetails , 400, 668,0); //show the customer details Customer c = salebill.getCustomerId(); Phrase custDetails = new Phrase("SOLD TO", FONT[3]); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails , 35, 707,0); custDetails = new Phrase(c.getCompanyName()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails , 35, 693,0); custDetails = new Phrase(c.getSiteAddress()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails , 35, 681,0); custDetails = new Phrase("Licence : "+c.getLicenceNo()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails , 35, 668,0); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); //Item Particulars are shown here PdfPTable table = new PdfPTable(5); table.setTotalWidth(new float[]{275,50,50,50,75}); table.setHeaderRows(1); //headers table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY); table.addCell("Particulars"); table.addCell("MRP"); table.addCell("Rate"); table.addCell("Qnty"); table.addCell("SubTotal"); table.getDefaultCell().setBackgroundColor(null); table.setSpacingAfter(5.0f); List<SaleBillPharmaItem> items = salebill.getSaleBillPharmaItemList(); for(int i = 0 ;i <items.size();i++){ - PdfPCell desc = new PdfPCell(new Phrase(items.get(i).getItemName())); + PdfPCell desc = new PdfPCell(new Phrase(items.get(i).getItemName() + " Exp: " + items.get(i).getExpDate())); // //desc.setBorderColor(BaseColor.WHITE); // desc.setBorderColorLeft(BaseColor.BLACK); // desc.setBorderColorRight(BaseColor.WHITE); table.addCell(desc); PdfPCell mrp = new PdfPCell(new Phrase(items.get(i).getMrp()+"")); // //mrp.setBorderColor(BaseColor.WHITE); // mrp.setBorderColorLeft(BaseColor.BLACK); // mrp.setBorderColorRight(BaseColor.WHITE); table.addCell(mrp); PdfPCell rate = new PdfPCell(new Phrase(items.get(i).getItemRate()+"")); // //rate.setBorderColor(BaseColor.WHITE); // rate.setBorderColorLeft(BaseColor.BLACK); // rate.setBorderColorRight(BaseColor.WHITE); table.addCell(rate); PdfPCell quantity = new PdfPCell(new Phrase(items.get(i).getQnty()+"")); // //quantity.setBorderColor(BaseColor.WHITE); // quantity.setBorderColorLeft(BaseColor.BLACK); // quantity.setBorderColorRight(BaseColor.WHITE); table.addCell(quantity); PdfPCell subtotal = new PdfPCell(new Phrase(items.get(i).getAmt()+"")); // //subtotal.setBorderColor(BaseColor.WHITE); // subtotal.setBorderColorLeft(BaseColor.BLACK); // subtotal.setBorderColorRight(BaseColor.WHITE); table.addCell(subtotal); } //now show the sub details PdfPCell finalCell = new PdfPCell(new Phrase("Total VAT Amt : Rs " + salebill.getTotalVat() + " Total Amount : Rs ")); finalCell.setHorizontalAlignment(Element.ALIGN_RIGHT); finalCell.setColspan(4); table.addCell(finalCell); table.addCell(""+salebill.getTotalAmt()); PdfPCell cdCell = new PdfPCell(new Phrase("Cash Discount (2 %) : (-) Rs")); cdCell.setColspan(4); cdCell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cdCell); table.addCell(""+salebill.getDiscount()); PdfPCell finalAmtCell = new PdfPCell(new Phrase("Final Amount : Rs" )); finalAmtCell.setColspan(4); finalAmtCell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(finalAmtCell); table.addCell(""+salebill.getFinalAmt()); document.add(table); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); Paragraph sign = new Paragraph(new Chunk("Authorized signatory\n(BIO PHARMA)")) ; sign.setAlignment(Element.ALIGN_RIGHT); document.add(sign); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); document.add(new Chunk("Terms and Conditions ", FONT[3])); document.add(Chunk.NEWLINE); document.add(new Chunk("1. This invoice is valid only for 30 days from date of generation")); document.add(Chunk.NEWLINE); document.add(new Chunk("2. All disputes will be subject to AKOT jurisdiction.")); document.add(Chunk.NEWLINE); Paragraph p = new Paragraph("THANK YOU FOR YOUR BUSINESS"); p.setFont(FONT[4]); p.setAlignment(Element.ALIGN_CENTER); document.add(p); ///////////////////End Documnet here////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// document.close(); // no need to close PDFwriter? } catch (DocumentException | FileNotFoundException e) { //LOGGER e.printStackTrace(); } } public void drawTable(PdfContentByte directcontent){ } /** The number of locations on our time table. */ public static final int LOCATIONS = 9; /** The number of time slots on our time table. */ public static final int TIMESLOTS = 32; /** The offset to the left of our time table. */ public static final float OFFSET_LEFT = 30; /** The width of our time table. */ public static final float WIDTH = 540; /** The offset from the bottom of our time table. */ public static final float OFFSET_BOTTOM = 80; /** The height of our time table */ public static final float HEIGHT = 504; /** The offset of the location bar next to our time table. */ public static final float OFFSET_LOCATION = 26; /** The width of the location bar next to our time table. */ public static final float WIDTH_LOCATION = 48; /** The height of a bar showing the movies at one specific location. */ public static final float HEIGHT_LOCATION = HEIGHT / LOCATIONS; /** The width of a time slot. */ public static final float WIDTH_TIMESLOT = WIDTH / TIMESLOTS; }
true
true
public void getDocument(){ try{ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("SaleBill#"+salebill.getId()+".pdf")); document.open(); //////////////////////////////////////////////////////////////////////////////////// ///////////////////Start Document Here///////////////////////////////// PdfContentByte directContent = writer.getDirectContent(); Paragraph p1 = new Paragraph("SALE BILL"); p1.setFont(FONT[4]); p1.setAlignment(Element.ALIGN_CENTER); document.add(p1); //show the company details here. Phrase company = new Phrase(new Chunk("BIO PHARMA\nAKOT 444101(M.S)", FONT[3])); document.add(company); document.add(new Phrase("\nLicense No : 20B : AK-88888\n 21B : AK-88889",FONT[2])); System.out.println(dateFormatter.format(salebill.getBillDate())); //show the invoice details // String txt = "Bill No. : " + salebill.getId()+"\nBill Date : " + dateFormatter.format(salebill.getBillDate()) +; Phrase invoiceDetails = new Phrase( "Bill No. : " + salebill.getId()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, invoiceDetails , 400, 693,0); invoiceDetails = new Phrase("Bill Date : " + dateFormatter.format(salebill.getBillDate())); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, invoiceDetails , 400, 681,0); invoiceDetails = new Phrase("Mode of Payment : " + salebill.getMode()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, invoiceDetails , 400, 668,0); //show the customer details Customer c = salebill.getCustomerId(); Phrase custDetails = new Phrase("SOLD TO", FONT[3]); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails , 35, 707,0); custDetails = new Phrase(c.getCompanyName()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails , 35, 693,0); custDetails = new Phrase(c.getSiteAddress()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails , 35, 681,0); custDetails = new Phrase("Licence : "+c.getLicenceNo()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails , 35, 668,0); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); //Item Particulars are shown here PdfPTable table = new PdfPTable(5); table.setTotalWidth(new float[]{275,50,50,50,75}); table.setHeaderRows(1); //headers table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY); table.addCell("Particulars"); table.addCell("MRP"); table.addCell("Rate"); table.addCell("Qnty"); table.addCell("SubTotal"); table.getDefaultCell().setBackgroundColor(null); table.setSpacingAfter(5.0f); List<SaleBillPharmaItem> items = salebill.getSaleBillPharmaItemList(); for(int i = 0 ;i <items.size();i++){ PdfPCell desc = new PdfPCell(new Phrase(items.get(i).getItemName())); // //desc.setBorderColor(BaseColor.WHITE); // desc.setBorderColorLeft(BaseColor.BLACK); // desc.setBorderColorRight(BaseColor.WHITE); table.addCell(desc); PdfPCell mrp = new PdfPCell(new Phrase(items.get(i).getMrp()+"")); // //mrp.setBorderColor(BaseColor.WHITE); // mrp.setBorderColorLeft(BaseColor.BLACK); // mrp.setBorderColorRight(BaseColor.WHITE); table.addCell(mrp); PdfPCell rate = new PdfPCell(new Phrase(items.get(i).getItemRate()+"")); // //rate.setBorderColor(BaseColor.WHITE); // rate.setBorderColorLeft(BaseColor.BLACK); // rate.setBorderColorRight(BaseColor.WHITE); table.addCell(rate); PdfPCell quantity = new PdfPCell(new Phrase(items.get(i).getQnty()+"")); // //quantity.setBorderColor(BaseColor.WHITE); // quantity.setBorderColorLeft(BaseColor.BLACK); // quantity.setBorderColorRight(BaseColor.WHITE); table.addCell(quantity); PdfPCell subtotal = new PdfPCell(new Phrase(items.get(i).getAmt()+"")); // //subtotal.setBorderColor(BaseColor.WHITE); // subtotal.setBorderColorLeft(BaseColor.BLACK); // subtotal.setBorderColorRight(BaseColor.WHITE); table.addCell(subtotal); } //now show the sub details PdfPCell finalCell = new PdfPCell(new Phrase("Total VAT Amt : Rs " + salebill.getTotalVat() + " Total Amount : Rs ")); finalCell.setHorizontalAlignment(Element.ALIGN_RIGHT); finalCell.setColspan(4); table.addCell(finalCell); table.addCell(""+salebill.getTotalAmt()); PdfPCell cdCell = new PdfPCell(new Phrase("Cash Discount (2 %) : (-) Rs")); cdCell.setColspan(4); cdCell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cdCell); table.addCell(""+salebill.getDiscount()); PdfPCell finalAmtCell = new PdfPCell(new Phrase("Final Amount : Rs" )); finalAmtCell.setColspan(4); finalAmtCell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(finalAmtCell); table.addCell(""+salebill.getFinalAmt()); document.add(table); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); Paragraph sign = new Paragraph(new Chunk("Authorized signatory\n(BIO PHARMA)")) ; sign.setAlignment(Element.ALIGN_RIGHT); document.add(sign); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); document.add(new Chunk("Terms and Conditions ", FONT[3])); document.add(Chunk.NEWLINE); document.add(new Chunk("1. This invoice is valid only for 30 days from date of generation")); document.add(Chunk.NEWLINE); document.add(new Chunk("2. All disputes will be subject to AKOT jurisdiction.")); document.add(Chunk.NEWLINE); Paragraph p = new Paragraph("THANK YOU FOR YOUR BUSINESS"); p.setFont(FONT[4]); p.setAlignment(Element.ALIGN_CENTER); document.add(p); ///////////////////End Documnet here////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// document.close(); // no need to close PDFwriter? } catch (DocumentException | FileNotFoundException e) { //LOGGER e.printStackTrace(); } }
public void getDocument(){ try{ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("SaleBill#"+salebill.getId()+".pdf")); document.open(); //////////////////////////////////////////////////////////////////////////////////// ///////////////////Start Document Here///////////////////////////////// PdfContentByte directContent = writer.getDirectContent(); Paragraph p1 = new Paragraph("SALE BILL"); p1.setFont(FONT[4]); p1.setAlignment(Element.ALIGN_CENTER); document.add(p1); //show the company details here. Phrase company = new Phrase(new Chunk("BIO PHARMA\nAKOT 444101(M.S)", FONT[3])); document.add(company); document.add(new Phrase("\nLicense No : 20B : AK-88888\n 21B : AK-88889",FONT[2])); System.out.println(dateFormatter.format(salebill.getBillDate())); //show the invoice details // String txt = "Bill No. : " + salebill.getId()+"\nBill Date : " + dateFormatter.format(salebill.getBillDate()) +; Phrase invoiceDetails = new Phrase( "Bill No. : " + salebill.getId()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, invoiceDetails , 400, 693,0); invoiceDetails = new Phrase("Bill Date : " + dateFormatter.format(salebill.getBillDate())); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, invoiceDetails , 400, 681,0); invoiceDetails = new Phrase("Mode of Payment : " + salebill.getMode()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, invoiceDetails , 400, 668,0); //show the customer details Customer c = salebill.getCustomerId(); Phrase custDetails = new Phrase("SOLD TO", FONT[3]); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails , 35, 707,0); custDetails = new Phrase(c.getCompanyName()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails , 35, 693,0); custDetails = new Phrase(c.getSiteAddress()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails , 35, 681,0); custDetails = new Phrase("Licence : "+c.getLicenceNo()); ColumnText.showTextAligned(directContent, Element.ALIGN_LEFT, custDetails , 35, 668,0); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); //Item Particulars are shown here PdfPTable table = new PdfPTable(5); table.setTotalWidth(new float[]{275,50,50,50,75}); table.setHeaderRows(1); //headers table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY); table.addCell("Particulars"); table.addCell("MRP"); table.addCell("Rate"); table.addCell("Qnty"); table.addCell("SubTotal"); table.getDefaultCell().setBackgroundColor(null); table.setSpacingAfter(5.0f); List<SaleBillPharmaItem> items = salebill.getSaleBillPharmaItemList(); for(int i = 0 ;i <items.size();i++){ PdfPCell desc = new PdfPCell(new Phrase(items.get(i).getItemName() + " Exp: " + items.get(i).getExpDate())); // //desc.setBorderColor(BaseColor.WHITE); // desc.setBorderColorLeft(BaseColor.BLACK); // desc.setBorderColorRight(BaseColor.WHITE); table.addCell(desc); PdfPCell mrp = new PdfPCell(new Phrase(items.get(i).getMrp()+"")); // //mrp.setBorderColor(BaseColor.WHITE); // mrp.setBorderColorLeft(BaseColor.BLACK); // mrp.setBorderColorRight(BaseColor.WHITE); table.addCell(mrp); PdfPCell rate = new PdfPCell(new Phrase(items.get(i).getItemRate()+"")); // //rate.setBorderColor(BaseColor.WHITE); // rate.setBorderColorLeft(BaseColor.BLACK); // rate.setBorderColorRight(BaseColor.WHITE); table.addCell(rate); PdfPCell quantity = new PdfPCell(new Phrase(items.get(i).getQnty()+"")); // //quantity.setBorderColor(BaseColor.WHITE); // quantity.setBorderColorLeft(BaseColor.BLACK); // quantity.setBorderColorRight(BaseColor.WHITE); table.addCell(quantity); PdfPCell subtotal = new PdfPCell(new Phrase(items.get(i).getAmt()+"")); // //subtotal.setBorderColor(BaseColor.WHITE); // subtotal.setBorderColorLeft(BaseColor.BLACK); // subtotal.setBorderColorRight(BaseColor.WHITE); table.addCell(subtotal); } //now show the sub details PdfPCell finalCell = new PdfPCell(new Phrase("Total VAT Amt : Rs " + salebill.getTotalVat() + " Total Amount : Rs ")); finalCell.setHorizontalAlignment(Element.ALIGN_RIGHT); finalCell.setColspan(4); table.addCell(finalCell); table.addCell(""+salebill.getTotalAmt()); PdfPCell cdCell = new PdfPCell(new Phrase("Cash Discount (2 %) : (-) Rs")); cdCell.setColspan(4); cdCell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cdCell); table.addCell(""+salebill.getDiscount()); PdfPCell finalAmtCell = new PdfPCell(new Phrase("Final Amount : Rs" )); finalAmtCell.setColspan(4); finalAmtCell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(finalAmtCell); table.addCell(""+salebill.getFinalAmt()); document.add(table); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); Paragraph sign = new Paragraph(new Chunk("Authorized signatory\n(BIO PHARMA)")) ; sign.setAlignment(Element.ALIGN_RIGHT); document.add(sign); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); document.add(new Chunk("Terms and Conditions ", FONT[3])); document.add(Chunk.NEWLINE); document.add(new Chunk("1. This invoice is valid only for 30 days from date of generation")); document.add(Chunk.NEWLINE); document.add(new Chunk("2. All disputes will be subject to AKOT jurisdiction.")); document.add(Chunk.NEWLINE); Paragraph p = new Paragraph("THANK YOU FOR YOUR BUSINESS"); p.setFont(FONT[4]); p.setAlignment(Element.ALIGN_CENTER); document.add(p); ///////////////////End Documnet here////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// document.close(); // no need to close PDFwriter? } catch (DocumentException | FileNotFoundException e) { //LOGGER e.printStackTrace(); } }
diff --git a/src/nl/giantit/minecraft/GiantShop/core/Updater/Updater.java b/src/nl/giantit/minecraft/GiantShop/core/Updater/Updater.java index dee6bac..e91ca55 100644 --- a/src/nl/giantit/minecraft/GiantShop/core/Updater/Updater.java +++ b/src/nl/giantit/minecraft/GiantShop/core/Updater/Updater.java @@ -1,119 +1,119 @@ package nl.giantit.minecraft.GiantShop.core.Updater; import nl.giantit.minecraft.GiantShop.GiantShop; import nl.giantit.minecraft.GiantShop.Misc.Heraut; import nl.giantit.minecraft.GiantShop.core.config; import nl.giantit.minecraft.GiantShop.core.Updater.Config.confUpdate; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.net.URL; import java.util.logging.Level; import javax.xml.parsers.DocumentBuilderFactory; public class Updater { private GiantShop plugin; private int tID; private config conf = config.Obtain(); private boolean outOfDate = false; private String newVersion = ""; private void start() { tID = this.plugin.scheduleAsyncRepeatingTask(new Runnable() { @Override public void run() { newVersion = updateCheck(plugin.getDescription().getVersion()); if(isNewer(newVersion, plugin.getDescription().getVersion())) { outOfDate = true; GiantShop.log.log(Level.WARNING, "[" + plugin.getName() + "] " + newVersion + " has been released! You are currently running: " + plugin.getDescription().getVersion()); if(conf.getBoolean("GiantShop.Updater.broadcast")) Heraut.broadcast("&cA new version of GiantShop has just ben released! You are currently running: " + plugin.getDescription().getVersion() + " while the latest version is: " + newVersion, true); } } }, 0L, 432000L); } public Updater(GiantShop plugin) { this.plugin = plugin; if(conf.getBoolean("GiantShop.Updater.checkForUpdates", false)) { this.start(); } } public void stop() { if(!Double.isNaN(tID)) { plugin.getServer().getScheduler().cancelTask(tID); } } public String updateCheck(String version) { String uri = "http://dev.bukkit.org/server-mods/giantshop/files.rss"; try { URL url = new URL(uri); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openConnection().getInputStream()); doc.getDocumentElement().normalize(); Node firstNode = doc.getElementsByTagName("item").item(0); if(firstNode.getNodeType() == 1) { NodeList firstElementTagName = ((Element)firstNode).getElementsByTagName("title"); NodeList firstNodes = ((Element)firstElementTagName.item(0)).getChildNodes(); return firstNodes.item(0).getNodeValue().replace("GiantShop 2.0", "").replaceAll(" \\(([a-zA-Z ]+)\\)", "").trim(); } }catch (Exception e) { } return version; } public iUpdater getUpdater(UpdateType t) { switch(t) { case CONFIG: return new confUpdate(); default: break; } return null; } public boolean isNewer(String newVersion, String version) { - String[] nv = newVersion.replaceAll("\\.[a-zA-Z]+", "").split("\\."); - String[] v = version.replaceAll("\\.[a-zA-Z]+", "").split("\\."); + String[] nv = newVersion.replace("\\.[a-zA-Z]+", "").split("\\."); + String[] v = version.split("-")[0].replace("\\.[a-zA-Z]+", "").split("\\."); Boolean isNew = false; Boolean prevIsEqual = false; for(int i = 0; i < nv.length; i++) { int tn = Integer.parseInt(nv[i]); int tv = 0; if(v.length - 1 >= i) tv = Integer.parseInt(v[i]); if(tn > tv) { if(i == 0 || prevIsEqual == true) { isNew = true; break; } }else if(tn == tv) { prevIsEqual = true; }else{ break; } } return isNew; } public Boolean isOutOfDate() { return this.outOfDate; } public String getNewVersion() { return this.newVersion; } }
true
true
public boolean isNewer(String newVersion, String version) { String[] nv = newVersion.replaceAll("\\.[a-zA-Z]+", "").split("\\."); String[] v = version.replaceAll("\\.[a-zA-Z]+", "").split("\\."); Boolean isNew = false; Boolean prevIsEqual = false; for(int i = 0; i < nv.length; i++) { int tn = Integer.parseInt(nv[i]); int tv = 0; if(v.length - 1 >= i) tv = Integer.parseInt(v[i]); if(tn > tv) { if(i == 0 || prevIsEqual == true) { isNew = true; break; } }else if(tn == tv) { prevIsEqual = true; }else{ break; } } return isNew; }
public boolean isNewer(String newVersion, String version) { String[] nv = newVersion.replace("\\.[a-zA-Z]+", "").split("\\."); String[] v = version.split("-")[0].replace("\\.[a-zA-Z]+", "").split("\\."); Boolean isNew = false; Boolean prevIsEqual = false; for(int i = 0; i < nv.length; i++) { int tn = Integer.parseInt(nv[i]); int tv = 0; if(v.length - 1 >= i) tv = Integer.parseInt(v[i]); if(tn > tv) { if(i == 0 || prevIsEqual == true) { isNew = true; break; } }else if(tn == tv) { prevIsEqual = true; }else{ break; } } return isNew; }
diff --git a/test/util/TcoffeeHelperTest.java b/test/util/TcoffeeHelperTest.java index 8c959ad..a3d163b 100644 --- a/test/util/TcoffeeHelperTest.java +++ b/test/util/TcoffeeHelperTest.java @@ -1,38 +1,38 @@ package util; import java.io.File; import java.util.Arrays; import java.util.List; import org.junit.Test; import play.test.UnitTest; import util.TcoffeeHelper.ResultHtml; public class TcoffeeHelperTest extends UnitTest { @Test public void testParseHtml() { parseHtmlFile( TestHelper.file("/sample-alignment.html") ); } public static void parseHtmlFile( File file ) { String TEST_STYLE = "SPAN { font-family: courier new, courier-new, courier, monospace; font-weight: bold; font-size: 11pt;}"; - String TEST_BODY = "<span class=valuedefault>T-COFFEE,&nbsp;Version_8.98(Wed&nbsp;Jan&nbsp;12&nbsp;00:16:57&nbsp;CET&nbsp;2011&nbsp;-&nbsp;Revision&nbsp;528)</span><br><span class=valuedefault>Cedric&nbsp;Notredame&nbsp;</span><br><span class=valuedefault>SCORE=45</span><br>"; + String TEST_BODY = "<span class=valuedefault>T-COFFEE,&nbsp;Version_8.99(Thu&nbsp;Feb&nbsp;17&nbsp;19:24:49&nbsp;CET&nbsp;2011&nbsp;-&nbsp;Revision&nbsp;594)</span><br><span class=valuedefault>Cedric&nbsp;Notredame&nbsp;</span><br><span class=valuedefault>SCORE=45</span><br>"; ResultHtml result = TcoffeeHelper.parseHtml(file); assertEquals( TEST_STYLE, result.style.trim() .substring(0,TEST_STYLE.length()) ); assertEquals( TEST_BODY, result.body.trim() .substring(0,TEST_BODY.length()) ); } @Test public void parseConsensus() { List<Integer> expected = Arrays.asList( 6, 4, 3, 6, 3,3, -1, 1,1, 3, 4,4,4, 3,3, 4,4,4, 3, 4, 2, 3,3,3, 4,4, 3,3,3,3,3, 1,1,1,1,1,1,1, 2,2,2,2, 1,1,1,1, 2,2, 1,1,1, 2,2, 3, 3, 2, -1,-1, 2,2,2,2,2, 3, 2,2, 4, 5, 6,6, 5,5,5,5, -1,-1,-1,-1,-1, 4, 6, 7, 9 ); List<Integer> result = TcoffeeHelper.parseConsensus(TestHelper.file("/sample-alignment.html")); assertEquals( expected, result ); } }
true
true
public static void parseHtmlFile( File file ) { String TEST_STYLE = "SPAN { font-family: courier new, courier-new, courier, monospace; font-weight: bold; font-size: 11pt;}"; String TEST_BODY = "<span class=valuedefault>T-COFFEE,&nbsp;Version_8.98(Wed&nbsp;Jan&nbsp;12&nbsp;00:16:57&nbsp;CET&nbsp;2011&nbsp;-&nbsp;Revision&nbsp;528)</span><br><span class=valuedefault>Cedric&nbsp;Notredame&nbsp;</span><br><span class=valuedefault>SCORE=45</span><br>"; ResultHtml result = TcoffeeHelper.parseHtml(file); assertEquals( TEST_STYLE, result.style.trim() .substring(0,TEST_STYLE.length()) ); assertEquals( TEST_BODY, result.body.trim() .substring(0,TEST_BODY.length()) ); }
public static void parseHtmlFile( File file ) { String TEST_STYLE = "SPAN { font-family: courier new, courier-new, courier, monospace; font-weight: bold; font-size: 11pt;}"; String TEST_BODY = "<span class=valuedefault>T-COFFEE,&nbsp;Version_8.99(Thu&nbsp;Feb&nbsp;17&nbsp;19:24:49&nbsp;CET&nbsp;2011&nbsp;-&nbsp;Revision&nbsp;594)</span><br><span class=valuedefault>Cedric&nbsp;Notredame&nbsp;</span><br><span class=valuedefault>SCORE=45</span><br>"; ResultHtml result = TcoffeeHelper.parseHtml(file); assertEquals( TEST_STYLE, result.style.trim() .substring(0,TEST_STYLE.length()) ); assertEquals( TEST_BODY, result.body.trim() .substring(0,TEST_BODY.length()) ); }
diff --git a/src/game/DemoGame2.java b/src/game/DemoGame2.java index 9274536..3ff0c60 100644 --- a/src/game/DemoGame2.java +++ b/src/game/DemoGame2.java @@ -1,150 +1,149 @@ package game; /** * @author Kuang Han */ import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import mario.Mario; import keyconfiguration.KeyConfig; import charactersprites.Character; import charactersprites.GameElement; import collision.CharacterPlatformCollision; import collision.UniversalCollision; import com.golden.gamedev.Game; import com.golden.gamedev.GameLoader; import com.golden.gamedev.object.Background; import com.golden.gamedev.object.PlayField; import com.golden.gamedev.object.SpriteGroup; import com.golden.gamedev.object.background.ColorBackground; import charactersprites.Player; import setting.*; public class DemoGame2 extends Game{ PlayField playfield; Background background; KeyConfig keyConfig ,keyConfig1; @Override public void initResources() { playfield = new PlayField(); background = new ColorBackground(Color.gray, 640, 480); playfield.setBackground(background); BufferedImage[] images = this.getImages("resources/Mario1.png", 1, 1); Player mario = new Mario(this); keyConfig = new KeyConfig(mario,this); mario.setKeyList(keyConfig.getInputKeyList()); mario.setImages(images); mario.setLocation(25, 20); - Mario mario1 = new Mario(this); - keyConfig1 = new KeyConfig(mario,this); - keyConfig1.parseKeyConfig("configurations/keyConfig.json"); - mario1.setKeyList(keyConfig1.getKeyList()); - mario1.setImages(images); - mario1.setLocation(300, 20); +// Mario mario1 = new Mario(this); +// keyConfig1 = new KeyConfig(mario1,this); +// mario1.setKeyList(keyConfig1.getInputKeyList()); +// mario1.setImages(images); +// mario1.setLocation(300, 20); images = this.getImages("resources/Bar.png", 1, 1); Platform floor = new BasePlatform(this); floor.setImages(images); floor.setLocation(0, 440); Platform ceiling = new BasePlatform(this); ceiling.setImages(images); ceiling.setLocation(70, -20); images = this.getImages("resources/SmallBar.png", 1, 1); Platform middleBar = new BasePlatform(this); middleBar.setImages(images); middleBar.setLocation(260, 260); images = this.getImages("resources/Wall.png", 1, 1); Platform wall1 = new BasePlatform(this); wall1.setImages(images); wall1.setLocation(0, 0); Platform wall2 = new BasePlatform(this); wall2.setImages(images); wall2.setLocation(620, 0); images = this.getImages("resources/Block1.png", 1, 1); Platform block1 = new ItemDecorator(new BasePlatform(this)); block1.setMass(6); block1.setMovable(false); block1.setImages(images); block1.setLocation(100, 200); images = this.getImages("resources/Block2.png", 1, 1); Platform block2 = new BreakableDecorator(new BasePlatform(this)); block2.setMass(6); block2.setMovable(false); block2.setImages(images); block2.setLocation(160, 200); images = this.getImages("resources/Water2.png", 1, 1); @SuppressWarnings("serial") Platform water = new BasePlatform(this) { @Override public void afterCollidedWith(GameElement e, int collisionSide) { if (e instanceof Mario) { ((Mario) e).setStrength(0.2); } } }; water.setPenetrable(true); water.setDensity(1); water.setDragCoefficient(.2); water.setImages(images); water.setLocation(0, 240); SpriteGroup blocks = new SpriteGroup("block"); blocks.add(water); blocks.add(floor); blocks.add(ceiling); blocks.add(middleBar); blocks.add(wall1); blocks.add(wall2); blocks.add(block1); blocks.add(block2); SpriteGroup characters = new SpriteGroup("characters"); characters.add(mario); // characters.add(mario1); playfield.addGroup(blocks); playfield.addGroup(characters); UniversalCollision collision = new UniversalCollision(); playfield.addCollisionGroup(characters, blocks, collision); } @Override public void render(Graphics2D g) { playfield.render(g); } @Override public void update(long t) { playfield.update(t); } public static void main(String[] args) { GameLoader game = new GameLoader(); game.setup(new DemoGame2(), new Dimension(640,480), false); game.start(); } }
true
true
public void initResources() { playfield = new PlayField(); background = new ColorBackground(Color.gray, 640, 480); playfield.setBackground(background); BufferedImage[] images = this.getImages("resources/Mario1.png", 1, 1); Player mario = new Mario(this); keyConfig = new KeyConfig(mario,this); mario.setKeyList(keyConfig.getInputKeyList()); mario.setImages(images); mario.setLocation(25, 20); Mario mario1 = new Mario(this); keyConfig1 = new KeyConfig(mario,this); keyConfig1.parseKeyConfig("configurations/keyConfig.json"); mario1.setKeyList(keyConfig1.getKeyList()); mario1.setImages(images); mario1.setLocation(300, 20); images = this.getImages("resources/Bar.png", 1, 1); Platform floor = new BasePlatform(this); floor.setImages(images); floor.setLocation(0, 440); Platform ceiling = new BasePlatform(this); ceiling.setImages(images); ceiling.setLocation(70, -20); images = this.getImages("resources/SmallBar.png", 1, 1); Platform middleBar = new BasePlatform(this); middleBar.setImages(images); middleBar.setLocation(260, 260); images = this.getImages("resources/Wall.png", 1, 1); Platform wall1 = new BasePlatform(this); wall1.setImages(images); wall1.setLocation(0, 0); Platform wall2 = new BasePlatform(this); wall2.setImages(images); wall2.setLocation(620, 0); images = this.getImages("resources/Block1.png", 1, 1); Platform block1 = new ItemDecorator(new BasePlatform(this)); block1.setMass(6); block1.setMovable(false); block1.setImages(images); block1.setLocation(100, 200); images = this.getImages("resources/Block2.png", 1, 1); Platform block2 = new BreakableDecorator(new BasePlatform(this)); block2.setMass(6); block2.setMovable(false); block2.setImages(images); block2.setLocation(160, 200); images = this.getImages("resources/Water2.png", 1, 1); @SuppressWarnings("serial") Platform water = new BasePlatform(this) { @Override public void afterCollidedWith(GameElement e, int collisionSide) { if (e instanceof Mario) { ((Mario) e).setStrength(0.2); } } }; water.setPenetrable(true); water.setDensity(1); water.setDragCoefficient(.2); water.setImages(images); water.setLocation(0, 240); SpriteGroup blocks = new SpriteGroup("block"); blocks.add(water); blocks.add(floor); blocks.add(ceiling); blocks.add(middleBar); blocks.add(wall1); blocks.add(wall2); blocks.add(block1); blocks.add(block2); SpriteGroup characters = new SpriteGroup("characters"); characters.add(mario); // characters.add(mario1); playfield.addGroup(blocks); playfield.addGroup(characters); UniversalCollision collision = new UniversalCollision(); playfield.addCollisionGroup(characters, blocks, collision); }
public void initResources() { playfield = new PlayField(); background = new ColorBackground(Color.gray, 640, 480); playfield.setBackground(background); BufferedImage[] images = this.getImages("resources/Mario1.png", 1, 1); Player mario = new Mario(this); keyConfig = new KeyConfig(mario,this); mario.setKeyList(keyConfig.getInputKeyList()); mario.setImages(images); mario.setLocation(25, 20); // Mario mario1 = new Mario(this); // keyConfig1 = new KeyConfig(mario1,this); // mario1.setKeyList(keyConfig1.getInputKeyList()); // mario1.setImages(images); // mario1.setLocation(300, 20); images = this.getImages("resources/Bar.png", 1, 1); Platform floor = new BasePlatform(this); floor.setImages(images); floor.setLocation(0, 440); Platform ceiling = new BasePlatform(this); ceiling.setImages(images); ceiling.setLocation(70, -20); images = this.getImages("resources/SmallBar.png", 1, 1); Platform middleBar = new BasePlatform(this); middleBar.setImages(images); middleBar.setLocation(260, 260); images = this.getImages("resources/Wall.png", 1, 1); Platform wall1 = new BasePlatform(this); wall1.setImages(images); wall1.setLocation(0, 0); Platform wall2 = new BasePlatform(this); wall2.setImages(images); wall2.setLocation(620, 0); images = this.getImages("resources/Block1.png", 1, 1); Platform block1 = new ItemDecorator(new BasePlatform(this)); block1.setMass(6); block1.setMovable(false); block1.setImages(images); block1.setLocation(100, 200); images = this.getImages("resources/Block2.png", 1, 1); Platform block2 = new BreakableDecorator(new BasePlatform(this)); block2.setMass(6); block2.setMovable(false); block2.setImages(images); block2.setLocation(160, 200); images = this.getImages("resources/Water2.png", 1, 1); @SuppressWarnings("serial") Platform water = new BasePlatform(this) { @Override public void afterCollidedWith(GameElement e, int collisionSide) { if (e instanceof Mario) { ((Mario) e).setStrength(0.2); } } }; water.setPenetrable(true); water.setDensity(1); water.setDragCoefficient(.2); water.setImages(images); water.setLocation(0, 240); SpriteGroup blocks = new SpriteGroup("block"); blocks.add(water); blocks.add(floor); blocks.add(ceiling); blocks.add(middleBar); blocks.add(wall1); blocks.add(wall2); blocks.add(block1); blocks.add(block2); SpriteGroup characters = new SpriteGroup("characters"); characters.add(mario); // characters.add(mario1); playfield.addGroup(blocks); playfield.addGroup(characters); UniversalCollision collision = new UniversalCollision(); playfield.addCollisionGroup(characters, blocks, collision); }
diff --git a/src/com/vodafone360/people/engine/meprofile/SyncMeDbUtils.java b/src/com/vodafone360/people/engine/meprofile/SyncMeDbUtils.java index 52af694..13fd3bd 100644 --- a/src/com/vodafone360/people/engine/meprofile/SyncMeDbUtils.java +++ b/src/com/vodafone360/people/engine/meprofile/SyncMeDbUtils.java @@ -1,475 +1,475 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.meprofile; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import android.graphics.BitmapFactory; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.ContactChangeLogTable; import com.vodafone360.people.database.tables.ContactsTable; import com.vodafone360.people.database.tables.StateTable; import com.vodafone360.people.database.tables.ContactChangeLogTable.ContactChangeInfo; import com.vodafone360.people.database.tables.ContactChangeLogTable.ContactChangeType; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactChanges; import com.vodafone360.people.datatypes.ContactDetail; import com.vodafone360.people.datatypes.UserProfile; import com.vodafone360.people.datatypes.ContactDetail.DetailKeys; import com.vodafone360.people.engine.presence.PresenceDbUtils; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.ThirdPartyAccount; import com.vodafone360.people.utils.ThumbnailUtils; /** * This class is a set of utility methods called by * SyncMeEngine to save/read data to/from the database. * */ public class SyncMeDbUtils { /** * Me profile local contact id. */ private static Long sMeProfileLocalContactId; /** * Mime type for the uploaded thumbnail picture of the me profile. */ private static final String PHOTO_MIME_TYPE = "image/png"; /** * This method create a Me Profile contact in the database. * @param dbHelper DatabaseHelper - the database. * @param meProfile Contact - the Me Profile contact * @return ServiceStatus - ServiceStatus.SUCCESS when the new contact is * successfully created. */ public static ServiceStatus setMeProfile(final DatabaseHelper dbHelper, Contact meProfile) { ServiceStatus status = ServiceStatus.ERROR_DATABASE_CORRUPT; // the contact didn't exist before if (sMeProfileLocalContactId == null) { List<Contact> contactList = new ArrayList<Contact>(); contactList.add(meProfile); status = dbHelper.syncAddContactList(contactList, false, false); if (ServiceStatus.SUCCESS == status) { sMeProfileLocalContactId = meProfile.localContactID; status = StateTable.modifyMeProfileID(sMeProfileLocalContactId, dbHelper.getWritableDatabase()); PresenceDbUtils.resetMeProfileIds(); if (ServiceStatus.SUCCESS != status) { List<ContactsTable.ContactIdInfo> idList = new ArrayList<ContactsTable.ContactIdInfo>(); ContactsTable.ContactIdInfo contactIdInfo = new ContactsTable.ContactIdInfo(); contactIdInfo.localId = meProfile.localContactID; contactIdInfo.serverId = meProfile.contactID; contactIdInfo.nativeId = meProfile.nativeContactId; idList.add(contactIdInfo); dbHelper.syncDeleteContactList(idList, false, false); } } } return status; } /** * This method reads Me Profile contact from the database. * @param dbHelper DatabaseHelper - the database * @param contact Contact - the empty (stub) contact to read into * @return ServiceStatus - ServiceStatus.SUCCESS when the contact is * successfully filled, ServiceStatus.ERROR_NOT_FOUND - if the Me * Profile needs to be created first. */ public static ServiceStatus fetchMeProfile(final DatabaseHelper dbHelper, Contact contact) { if (sMeProfileLocalContactId == null) { return ServiceStatus.ERROR_NOT_FOUND; } return dbHelper.fetchContact(sMeProfileLocalContactId, contact); } /** * This method returns the Me Profile localContactId... * @param dbHelper DatabaseHelper - the database * @return Long - Me Profile localContactId. */ public static Long getMeProfileLocalContactId(DatabaseHelper dbHelper) { if (dbHelper == null) return null; if (sMeProfileLocalContactId == null) { sMeProfileLocalContactId = StateTable.fetchMeProfileId(dbHelper.getReadableDatabase()); } return sMeProfileLocalContactId; } /** * This method sets Me Profile localContactId... * @param meProfileId Long - localContactID */ public static void setMeProfileId(final Long meProfileId) { sMeProfileLocalContactId = meProfileId; } /** * This method updates current Me Profile with changes from user profile. * @param dbHelper DatabaseHelper - database * @param currentMeProfile Contact - current me profile, from DB * @param profileChanges - the changes to the current Me Profile * @return String - the profile avatar picture url, null if no picture can * be found. */ public static String updateMeProfile(final DatabaseHelper dbHelper, final Contact currentMeProfile, final UserProfile profileChanges) { if (processMyContactChanges(dbHelper, currentMeProfile, profileChanges) == ServiceStatus.SUCCESS) { return processMyContactDetailsChanges(dbHelper, currentMeProfile, profileChanges); } return null; } /** * This method stores the getMyChanges() response to database - contacts part. * @param dbHelper DatabaseHelper - database. * @param currentMeProfile Contact - me profile contact. * @param profileChanges UserProfile - the contact changes. * @return ServiceStatus - SUCCESS if the contact changes have been successfully processed stored. */ private static ServiceStatus processMyContactChanges(final DatabaseHelper dbHelper, final Contact currentMeProfile, final UserProfile profileChanges) { boolean profileChanged = false; if (profileChanges.userID != null) { currentMeProfile.userID = profileChanges.userID; profileChanged = true; } if (profileChanges.aboutMe != null) { currentMeProfile.aboutMe = profileChanges.aboutMe; profileChanged = true; } if (profileChanges.contactID != null) { currentMeProfile.contactID = profileChanges.contactID; profileChanged = true; } if (profileChanges.gender != null) { currentMeProfile.gender = profileChanges.gender; profileChanged = true; } if (profileChanges.profilePath != null) { currentMeProfile.profilePath = profileChanges.profilePath; profileChanged = true; } if (profileChanges.sources != null) { currentMeProfile.sources.clear(); currentMeProfile.sources.addAll(profileChanges.sources); profileChanged = true; } if (profileChanges.updated != null) { currentMeProfile.updated = profileChanges.updated; profileChanged = true; } if (profileChanged) { ArrayList<Contact> contactList = new ArrayList<Contact>(); contactList.add(currentMeProfile); return dbHelper.syncModifyContactList(contactList, false, false); } return ServiceStatus.SUCCESS; } /** * This method stores the getMyChanges() response to database - details part. * @param dbHelper DatabaseHelper - database. * @param currentMeProfile Contact - me profile contact. * @param profileChanges UserProfile - the contact changes. * @return ServiceStatus - SUCCESS if the contact changes have been successfully processed stored. */ private static String processMyContactDetailsChanges(final DatabaseHelper dbHelper, final Contact currentMeProfile, final UserProfile profileChanges) { String ret = null; final ArrayList<ContactDetail> modifiedDetailList = new ArrayList<ContactDetail>(); final ArrayList<ContactDetail> addedDetailList = new ArrayList<ContactDetail>(); final ArrayList<ContactDetail> deletedDetailList = new ArrayList<ContactDetail>(); for (ContactDetail newDetail : profileChanges.details) { boolean found = false; for (int i = 0; i < currentMeProfile.details.size(); i++) { ContactDetail oldDetail = currentMeProfile.details.get(i); if (DatabaseHelper.doDetailsMatch(newDetail, oldDetail)) { found = true; if (newDetail.deleted != null && newDetail.deleted.booleanValue()) { deletedDetailList.add(oldDetail); } else if (DatabaseHelper.hasDetailChanged(oldDetail, newDetail)) { newDetail.localDetailID = oldDetail.localDetailID; newDetail.localContactID = oldDetail.localContactID; newDetail.nativeContactId = oldDetail.nativeContactId; newDetail.nativeDetailId = oldDetail.nativeDetailId; modifiedDetailList.add(newDetail); if (newDetail.key == DetailKeys.PHOTO) { dbHelper.markMeProfileAvatarChanged(); ret = newDetail.value; } } break; } } - if (!found) { + if (!found && !newDetail.deleted.booleanValue()) { newDetail.localContactID = currentMeProfile.localContactID; newDetail.nativeContactId = currentMeProfile.nativeContactId; if (newDetail.key == DetailKeys.PHOTO) { dbHelper.markMeProfileAvatarChanged(); ret = newDetail.value; } addedDetailList.add(newDetail); } } if (!addedDetailList.isEmpty()) { dbHelper.syncAddContactDetailList(addedDetailList, false, false); } if (!modifiedDetailList.isEmpty()) { dbHelper.syncModifyContactDetailList(modifiedDetailList, false, false); } if (!deletedDetailList.isEmpty()) { dbHelper.syncDeleteContactDetailList(deletedDetailList, false, false); } return ret; } /** * The utility method to save Contacts/setMe() response to the database... * @param dbHelper Database - database * @param uploadedMeProfile Contact - me profile which has been uploaded in * Contacts/setMe() call * @param result ContactChanges - the contents of response Contacts/setMe(). * The contact details in response need to be in the same order * as they were in setMe() request */ public static void updateMeProfileDbDetailIds(final DatabaseHelper dbHelper, final ArrayList<ContactDetail> uploadedDetails, final ContactChanges result) { Contact uploadedMeProfile = new Contact(); SyncMeDbUtils.fetchMeProfile(dbHelper, uploadedMeProfile); boolean changed = false; if (result.mUserProfile.userID != null && !result.mUserProfile.userID.equals(uploadedMeProfile.userID)) { uploadedMeProfile.userID = result.mUserProfile.userID; changed = true; } if (result.mUserProfile.contactID != null && !result.mUserProfile.contactID.equals(uploadedMeProfile.contactID)) { uploadedMeProfile.contactID = result.mUserProfile.contactID; changed = true; } if (changed) { dbHelper.modifyContactServerId(uploadedMeProfile.localContactID, uploadedMeProfile.contactID, uploadedMeProfile.userID); } ListIterator<ContactDetail> destIt = uploadedDetails.listIterator(); for (ContactDetail srcDetail : result.mUserProfile.details) { if (!destIt.hasNext()) { LogUtils .logE("SyncMeDbUtils updateProfileDbDetailsId() - # of details in response > # in request"); return; } final ContactDetail destDetail = destIt.next(); if (srcDetail.key == null || !srcDetail.key.equals(destDetail.key)) { LogUtils.logE("SyncMeDbUtils updateProfileDbDetailsId() - details order is wrong"); break; } destDetail.unique_id = srcDetail.unique_id; dbHelper.syncContactDetail(destDetail.localDetailID, destDetail.unique_id); } } /** * The utility method to save the status text change to the database... * @param dbHelper DatabaseHelper - database * @param statusText String - status text * @return ContactDetail - the modified or created ContactDetail with key * ContactDetail.DetailKeys.PRESENCE_TEXT */ public static ContactDetail updateStatus(final DatabaseHelper dbHelper, final String statusText) { Contact meContact = new Contact(); if (fetchMeProfile(dbHelper, meContact) == ServiceStatus.SUCCESS) { // try to modify an existing detail for (ContactDetail detail : meContact.details) { if (detail.key == ContactDetail.DetailKeys.PRESENCE_TEXT) { detail.value = statusText; // Currently it's only possible to post a status on // Vodafone sns detail.alt = ThirdPartyAccount.SNS_TYPE_VODAFONE; if (ServiceStatus.SUCCESS == dbHelper.modifyContactDetail(detail)) { return detail; } } } // create a new detail instead ContactDetail contactDetail = new ContactDetail(); contactDetail.setValue(statusText, ContactDetail.DetailKeys.PRESENCE_TEXT, null); contactDetail.alt = ThirdPartyAccount.SNS_TYPE_VODAFONE; contactDetail.localContactID = meContact.localContactID; if (ServiceStatus.SUCCESS == dbHelper.addContactDetail(contactDetail)) { return contactDetail; } } return null; } /** * The utility method to save Contacts/setMe() response for the status text * change to the database... * @param dbHelper DatabaseHelper - database. * @param ContactChanges result - status text change. */ public static void savePresenceStatusResponse(final DatabaseHelper dbHelper, ContactChanges result) { Contact currentMeProfile = new Contact(); if (ServiceStatus.SUCCESS == SyncMeDbUtils.fetchMeProfile(dbHelper, currentMeProfile)) { boolean changed = false; if (result.mUserProfile.userID != null && (!result.mUserProfile.userID.equals(currentMeProfile.userID))) { currentMeProfile.userID = result.mUserProfile.userID; changed = true; } if (result.mUserProfile.contactID != null && (!result.mUserProfile.contactID.equals(currentMeProfile.contactID))) { currentMeProfile.contactID = result.mUserProfile.contactID; changed = true; } if (changed) { dbHelper.modifyContactServerId(currentMeProfile.localContactID, currentMeProfile.contactID, currentMeProfile.userID); } for (ContactDetail oldStatus : currentMeProfile.details) { if (oldStatus.key == ContactDetail.DetailKeys.PRESENCE_TEXT) { for (ContactDetail newStatus : result.mUserProfile.details) { if (newStatus.key == ContactDetail.DetailKeys.PRESENCE_TEXT) { oldStatus.unique_id = newStatus.unique_id; dbHelper.syncContactDetail(oldStatus.localDetailID, oldStatus.unique_id); break; } } } } } } /** * A utility method to save the Me Profile contact before sending the * updates to backend * * @param dbHelper DataBaseHelper - database * @param meProfile - the new me Profile to push to server * @return - ArrayList of ContactDetails to be pushed to server */ public static ArrayList<ContactDetail> saveContactDetailChanges(final DatabaseHelper dbHelper, final Contact meProfile) { ArrayList<ContactDetail> updates = new ArrayList<ContactDetail>(); populateWithModifiedDetails(dbHelper, updates, meProfile); // add the deleted details from the change log table to the contact // details populateWithDeletedContactDetails(dbHelper, updates, meProfile.contactID); return updates; } private static void populateWithModifiedDetails(final DatabaseHelper dbHelper, final ArrayList<ContactDetail> updates, Contact meProfile) { boolean avatarChanged = dbHelper.isMeProfileAvatarChanged(); for (ContactDetail detail : meProfile.details) { // LogUtils.logV("meProfile.details:" + detail); if (avatarChanged && detail.key == ContactDetail.DetailKeys.PHOTO) { populatePhotoDetail(dbHelper, meProfile, detail); updates.add(detail); } else if (detail.key != ContactDetail.DetailKeys.VCARD_INTERNET_ADDRESS && detail.key != ContactDetail.DetailKeys.VCARD_IMADDRESS && detail.key != ContactDetail.DetailKeys.PRESENCE_TEXT) { // fix for bug 16029 - it's a server issue (getMe() returns // broken details) but the workaround on the client side is // just // not to add the extra details to setMe() request detail.updated = null; // LogUtils.logV("meProfile.details: put"); updates.add(detail); } } } /** * This method reads a photo data from a file into the ContactDetail... * @param dbHelper DatabaseHelper - database * @param meProfile Contact - me profile contact * @param detail ContactDetail - the detail to write the photo into. */ private static void populatePhotoDetail(final DatabaseHelper dbHelper, final Contact meProfile, final ContactDetail detail) { String path = ThumbnailUtils.thumbnailPath(meProfile.localContactID); detail.photo = BitmapFactory.decodeFile(path); if (detail.photo == null) { LogUtils.logE("SyncMeDbUtils saveContactDetailChanges: " + "Unable to decode avatar"); } detail.photo_mime_type = PHOTO_MIME_TYPE; // when sending the "bytes" the "val" (photoDetail.value)has to // be null, otherwise the the picture on the website is not // updated detail.value = null; detail.updated = null; detail.order = 0; } /** * This method adds the deleted details to the detail list sent to server... * @param dbHelper DatabaseHelper - database * @param contactDetails List<ContactDetail> - the deleted details list * @param contactId Long - Me Profile local contact id. */ private static void populateWithDeletedContactDetails(final DatabaseHelper dbHelper, final List<ContactDetail> contactDetails, final Long contactId) { List<ContactChangeInfo> deletedDetails = new ArrayList<ContactChangeInfo>(); if (!ContactChangeLogTable.fetchMeProfileChangeLog(deletedDetails, ContactChangeType.DELETE_DETAIL, dbHelper.getReadableDatabase(), contactId)) { LogUtils.logE("UploadServerContacts populateWithDeletedContactDetails -" + " Unable to fetch contact changes from database"); return; } for (int i = 0; i < deletedDetails.size(); i++) { ContactChangeInfo info = deletedDetails.get(i); final ContactDetail detail = new ContactDetail(); detail.localDetailID = info.mLocalDetailId; detail.key = info.mServerDetailKey; detail.unique_id = info.mServerDetailId; detail.deleted = true; contactDetails.add(detail); } dbHelper.deleteContactChanges(deletedDetails); } }
true
true
private static String processMyContactDetailsChanges(final DatabaseHelper dbHelper, final Contact currentMeProfile, final UserProfile profileChanges) { String ret = null; final ArrayList<ContactDetail> modifiedDetailList = new ArrayList<ContactDetail>(); final ArrayList<ContactDetail> addedDetailList = new ArrayList<ContactDetail>(); final ArrayList<ContactDetail> deletedDetailList = new ArrayList<ContactDetail>(); for (ContactDetail newDetail : profileChanges.details) { boolean found = false; for (int i = 0; i < currentMeProfile.details.size(); i++) { ContactDetail oldDetail = currentMeProfile.details.get(i); if (DatabaseHelper.doDetailsMatch(newDetail, oldDetail)) { found = true; if (newDetail.deleted != null && newDetail.deleted.booleanValue()) { deletedDetailList.add(oldDetail); } else if (DatabaseHelper.hasDetailChanged(oldDetail, newDetail)) { newDetail.localDetailID = oldDetail.localDetailID; newDetail.localContactID = oldDetail.localContactID; newDetail.nativeContactId = oldDetail.nativeContactId; newDetail.nativeDetailId = oldDetail.nativeDetailId; modifiedDetailList.add(newDetail); if (newDetail.key == DetailKeys.PHOTO) { dbHelper.markMeProfileAvatarChanged(); ret = newDetail.value; } } break; } } if (!found) { newDetail.localContactID = currentMeProfile.localContactID; newDetail.nativeContactId = currentMeProfile.nativeContactId; if (newDetail.key == DetailKeys.PHOTO) { dbHelper.markMeProfileAvatarChanged(); ret = newDetail.value; } addedDetailList.add(newDetail); } } if (!addedDetailList.isEmpty()) { dbHelper.syncAddContactDetailList(addedDetailList, false, false); } if (!modifiedDetailList.isEmpty()) { dbHelper.syncModifyContactDetailList(modifiedDetailList, false, false); } if (!deletedDetailList.isEmpty()) { dbHelper.syncDeleteContactDetailList(deletedDetailList, false, false); } return ret; }
private static String processMyContactDetailsChanges(final DatabaseHelper dbHelper, final Contact currentMeProfile, final UserProfile profileChanges) { String ret = null; final ArrayList<ContactDetail> modifiedDetailList = new ArrayList<ContactDetail>(); final ArrayList<ContactDetail> addedDetailList = new ArrayList<ContactDetail>(); final ArrayList<ContactDetail> deletedDetailList = new ArrayList<ContactDetail>(); for (ContactDetail newDetail : profileChanges.details) { boolean found = false; for (int i = 0; i < currentMeProfile.details.size(); i++) { ContactDetail oldDetail = currentMeProfile.details.get(i); if (DatabaseHelper.doDetailsMatch(newDetail, oldDetail)) { found = true; if (newDetail.deleted != null && newDetail.deleted.booleanValue()) { deletedDetailList.add(oldDetail); } else if (DatabaseHelper.hasDetailChanged(oldDetail, newDetail)) { newDetail.localDetailID = oldDetail.localDetailID; newDetail.localContactID = oldDetail.localContactID; newDetail.nativeContactId = oldDetail.nativeContactId; newDetail.nativeDetailId = oldDetail.nativeDetailId; modifiedDetailList.add(newDetail); if (newDetail.key == DetailKeys.PHOTO) { dbHelper.markMeProfileAvatarChanged(); ret = newDetail.value; } } break; } } if (!found && !newDetail.deleted.booleanValue()) { newDetail.localContactID = currentMeProfile.localContactID; newDetail.nativeContactId = currentMeProfile.nativeContactId; if (newDetail.key == DetailKeys.PHOTO) { dbHelper.markMeProfileAvatarChanged(); ret = newDetail.value; } addedDetailList.add(newDetail); } } if (!addedDetailList.isEmpty()) { dbHelper.syncAddContactDetailList(addedDetailList, false, false); } if (!modifiedDetailList.isEmpty()) { dbHelper.syncModifyContactDetailList(modifiedDetailList, false, false); } if (!deletedDetailList.isEmpty()) { dbHelper.syncDeleteContactDetailList(deletedDetailList, false, false); } return ret; }
diff --git a/src/Model/Skills/Hunter/SkillCripplingTrap.java b/src/Model/Skills/Hunter/SkillCripplingTrap.java index a09739e..89cd896 100644 --- a/src/Model/Skills/Hunter/SkillCripplingTrap.java +++ b/src/Model/Skills/Hunter/SkillCripplingTrap.java @@ -1,44 +1,44 @@ package Model.Skills.Hunter; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import Model.Skills.Skill; import Model.StatusEffects.StatusEffectMovement; import Model.StatusEffects.StatusEffectImmobilize; public class SkillCripplingTrap extends Skill { public SkillCripplingTrap(){ //String name, int cd, int range, double speed, int aoe, int cost, int damage, StatusEffect SE - super("Crippling trap", 1000, 0, 0.4, 3, 25, 150, 300, 300, 300,"Crippling shot: \nA shot which slows the enemy.\n" + + super("Crippling trap", 1000, 0, 0.4, 3, 25, 150, 300, 300, 300,"Crippling trap: \nA trap which slows the enemy.\n" + "Level 1: 150 damage\n" + "Level 2: 300 damage\n" + "Level 3: 300 damage\n" + "Level 4: 300 damage"); Image attackImage = null; Image[] animation = new Image[1]; Image[] skillBar = new Image[3]; super.setOffensiveStatusEffectShell(new StatusEffectMovement(this, -0.3, 1),true); try { attackImage = new Image("res/animations/arrow.png"); animation[0] = new Image("res/animations/trap/slowingtrap.png"); skillBar[0] = new Image("res/skillIcons/cripplingshot.png"); skillBar[1] = new Image("res/skillIcons/cripplingshot_active.png"); skillBar[2] = new Image("res/skillIcons/cripplingshot_disabled.png"); } catch (SlickException e) { // TODO Auto-generated catch block e.printStackTrace(); } super.setImage(attackImage); super.setEndState(animation, 20000, 1010); super.setSkillBarImages(skillBar); } }
true
true
public SkillCripplingTrap(){ //String name, int cd, int range, double speed, int aoe, int cost, int damage, StatusEffect SE super("Crippling trap", 1000, 0, 0.4, 3, 25, 150, 300, 300, 300,"Crippling shot: \nA shot which slows the enemy.\n" + "Level 1: 150 damage\n" + "Level 2: 300 damage\n" + "Level 3: 300 damage\n" + "Level 4: 300 damage"); Image attackImage = null; Image[] animation = new Image[1]; Image[] skillBar = new Image[3]; super.setOffensiveStatusEffectShell(new StatusEffectMovement(this, -0.3, 1),true); try { attackImage = new Image("res/animations/arrow.png"); animation[0] = new Image("res/animations/trap/slowingtrap.png"); skillBar[0] = new Image("res/skillIcons/cripplingshot.png"); skillBar[1] = new Image("res/skillIcons/cripplingshot_active.png"); skillBar[2] = new Image("res/skillIcons/cripplingshot_disabled.png"); } catch (SlickException e) { // TODO Auto-generated catch block e.printStackTrace(); } super.setImage(attackImage); super.setEndState(animation, 20000, 1010); super.setSkillBarImages(skillBar); }
public SkillCripplingTrap(){ //String name, int cd, int range, double speed, int aoe, int cost, int damage, StatusEffect SE super("Crippling trap", 1000, 0, 0.4, 3, 25, 150, 300, 300, 300,"Crippling trap: \nA trap which slows the enemy.\n" + "Level 1: 150 damage\n" + "Level 2: 300 damage\n" + "Level 3: 300 damage\n" + "Level 4: 300 damage"); Image attackImage = null; Image[] animation = new Image[1]; Image[] skillBar = new Image[3]; super.setOffensiveStatusEffectShell(new StatusEffectMovement(this, -0.3, 1),true); try { attackImage = new Image("res/animations/arrow.png"); animation[0] = new Image("res/animations/trap/slowingtrap.png"); skillBar[0] = new Image("res/skillIcons/cripplingshot.png"); skillBar[1] = new Image("res/skillIcons/cripplingshot_active.png"); skillBar[2] = new Image("res/skillIcons/cripplingshot_disabled.png"); } catch (SlickException e) { // TODO Auto-generated catch block e.printStackTrace(); } super.setImage(attackImage); super.setEndState(animation, 20000, 1010); super.setSkillBarImages(skillBar); }
diff --git a/junixsocket/src/main/org/newsclub/net/unix/NativeUnixSocket.java b/junixsocket/src/main/org/newsclub/net/unix/NativeUnixSocket.java index 664658c..047ece5 100644 --- a/junixsocket/src/main/org/newsclub/net/unix/NativeUnixSocket.java +++ b/junixsocket/src/main/org/newsclub/net/unix/NativeUnixSocket.java @@ -1,160 +1,160 @@ /** * junixsocket * * Copyright (c) 2009 NewsClub, Christian Kohlschütter * * The author 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.newsclub.net.unix; import java.io.File; import java.io.FileDescriptor; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * JNI connector to native JNI C code. * * @author Christian Kohlschütter */ final class NativeUnixSocket { private static final String PROP_LIBRARY_LOADED = "org.newsclub.net.unix.library.loaded"; private static final String PROP_LIBRARY_DIR = "org.newsclub.net.unix.library.path"; static boolean isSupported() { return "true".equals(System.getProperty(PROP_LIBRARY_LOADED, "false")); } static void checkSupported() { load(); } static void load() { if (!isSupported()) { String osName = System.getProperty("os.name"); final String arch = System.getProperty("os.arch"); final String javaSpec = System .getProperty("java.specification.version"); String prefix = "lib"; String suffix = ".so"; String os = osName.replaceAll("[^A-Za-z0-9]", "").toLowerCase(); if ("macosx".equals(os)) { suffix = ".dylib"; - } else if ("linux".equals(os)) { + } else if ("linux".equals(os) || "freebsd".equals(os)) { suffix = ".so"; } else { Logger.getLogger(NativeUnixSocket.class.getName()).log( Level.WARNING, "Unsupported Operating System: " + osName); } final String libDir = System.getProperty(PROP_LIBRARY_DIR, NativeUnixSocketConfig.LIBRARY_PATH); String[] libDirs = libDir == null ? new String[] { null } : new String[] { libDir, null }; String[] javaSpecs = "1.5".equals(javaSpec) ? new String[] { javaSpec } : new String[] { javaSpec, "1.5" }; List<String> paths = new ArrayList<String>(); UnsatisfiedLinkError ule = null; findLib: for (String ld : libDirs) { for (String js : javaSpecs) { ule = null; String libId = "junixsocket-" + os + "-" + js + "-" + arch; try { if (ld == null) { paths.add("lib:" + libId); System.loadLibrary(libId); } else { final File libFile = new File(new File(ld), prefix + libId + suffix); final String absPath = libFile.getAbsolutePath(); paths.add(absPath); System.load(absPath); } } catch (UnsatisfiedLinkError e) { ule = e; } if (ule == null) { break findLib; } } } if (ule != null) { throw (UnsatisfiedLinkError) new UnsatisfiedLinkError( "Could not load junixsocket library, tried " + paths) .initCause(ule); } System.setProperty(PROP_LIBRARY_LOADED, "true"); } } static { load(); } native static void bind(final String socketFile, final FileDescriptor fd, final int backlog) throws IOException; native static void listen(final FileDescriptor fd, final int backlog) throws IOException; native static void accept(final String socketFile, final FileDescriptor fdServer, final FileDescriptor fd) throws IOException; native static void connect(final String socketFile, final FileDescriptor fd) throws IOException; native static int read(final FileDescriptor fd, byte[] b, int off, int len) throws IOException; native static int write(final FileDescriptor fd, byte[] b, int off, int len) throws IOException; native static void close(final FileDescriptor fd) throws IOException; native static void shutdown(final FileDescriptor fd, int mode) throws IOException; native static int getSocketOptionInt(final FileDescriptor fd, int optionId) throws IOException; native static void setSocketOptionInt(final FileDescriptor fd, int optionId, int value) throws IOException; native static void unlink(final String socketFile) throws IOException; native static int available(final FileDescriptor fd) throws IOException; native static void initServerImpl(final AFUNIXServerSocket serverSocket, final AFUNIXSocketImpl impl); native static void setCreated(final AFUNIXSocket socket); native static void setConnected(final AFUNIXSocket socket); native static void setBound(final AFUNIXSocket socket); native static void setCreatedServer(final AFUNIXServerSocket socket); native static void setBoundServer(final AFUNIXServerSocket socket); native static void setPort(final AFUNIXSocketAddress addr, int port); }
true
true
static void load() { if (!isSupported()) { String osName = System.getProperty("os.name"); final String arch = System.getProperty("os.arch"); final String javaSpec = System .getProperty("java.specification.version"); String prefix = "lib"; String suffix = ".so"; String os = osName.replaceAll("[^A-Za-z0-9]", "").toLowerCase(); if ("macosx".equals(os)) { suffix = ".dylib"; } else if ("linux".equals(os)) { suffix = ".so"; } else { Logger.getLogger(NativeUnixSocket.class.getName()).log( Level.WARNING, "Unsupported Operating System: " + osName); } final String libDir = System.getProperty(PROP_LIBRARY_DIR, NativeUnixSocketConfig.LIBRARY_PATH); String[] libDirs = libDir == null ? new String[] { null } : new String[] { libDir, null }; String[] javaSpecs = "1.5".equals(javaSpec) ? new String[] { javaSpec } : new String[] { javaSpec, "1.5" }; List<String> paths = new ArrayList<String>(); UnsatisfiedLinkError ule = null; findLib: for (String ld : libDirs) { for (String js : javaSpecs) { ule = null; String libId = "junixsocket-" + os + "-" + js + "-" + arch; try { if (ld == null) { paths.add("lib:" + libId); System.loadLibrary(libId); } else { final File libFile = new File(new File(ld), prefix + libId + suffix); final String absPath = libFile.getAbsolutePath(); paths.add(absPath); System.load(absPath); } } catch (UnsatisfiedLinkError e) { ule = e; } if (ule == null) { break findLib; } } } if (ule != null) { throw (UnsatisfiedLinkError) new UnsatisfiedLinkError( "Could not load junixsocket library, tried " + paths) .initCause(ule); } System.setProperty(PROP_LIBRARY_LOADED, "true"); } }
static void load() { if (!isSupported()) { String osName = System.getProperty("os.name"); final String arch = System.getProperty("os.arch"); final String javaSpec = System .getProperty("java.specification.version"); String prefix = "lib"; String suffix = ".so"; String os = osName.replaceAll("[^A-Za-z0-9]", "").toLowerCase(); if ("macosx".equals(os)) { suffix = ".dylib"; } else if ("linux".equals(os) || "freebsd".equals(os)) { suffix = ".so"; } else { Logger.getLogger(NativeUnixSocket.class.getName()).log( Level.WARNING, "Unsupported Operating System: " + osName); } final String libDir = System.getProperty(PROP_LIBRARY_DIR, NativeUnixSocketConfig.LIBRARY_PATH); String[] libDirs = libDir == null ? new String[] { null } : new String[] { libDir, null }; String[] javaSpecs = "1.5".equals(javaSpec) ? new String[] { javaSpec } : new String[] { javaSpec, "1.5" }; List<String> paths = new ArrayList<String>(); UnsatisfiedLinkError ule = null; findLib: for (String ld : libDirs) { for (String js : javaSpecs) { ule = null; String libId = "junixsocket-" + os + "-" + js + "-" + arch; try { if (ld == null) { paths.add("lib:" + libId); System.loadLibrary(libId); } else { final File libFile = new File(new File(ld), prefix + libId + suffix); final String absPath = libFile.getAbsolutePath(); paths.add(absPath); System.load(absPath); } } catch (UnsatisfiedLinkError e) { ule = e; } if (ule == null) { break findLib; } } } if (ule != null) { throw (UnsatisfiedLinkError) new UnsatisfiedLinkError( "Could not load junixsocket library, tried " + paths) .initCause(ule); } System.setProperty(PROP_LIBRARY_LOADED, "true"); } }
diff --git a/resources/sip/ra/src/main/java/org/mobicents/slee/resource/sip/wrappers/ServerTransactionWrapper.java b/resources/sip/ra/src/main/java/org/mobicents/slee/resource/sip/wrappers/ServerTransactionWrapper.java index 9c04b6701..6c0e63edf 100755 --- a/resources/sip/ra/src/main/java/org/mobicents/slee/resource/sip/wrappers/ServerTransactionWrapper.java +++ b/resources/sip/ra/src/main/java/org/mobicents/slee/resource/sip/wrappers/ServerTransactionWrapper.java @@ -1,324 +1,324 @@ /* * Mobicents: The Open Source SLEE Platform * * Copyright 2003-2005, CocoonHive, LLC., * and individual contributors as indicated * by the @authors tag. See the copyright.txt * in the distribution for a full listing of * individual contributors. * * This is free software; you can redistribute it * and/or modify it under the terms of the * GNU Lesser General Public License as * published by the Free Software Foundation; * either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the * GNU Lesser General Public * License along with this software; * if not, write to the Free * Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: * http://www.fsf.org. */ package org.mobicents.slee.resource.sip.wrappers; import java.util.Timer; import javax.sip.Dialog; import javax.sip.InvalidArgumentException; import javax.sip.ObjectInUseException; import javax.sip.ServerTransaction; import javax.sip.SipException; import javax.sip.Transaction; import javax.sip.TransactionState; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.mobicents.slee.container.SleeContainer; import org.mobicents.slee.resource.sip.SipActivityHandle; import org.mobicents.slee.resource.sip.SipResourceAdaptor; /** * * Wraps SIP ServerTransaction. * * @author M. Ranganathan * @author B. Baranowski */ public class ServerTransactionWrapper implements ServerTransaction, SecretWrapperInterface { private static Logger logger = Logger .getLogger(ServerTransactionWrapper.class); // REAL TX WHICH IS WRAPPED IN THIS CLASS private ServerTransaction realTransaction = null; // TXs APPLICATION DATA IS USED TO STORE THIS OBJECT IN TX, SO WE HAVE TO // PROVIDE SOMETHING IN RETURN private Object applicationData = null; // private boolean proxied=false; private SleeContainer serviceContainer = null; // THIS IS FOR INVITES CANCEL private RequestEventWrapper inviteCANCEL = null; private CancelWaitTimerTask cancelTimerTask = null; private DialogWrapper dialogWrapper; private SipActivityHandle activityHandle = null; private static long cancelWait = 5000; // Timer which postpones cancel firing into slee private static Timer cancelTimer = new Timer(); public static void setCancelWait(long timeout) { cancelWait = timeout; } private SipResourceAdaptor sipResourceAdaptor; public ServerTransactionWrapper(ServerTransaction ST, DialogWrapper dialogWrapper, SipResourceAdaptor sipResourceAdaptor) { realTransaction = ST; this.dialogWrapper = dialogWrapper; // STORE THIS OBJECT IN TX ST.setApplicationData(this); this.sipResourceAdaptor = sipResourceAdaptor; serviceContainer = SleeContainer.lookupFromJndi(); realTransaction.setApplicationData(this); activityHandle = new SipActivityHandle(ST.getBranchId() + "_" + ST.getRequest().getMethod()); } public Transaction getRealTransaction() { return realTransaction; } public void setDialogWrapper(DialogWrapper dialogWrapper) { this.dialogWrapper = dialogWrapper; } public void sendResponse(Response arg0) throws SipException, InvalidArgumentException { boolean gotToFire = false; try { if (this.dialogWrapper != null) this.dialogWrapper.startStateEventFireSequence(); this.realTransaction.sendResponse(arg0); gotToFire = true; // HERE WE HAVE TO CHECK STATE CHANGE OF A DIALOG if (this.dialogWrapper == null) return; if (logger.isDebugEnabled()) { logger .debug("\n---------------------------------------\nSENDING RESPONSE:\n" + arg0 + "\n---------------------------------------"); } if (logger.isDebugEnabled()) { logger .debug("\n-----------------------------------------\nOld State: " + ((DialogWrapper) dialogWrapper) .getLastState() + "\nNew State: " + dialogWrapper.getState() + "\n--------------------------------------"); } this.dialogWrapper.fireDialogStateEvent(arg0); } finally { - if (!gotToFire) + if (!gotToFire&& this.dialogWrapper!=null) this.dialogWrapper.endStateEventFireSequence(); } } public void enableRetransmissionAlerts() throws SipException { realTransaction.enableRetransmissionAlerts(); } public Dialog getDialog() { return dialogWrapper; } public TransactionState getState() { return realTransaction.getState(); } public int getRetransmitTimer() throws UnsupportedOperationException { return realTransaction.getRetransmitTimer(); } public void setRetransmitTimer(int arg0) throws UnsupportedOperationException { realTransaction.setRetransmitTimer(arg0); } public String getBranchId() { // LEAK BUG PATCH return realTransaction.getBranchId(); // return // realTransaction.getBranchId()+"_"+realTransaction.getRequest().getMethod(); } public Request getRequest() { return realTransaction.getRequest(); } public void setApplicationData(Object arg0) { applicationData = arg0; } public Object getApplicationData() { return applicationData; } public void terminate() throws ObjectInUseException { // FIXME: DO WE NEED SOMETHING HERE? realTransaction.terminate(); } public String toString() { return "[TransactionW WRAPPED[" + realTransaction + "] BRANCHID[" + realTransaction.getBranchId() + "] STATE[" + realTransaction.getState() + "] DIALOG{ " + dialogWrapper + " } ]"; } /** * Set local cancel request. Also activats timer, after it expires cancel * will be fired into slee. * * @param cancel */ public void setCancel(RequestEventWrapper cancel) { if (logger.isDebugEnabled()) { logger.debug("\n XxX Setting cancel to:" + cancel + " for tx:" + realTransaction.getBranchId() + "_" + realTransaction.getRequest().getMethod()); } this.inviteCANCEL = cancel; if (this.inviteCANCEL == null) { this.cancelTimerTask.cancel(); this.cancelTimerTask = null; } else { this.cancelTimerTask = new CancelWaitTimerTask(this.inviteCANCEL, this, sipResourceAdaptor.getSipFactoryProvider(), sipResourceAdaptor.getSleeEndpoint(), sipResourceAdaptor .getBootstrapContext().getEventLookupFacility(), logger); this.cancelTimer.schedule(this.cancelTimerTask, this.cancelWait); } if (logger.isDebugEnabled()) { logger.debug("\n XxX CANCEL SET"); logger.debug("======= STAGE: \n" + inviteCANCEL + "\n" + cancelTimerTask + "\n=========="); } } /** * Removes cancel timer, etc * */ public void processCancelOnEventProcessingFailed() { if (logger.isDebugEnabled()) { logger .debug("\n XxX processCancelOnEventProcessingFailed called for tx:" + realTransaction.getBranchId() + "_" + realTransaction.getRequest().getMethod()); logger.debug("======= STAGE: \n" + inviteCANCEL + "\n" + cancelTimerTask + "\n=========="); } if (this.inviteCANCEL == null) return; this.cancelTimerTask.cancel(); if (!this.cancelTimerTask.hasRun()) this.cancelTimerTask.run(); this.cancelTimerTask = null; this.inviteCANCEL = null; } /** * Removes cancel timer, etc * */ public void processCancelOnEventProcessingSucess() { if (logger.isDebugEnabled()) { logger .debug("\n XxX processCancelOnEventProcessingSucess() called for tx:" + realTransaction.getBranchId() + "_" + realTransaction.getRequest().getMethod()); logger.debug("======= STAGE: \n" + inviteCANCEL + "\n" + cancelTimerTask + "\n=========="); } if (this.inviteCANCEL == null) return; this.cancelTimerTask.cancel(); if (!this.cancelTimerTask.hasRun()) this.cancelTimerTask.run(); this.cancelTimerTask = null; this.inviteCANCEL = null; } /** * Removes cancel timer, etc * */ public void processCancelOnActivityEnd() { if (logger.isDebugEnabled()) { logger.debug("\n XxX processCancelOnActivityEnd() called for tx:" + realTransaction.getBranchId() + "_" + realTransaction.getRequest().getMethod()); logger.debug("======= STAGE: \n" + inviteCANCEL + "\n" + cancelTimerTask + "\n=========="); } if (this.inviteCANCEL == null) return; this.cancelTimerTask.cancel(); // this.cancelTimerTask.run(); this.cancelTimerTask = null; this.inviteCANCEL = null; } public SipActivityHandle getActivityHandle() { return this.activityHandle; } }
true
true
public void sendResponse(Response arg0) throws SipException, InvalidArgumentException { boolean gotToFire = false; try { if (this.dialogWrapper != null) this.dialogWrapper.startStateEventFireSequence(); this.realTransaction.sendResponse(arg0); gotToFire = true; // HERE WE HAVE TO CHECK STATE CHANGE OF A DIALOG if (this.dialogWrapper == null) return; if (logger.isDebugEnabled()) { logger .debug("\n---------------------------------------\nSENDING RESPONSE:\n" + arg0 + "\n---------------------------------------"); } if (logger.isDebugEnabled()) { logger .debug("\n-----------------------------------------\nOld State: " + ((DialogWrapper) dialogWrapper) .getLastState() + "\nNew State: " + dialogWrapper.getState() + "\n--------------------------------------"); } this.dialogWrapper.fireDialogStateEvent(arg0); } finally { if (!gotToFire) this.dialogWrapper.endStateEventFireSequence(); } }
public void sendResponse(Response arg0) throws SipException, InvalidArgumentException { boolean gotToFire = false; try { if (this.dialogWrapper != null) this.dialogWrapper.startStateEventFireSequence(); this.realTransaction.sendResponse(arg0); gotToFire = true; // HERE WE HAVE TO CHECK STATE CHANGE OF A DIALOG if (this.dialogWrapper == null) return; if (logger.isDebugEnabled()) { logger .debug("\n---------------------------------------\nSENDING RESPONSE:\n" + arg0 + "\n---------------------------------------"); } if (logger.isDebugEnabled()) { logger .debug("\n-----------------------------------------\nOld State: " + ((DialogWrapper) dialogWrapper) .getLastState() + "\nNew State: " + dialogWrapper.getState() + "\n--------------------------------------"); } this.dialogWrapper.fireDialogStateEvent(arg0); } finally { if (!gotToFire&& this.dialogWrapper!=null) this.dialogWrapper.endStateEventFireSequence(); } }
diff --git a/src/main/java/edu/uga/radiant/ajax/SearchOntologyTerm.java b/src/main/java/edu/uga/radiant/ajax/SearchOntologyTerm.java index b53fd94..cfec1a5 100644 --- a/src/main/java/edu/uga/radiant/ajax/SearchOntologyTerm.java +++ b/src/main/java/edu/uga/radiant/ajax/SearchOntologyTerm.java @@ -1,91 +1,91 @@ package edu.uga.radiant.ajax; import java.util.Iterator; import java.util.Map; import org.apache.log4j.Logger; import org.semanticweb.owlapi.model.OWLClass; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import edu.uga.radiant.ontology.OntologyManager; import edu.uga.radiant.ontology.SearchOntology; import edu.uga.radiant.printTree.LoadOWLTree; import edu.uga.radiant.util.RadiantToolConfig; import edu.uga.radiant.util.SortValueMap; public class SearchOntologyTerm extends ActionSupport { /** * */ private static final long serialVersionUID = 1L; private String term; private String errormsg; private String innerHtml; public String execute() { Logger logger = RadiantToolConfig.getLogger(); errormsg = ""; @SuppressWarnings("rawtypes") Map session = ActionContext.getContext().getSession(); OntologyManager mgr = (OntologyManager) session.get("OntologyManager"); StringBuffer buf = new StringBuffer(); SearchOntology search = new SearchOntology(mgr); logger.debug("term = " + term); SortValueMap<String, Double> searchTerms = search.search(term); logger.debug("searchTerms size = " + searchTerms.size()); Iterator<String> it = searchTerms.keySet().iterator(); - buf.append("<ol id='searchReslutSelectable'>"); + buf.append("<ol id='searchResultSelectable'>"); int i = 0; while(it.hasNext() && i < 20){ String iri = it.next(); OWLClass cls = mgr.getConceptClass(iri); String definition = mgr.getClassDefinition(cls); String label = mgr.getClassLabel(cls); String fragmentData = LoadOWLTree.charReplace(iri); String score = searchTerms.get(iri).toString(); if (score.length() > 6) score = score.substring(0, 6); - buf.append("<li data='" + fragmentData + "' class=\"ui-widget-content ontologySearchResullts\" style=\"margin:6px;padding:2px;\"><span value=\"" + fragmentData + "\" style='width:50%;float:left'><b>" + label + " : " + score + "</b></span><br/><" + iri + ">" + definition + "</li>"); + buf.append("<li data='" + fragmentData + "' class=\"ui-widget-content ontologySearchResults\" style=\"margin:6px;padding:2px;\"><span value=\"" + fragmentData + "\" style='width:50%;float:left'><b>" + label + " : " + score + "</b></span><br/><" + iri + ">" + ((definition== null)? "" : definition) + "</li>"); i++; } buf.append("<ol>"); innerHtml = buf.toString(); return SUCCESS; } public void setErrormsg(String errormsg) { this.errormsg = errormsg; } public String getErrormsg() { return errormsg; } public void setInnerHtml(String innerHtml) { this.innerHtml = innerHtml; } public String getInnerHtml() { return innerHtml; } public void setTerm(String term) { this.term = term; } public String getTerm() { return term; } }
false
true
public String execute() { Logger logger = RadiantToolConfig.getLogger(); errormsg = ""; @SuppressWarnings("rawtypes") Map session = ActionContext.getContext().getSession(); OntologyManager mgr = (OntologyManager) session.get("OntologyManager"); StringBuffer buf = new StringBuffer(); SearchOntology search = new SearchOntology(mgr); logger.debug("term = " + term); SortValueMap<String, Double> searchTerms = search.search(term); logger.debug("searchTerms size = " + searchTerms.size()); Iterator<String> it = searchTerms.keySet().iterator(); buf.append("<ol id='searchReslutSelectable'>"); int i = 0; while(it.hasNext() && i < 20){ String iri = it.next(); OWLClass cls = mgr.getConceptClass(iri); String definition = mgr.getClassDefinition(cls); String label = mgr.getClassLabel(cls); String fragmentData = LoadOWLTree.charReplace(iri); String score = searchTerms.get(iri).toString(); if (score.length() > 6) score = score.substring(0, 6); buf.append("<li data='" + fragmentData + "' class=\"ui-widget-content ontologySearchResullts\" style=\"margin:6px;padding:2px;\"><span value=\"" + fragmentData + "\" style='width:50%;float:left'><b>" + label + " : " + score + "</b></span><br/><" + iri + ">" + definition + "</li>"); i++; } buf.append("<ol>"); innerHtml = buf.toString(); return SUCCESS; }
public String execute() { Logger logger = RadiantToolConfig.getLogger(); errormsg = ""; @SuppressWarnings("rawtypes") Map session = ActionContext.getContext().getSession(); OntologyManager mgr = (OntologyManager) session.get("OntologyManager"); StringBuffer buf = new StringBuffer(); SearchOntology search = new SearchOntology(mgr); logger.debug("term = " + term); SortValueMap<String, Double> searchTerms = search.search(term); logger.debug("searchTerms size = " + searchTerms.size()); Iterator<String> it = searchTerms.keySet().iterator(); buf.append("<ol id='searchResultSelectable'>"); int i = 0; while(it.hasNext() && i < 20){ String iri = it.next(); OWLClass cls = mgr.getConceptClass(iri); String definition = mgr.getClassDefinition(cls); String label = mgr.getClassLabel(cls); String fragmentData = LoadOWLTree.charReplace(iri); String score = searchTerms.get(iri).toString(); if (score.length() > 6) score = score.substring(0, 6); buf.append("<li data='" + fragmentData + "' class=\"ui-widget-content ontologySearchResults\" style=\"margin:6px;padding:2px;\"><span value=\"" + fragmentData + "\" style='width:50%;float:left'><b>" + label + " : " + score + "</b></span><br/><" + iri + ">" + ((definition== null)? "" : definition) + "</li>"); i++; } buf.append("<ol>"); innerHtml = buf.toString(); return SUCCESS; }
diff --git a/programs/slammer/analysis/CoupledSimplified.java b/programs/slammer/analysis/CoupledSimplified.java index 84e764f0..144ebe77 100644 --- a/programs/slammer/analysis/CoupledSimplified.java +++ b/programs/slammer/analysis/CoupledSimplified.java @@ -1,50 +1,50 @@ /* This file is in the public domain. */ package slammer.analysis; import java.text.DecimalFormat; public class CoupledSimplified extends Analysis { public static String[] BrayAndTravasarou2007(final double ky, final double ts, final double sa, final double m) { String ret[] = new String[3]; final double p = 0.2316419; final double b1 = 0.319381530; final double b2 = -0.356563782; final double b3 = 1.781477937; final double b4 = -1.821255978; final double b5 = 1.330274429; final double lnky = Math.log(ky); final double lnky2 = lnky * lnky; final double ts15 = ts * 1.5; - final double lnsats15 = Math.log(sa * ts15); + final double lnsats15 = Math.log(sa); final double lnsats15_2 = lnsats15 * lnsats15; - double dispcm = Math.pow(Math.E, + double dispcm = Math.exp( -1.1 - 2.83 * lnky - 0.333 * lnky2 + 0.566 * lnky * lnsats15 + 3.04 * lnsats15 - 0.244 * lnsats15_2 + ts15 + 0.278 * (m - 7.0) ); double dispin = dispcm / 2.54; /* NORMSDIST from http://support.microsoft.com/?kbid=214111 */ double x = -1.76 - 3.22 * lnky - 0.484 * ts * lnky + 3.52 * lnsats15; double zx = (1. / Math.sqrt(2 * Math.PI)) * Math.exp(-(x * x) / 2.); double t = 1. / (1. + p * x); double t2 = t * t; double t3 = t2 * t; double t4 = t3 * t; double t5 = t4 * t; double px = 1 - zx * (b1 * t + b2 * t2 + b3 * t3 + b4 * t4 + b5 * t5); double prob_zero_disp = 1.0 - px; int incr = 0; ret[incr++] = fmtOne.format(dispcm); ret[incr++] = fmtOne.format(dispin); ret[incr++] = fmtTwo.format(prob_zero_disp); return ret; } }
false
true
public static String[] BrayAndTravasarou2007(final double ky, final double ts, final double sa, final double m) { String ret[] = new String[3]; final double p = 0.2316419; final double b1 = 0.319381530; final double b2 = -0.356563782; final double b3 = 1.781477937; final double b4 = -1.821255978; final double b5 = 1.330274429; final double lnky = Math.log(ky); final double lnky2 = lnky * lnky; final double ts15 = ts * 1.5; final double lnsats15 = Math.log(sa * ts15); final double lnsats15_2 = lnsats15 * lnsats15; double dispcm = Math.pow(Math.E, -1.1 - 2.83 * lnky - 0.333 * lnky2 + 0.566 * lnky * lnsats15 + 3.04 * lnsats15 - 0.244 * lnsats15_2 + ts15 + 0.278 * (m - 7.0) ); double dispin = dispcm / 2.54; /* NORMSDIST from http://support.microsoft.com/?kbid=214111 */ double x = -1.76 - 3.22 * lnky - 0.484 * ts * lnky + 3.52 * lnsats15; double zx = (1. / Math.sqrt(2 * Math.PI)) * Math.exp(-(x * x) / 2.); double t = 1. / (1. + p * x); double t2 = t * t; double t3 = t2 * t; double t4 = t3 * t; double t5 = t4 * t; double px = 1 - zx * (b1 * t + b2 * t2 + b3 * t3 + b4 * t4 + b5 * t5); double prob_zero_disp = 1.0 - px; int incr = 0; ret[incr++] = fmtOne.format(dispcm); ret[incr++] = fmtOne.format(dispin); ret[incr++] = fmtTwo.format(prob_zero_disp); return ret; }
public static String[] BrayAndTravasarou2007(final double ky, final double ts, final double sa, final double m) { String ret[] = new String[3]; final double p = 0.2316419; final double b1 = 0.319381530; final double b2 = -0.356563782; final double b3 = 1.781477937; final double b4 = -1.821255978; final double b5 = 1.330274429; final double lnky = Math.log(ky); final double lnky2 = lnky * lnky; final double ts15 = ts * 1.5; final double lnsats15 = Math.log(sa); final double lnsats15_2 = lnsats15 * lnsats15; double dispcm = Math.exp( -1.1 - 2.83 * lnky - 0.333 * lnky2 + 0.566 * lnky * lnsats15 + 3.04 * lnsats15 - 0.244 * lnsats15_2 + ts15 + 0.278 * (m - 7.0) ); double dispin = dispcm / 2.54; /* NORMSDIST from http://support.microsoft.com/?kbid=214111 */ double x = -1.76 - 3.22 * lnky - 0.484 * ts * lnky + 3.52 * lnsats15; double zx = (1. / Math.sqrt(2 * Math.PI)) * Math.exp(-(x * x) / 2.); double t = 1. / (1. + p * x); double t2 = t * t; double t3 = t2 * t; double t4 = t3 * t; double t5 = t4 * t; double px = 1 - zx * (b1 * t + b2 * t2 + b3 * t3 + b4 * t4 + b5 * t5); double prob_zero_disp = 1.0 - px; int incr = 0; ret[incr++] = fmtOne.format(dispcm); ret[incr++] = fmtOne.format(dispin); ret[incr++] = fmtTwo.format(prob_zero_disp); return ret; }
diff --git a/src/com/jgaap/classifiers/VectorOutputAnalysis.java b/src/com/jgaap/classifiers/VectorOutputAnalysis.java index 9631737..3a7e32f 100644 --- a/src/com/jgaap/classifiers/VectorOutputAnalysis.java +++ b/src/com/jgaap/classifiers/VectorOutputAnalysis.java @@ -1,81 +1,81 @@ package com.jgaap.classifiers; import com.jgaap.generics.*; import com.jgaap.jgaapConstants; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: jnoecker * Date: Feb 2, 2011 * Time: 11:53:53 AM * To change this template use File | Settings | File Templates. */ public class VectorOutputAnalysis extends AnalysisDriver { public String displayName() { return "Vector Output"; } public String tooltipText(){ return "Generates vectors from unknowns using a key (experimental)"; } public boolean showInGUI(){ return true; } public List<Pair<String, Double>> analyze(EventSet unknown, List<EventSet> known) { EventHistogram hist = new EventHistogram(); String keyFile = jgaapConstants.libDir() + "personae.key"; Scanner keyIn = null; try { keyIn = new Scanner(new File(keyFile)); } catch (FileNotFoundException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } FileOutputStream fsOut; PrintStream writer = null; try { String docPath = unknown.getDocumentName(); String[] docPathArray = docPath.split("/"); System.out.println(Arrays.toString(docPathArray)); String unknownFileName = docPathArray[docPathArray.length - 1]; fsOut = new FileOutputStream(jgaapConstants.tmpDir() + unknownFileName); writer = new PrintStream(fsOut); } catch (FileNotFoundException e) { e.printStackTrace(); - } + }; for(Event e : unknown) { hist.add(e); } - while(keyIn.hasNext()) { - String next = keyIn.next(); + while(keyIn.hasNextLine()) { + String next = keyIn.nextLine(); double freq = hist.getRelativeFrequency(new Event(next)); if(freq > 0) { writer.println(freq); } else { writer.println("0"); } } writer.close(); List<Pair<String,Double>> results = new ArrayList<Pair<String,Double>>(); results.add(new Pair<String, Double>("No analysis performed.\n", 0.0)); return results; } }
false
true
public List<Pair<String, Double>> analyze(EventSet unknown, List<EventSet> known) { EventHistogram hist = new EventHistogram(); String keyFile = jgaapConstants.libDir() + "personae.key"; Scanner keyIn = null; try { keyIn = new Scanner(new File(keyFile)); } catch (FileNotFoundException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } FileOutputStream fsOut; PrintStream writer = null; try { String docPath = unknown.getDocumentName(); String[] docPathArray = docPath.split("/"); System.out.println(Arrays.toString(docPathArray)); String unknownFileName = docPathArray[docPathArray.length - 1]; fsOut = new FileOutputStream(jgaapConstants.tmpDir() + unknownFileName); writer = new PrintStream(fsOut); } catch (FileNotFoundException e) { e.printStackTrace(); } for(Event e : unknown) { hist.add(e); } while(keyIn.hasNext()) { String next = keyIn.next(); double freq = hist.getRelativeFrequency(new Event(next)); if(freq > 0) { writer.println(freq); } else { writer.println("0"); } } writer.close(); List<Pair<String,Double>> results = new ArrayList<Pair<String,Double>>(); results.add(new Pair<String, Double>("No analysis performed.\n", 0.0)); return results; }
public List<Pair<String, Double>> analyze(EventSet unknown, List<EventSet> known) { EventHistogram hist = new EventHistogram(); String keyFile = jgaapConstants.libDir() + "personae.key"; Scanner keyIn = null; try { keyIn = new Scanner(new File(keyFile)); } catch (FileNotFoundException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } FileOutputStream fsOut; PrintStream writer = null; try { String docPath = unknown.getDocumentName(); String[] docPathArray = docPath.split("/"); System.out.println(Arrays.toString(docPathArray)); String unknownFileName = docPathArray[docPathArray.length - 1]; fsOut = new FileOutputStream(jgaapConstants.tmpDir() + unknownFileName); writer = new PrintStream(fsOut); } catch (FileNotFoundException e) { e.printStackTrace(); }; for(Event e : unknown) { hist.add(e); } while(keyIn.hasNextLine()) { String next = keyIn.nextLine(); double freq = hist.getRelativeFrequency(new Event(next)); if(freq > 0) { writer.println(freq); } else { writer.println("0"); } } writer.close(); List<Pair<String,Double>> results = new ArrayList<Pair<String,Double>>(); results.add(new Pair<String, Double>("No analysis performed.\n", 0.0)); return results; }
diff --git a/src/markehme/factionsplus/FactionsPlus.java b/src/markehme/factionsplus/FactionsPlus.java index d8e64dd..6ab2ded 100644 --- a/src/markehme/factionsplus/FactionsPlus.java +++ b/src/markehme/factionsplus/FactionsPlus.java @@ -1,463 +1,463 @@ package markehme.factionsplus; import java.io.File; import java.io.IOException; import java.util.logging.Logger; import markehme.factionsplus.extras.DCListener; import markehme.factionsplus.extras.LWCFunctions; import markehme.factionsplus.extras.LWCListener; import markehme.factionsplus.extras.MDListener; import markehme.factionsplus.extras.Metrics; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.permission.Permission; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import com.griefcraft.lwc.LWCPlugin; import com.massivecraft.factions.FPlayers; import com.massivecraft.factions.Faction; import com.massivecraft.factions.Factions; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; /* - fixed onEntityDeath TODO: LIST OF STUFF TO DO - made maxWarps configuration option work */ public class FactionsPlus extends JavaPlugin { public static FactionsPlus plugin; public static Logger log = Logger.getLogger("Minecraft"); Factions factions; FPlayers fplayers; Faction faction; public static Permission permission = null; public static Economy economy = null; public static File templatesFile = new File("plugins" + File.separator + "FactionsPlus" + File.separator + "templates.yml"); public static File configFile = new File("plugins" + File.separator + "FactionsPlus" + File.separator + "config.yml"); public static FileConfiguration wconfig; public static FileConfiguration config; public static FileConfiguration templates; public static boolean isMobDisguiseEnabled = false; public static boolean isDisguiseCraftEnabled = false; public static boolean isWorldEditEnabled = false; public static boolean isWorldGuardEnabled = false; public static boolean isLWCEnabled = false; public static boolean useLWCIntegrationFix = false; public final FactionsPlusListener FPListener = new FactionsPlusListener(); public final DCListener DCListener = new DCListener(); public final MDListener MDListener = new MDListener(); public final LWCListener LWCListener = new LWCListener(); public static WorldEditPlugin worldEditPlugin = null; public static WorldGuardPlugin worldGuardPlugin = null; public static String version; public static String FactionsVersion; public static Boolean isOnePointSix; public void onEnable() { PluginManager pm = this.getServer().getPluginManager(); pm.registerEvents(this.FPListener, this); FactionsPlusJail.server = getServer(); FactionsVersion = (this.getServer().getPluginManager().getPlugin("Factions").getDescription().getVersion()); if(FactionsVersion.startsWith("1.6")) { isOnePointSix = true; } else { isOnePointSix = false; } log.info("[FactionsPlus] Factions version " + FactionsVersion + " - " + isOnePointSix.toString()); try { if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator).exists()) { log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator); new File("plugins" + File.separator + "FactionsPlus" + File.separator).mkdir(); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt").exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt").createNewFile(); log.info("[FactionsPlus] Created file: plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt"); } } catch (Exception e) { e.printStackTrace(); } if(!FactionsPlus.configFile.exists()) { try { FactionsPlus.configFile.createNewFile(); } catch (Exception e) { e.printStackTrace(); } } try { wconfig = YamlConfiguration.loadConfiguration(configFile); configFile.delete(); configFile.createNewFile(); config = YamlConfiguration.loadConfiguration(configFile); if(wconfig.isSet("disableUpdateCheck")) { config.set("disableUpdateCheck", wconfig.getBoolean("disableUpdateCheck")); } else config.set("disableUpdateCheck", false); if(wconfig.isSet("unDisguiseIfInOwnTerritory")) { config.set("unDisguiseIfInOwnTerritory", wconfig.getBoolean("unDisguiseIfInOwnTerritory")); } else config.set("unDisguiseIfInOwnTerritory", Boolean.valueOf(false)); if(wconfig.isSet("unDisguiseIfInEnemyTerritory")) { config.set("unDisguiseIfInEnemyTerritory", wconfig.getBoolean("unDisguiseIfInEnemyTerritory")); } else config.set("unDisguiseIfInEnemyTerritory", Boolean.valueOf(false)); if(wconfig.isSet("leadersCanSetWarps")) { config.set("leadersCanSetWarps", wconfig.getBoolean("leadersCanSetWarps")); } else config.set("leadersCanSetWarps", true); if(wconfig.isSet("officersCanSetWarps")) { config.set("officersCanSetWarps", wconfig.getBoolean("officersCanSetWarps")); } else config.set("officersCanSetWarps", true); if(wconfig.isSet("membersCanSetWarps")) { config.set("membersCanSetWarps", wconfig.getBoolean("membersCanSetWarps")); } else config.set("membersCanSetWarps", false); if(wconfig.isSet("warpSetting")) { config.set("warpSetting", wconfig.getInt("warpSetting")); } else config.set("warpSetting", Integer.valueOf(1)); if(wconfig.isSet("maxWarps")) { config.set("maxWarps", wconfig.getInt("maxWarps")); } else config.set("maxWarps", Integer.valueOf(5)); if(wconfig.isSet("mustBeInOwnTerritoryToCreate")) { config.set("mustBeInOwnTerritoryToCreate", wconfig.getBoolean("mustBeInOwnTerritoryToCreate")); } else config.set("mustBeInOwnTerritoryToCreate", true); if(wconfig.isSet("warpTeleportAllowedFromEnemyTerritory")){ - config.set("homesTeleportAllowedFromEnemyTerritory", wconfig.getBoolean("homesTeleportAllowedFromEnemyTerritory")); - } else config.set("homesTeleportAllowedFromEnemyTerritory", true); + config.set("warpTeleportAllowedFromEnemyTerritory", wconfig.getBoolean("warpTeleportAllowedFromEnemyTerritory")); + } else config.set("warpTeleportAllowedFromEnemyTerritory", true); if(wconfig.isSet("warpTeleportAllowedFromDifferentWorld")){ config.set("warpTeleportAllowedFromDifferentWorld", wconfig.getBoolean("warpTeleportAllowedFromDifferentWorld")); } else config.set("warpTeleportAllowedFromDifferentWorld", true); if(wconfig.isSet("warpTeleportAllowedEnemyDistance")) { config.set("warpTeleportAllowedEnemyDistance", wconfig.getInt("warpTeleportAllowedEnemyDistance")); } else config.set("warpTeleportAllowedEnemyDistance", Integer.valueOf(35)); if(wconfig.isSet("warpTeleportIgnoreEnemiesIfInOwnTerritory")){ config.set("warpTeleportIgnoreEnemiesIfInOwnTerritory", wconfig.getBoolean("warpTeleportIgnoreEnemiesIfInOwnTerritory")); } else config.set("warpTeleportIgnoreEnemiesIfInOwnTerritory", true); if(wconfig.isSet("smokeEffectOnWarp")) { config.set("smokeEffectOnWarp", wconfig.getBoolean("smokeEffectOnWarp")); } else config.set("smokeEffectOnWarp", true); if(wconfig.isSet("powerBoostIfPeaceful")) { config.set("powerBoostIfPeaceful", wconfig.getInt("powerBoostIfPeaceful")); } else config.set("powerBoostIfPeaceful", Integer.valueOf(0)); if(wconfig.isSet("leadersCanSetJails")) { config.set("leadersCanSetJails", wconfig.getBoolean("leadersCanSetJails")); } else config.set("leadersCanSetJails", true); if(wconfig.isSet("officersCanSetJails")) { config.set("officersCanSetJails", wconfig.getBoolean("officersCanSetJails")); } else config.set("officersCanSetJails", true); if(wconfig.isSet("leadersCanSetRules")) { config.set("leadersCanSetRules", wconfig.getBoolean("leadersCanSetRules")); } else config.set("leadersCanSetRules", true); if(wconfig.isSet("officersCanSetRules")) { config.set("officersCanSetRules", wconfig.getBoolean("officersCanSetRules")); } else config.set("officersCanSetRules", true); if(wconfig.isSet("maxRulesPerFaction")) { config.set("maxRulesPerFaction", wconfig.getInt("maxRulesPerFaction")); } else config.set("maxRulesPerFaction", Integer.valueOf(12)); if(wconfig.isSet("membersCanSetJails")) { config.set("membersCanSetJails", wconfig.getBoolean("membersCanSetJails")); } else config.set("membersCanSetJails", false); if(wconfig.isSet("leadersCanJail")) { config.set("leadersCanJail", wconfig.getBoolean("leadersCanJail")); } else config.set("leadersCanJail", true); if(wconfig.isSet("officersCanJail")) { config.set("officersCanJail", wconfig.getBoolean("officersCanJail")); } else config.set("officersCanJail", true); if(wconfig.isSet("leadersCanAnnounce")) { config.set("leadersCanAnnounce", wconfig.getBoolean("leadersCanAnnounce")); } else config.set("leadersCanAnnounce", true); if(wconfig.isSet("officersCanAnnounce")) { config.set("officersCanAnnounce", wconfig.getBoolean("officersCanAnnounce")); } else config.set("officersCanAnnounce", true); if(wconfig.isSet("showLastAnnounceOnLogin")) { config.set("showLastAnnounceOnLogin", wconfig.getBoolean("showLastAnnounceOnLogin")); } else config.set("showLastAnnounceOnLogin", true); if(wconfig.isSet("showLastAnnounceOnLandEnter")) { config.set("showLastAnnounceOnLandEnter", wconfig.getBoolean("showLastAnnounceOnLandEnter")); } else config.set("showLastAnnounceOnLandEnter", true); if(wconfig.isSet("leadersCanFactionBan")) { config.set("leadersCanFactionBan", wconfig.getBoolean("leadersCanFactionBan")); } else config.set("leadersCanFactionBan", true); if(wconfig.isSet("officersCanFactionBan")) { config.set("officersCanFactionBan", wconfig.getBoolean("officersCanFactionBan")); } else config.set("officersCanFactionBan", true); if(wconfig.isSet("leaderCanNotBeBanned")) { config.set("leaderCanNotBeBanned", wconfig.getBoolean("leaderCanNotBeBanned")); } else config.set("leaderCanNotBeBanned", true); if(wconfig.isSet("leadersCanToggleState")) { config.set("leadersCanToggleState", wconfig.getBoolean("leadersCanToggleState")); } else config.set("leadersCanToggleState", false); if(wconfig.isSet("officersCanToggleState")) { config.set("officersCanToggleState", wconfig.getBoolean("officersCanToggleState")); } else config.set("officersCanToggleState", false); if(wconfig.isSet("membersCanToggleState")) { config.set("membersCanToggleState", wconfig.getBoolean("membersCanToggleState")); } else config.set("membersCanToggleState", false); if(wconfig.isSet("extraPowerLossIfDeathByOther")) { config.set("extraPowerLossIfDeathByOther", wconfig.getDouble("extraPowerLossIfDeathByOther")); } else config.set("extraPowerLossIfDeathByOther", Double.valueOf(0)); if(wconfig.isSet("extraPowerWhenKillPlayer")) { config.set("extraPowerWhenKillPlayer", wconfig.getDouble("extraPowerWhenKillPlayer")); } else config.set("extraPowerWhenKillPlayer", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathBySuicide")) { config.set("extraPowerLossIfDeathBySuicide", wconfig.getDouble("extraPowerLossIfDeathBySuicide")); } else config.set("extraPowerLossIfDeathBySuicide", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByPVP")) { config.set("extraPowerLossIfDeathByPVP", wconfig.getDouble("extraPowerLossIfDeathByPVP")); } else config.set("extraPowerLossIfDeathByPVP", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByMob")) { config.set("extraPowerLossIfDeathByMob", wconfig.getDouble("extraPowerLossIfDeathByMob")); } else config.set("extraPowerLossIfDeathByMob", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByCactus")) { config.set("extraPowerLossIfDeathByCactus", wconfig.getDouble("extraPowerLossIfDeathByCactus")); } else config.set("extraPowerLossIfDeathByCactus", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByTNT")) { config.set("extraPowerLossIfDeathByTNT", wconfig.getDouble("extraPowerLossIfDeathByTNT")); } else config.set("extraPowerLossIfDeathByTNT", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByFire")) { config.set("extraPowerLossIfDeathByFire", wconfig.getDouble("extraPowerLossIfDeathByFire")); } else config.set("extraPowerLossIfDeathByFire", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByPotion")) { config.set("extraPowerLossIfDeathByPotion", wconfig.getDouble("extraPowerLossIfDeathByPotion")); } else config.set("extraPowerLossIfDeathByPotion", Double.valueOf(0)); if(wconfig.isSet("enablePermissionGroups")) { config.set("enablePermissionGroups", wconfig.getBoolean("enablePermissionGroups")); } else config.set("enablePermissionGroups", Boolean.valueOf(false)); if(wconfig.isSet("economy_enable")) { config.set("economy_enable", wconfig.getBoolean("economy_enable")); } else config.set("economy_enable", Boolean.valueOf(false)); if(wconfig.isSet("economy_costToWarp")) { config.set("economy_costToWarp", wconfig.getInt("economy_costToWarp")); } else config.set("economy_costToWarp", Integer.valueOf(0)); if(wconfig.isSet("economy_costToCreateWarp")) { config.set("economy_costToCreateWarp", wconfig.getInt("economy_costToCreateWarp")); } else config.set("economy_costToCreateWarp", Integer.valueOf(0)); if(wconfig.isSet("economy_costToDeleteWarp")) { config.set("economy_costToDeleteWarp", wconfig.getInt("economy_costToDeleteWarp")); } else config.set("economy_costToDeleteWarp", Integer.valueOf(0)); if(wconfig.isSet("economy_costToAnnounce")) { config.set("economy_costToAnnounce", wconfig.getInt("economy_costToAnnounce")); } else config.set("economy_costToAnnounce", Integer.valueOf(0)); if(wconfig.isSet("economy_costToJail")) { config.set("economy_costToJail", wconfig.getInt("economy_costToJail")); } else config.set("economy_costToJail", Integer.valueOf(0)); if(wconfig.isSet("economy_costToSetJail")) { config.set("economy_costToSetJail", wconfig.getInt("economy_costToSetJail")); } else config.set("economy_costToSetJail", Integer.valueOf(0)); if(wconfig.isSet("economy_costToUnJail")) { config.set("economy_costToUnJail", wconfig.getInt("economy_costToUnJail")); } else config.set("economy_costToUnJail", Integer.valueOf(0)); if(wconfig.isSet("economy_costToToggleUpPeaceful")) { config.set("economy_costToToggleUpPeaceful", wconfig.getInt("economy_costToToggleUpPeaceful")); } else config.set("economy_costToToggleUpPeaceful", Integer.valueOf(0)); if(wconfig.isSet("economy_costToToggleDownPeaceful")) { config.set("economy_costToToggleDownPeaceful", wconfig.getInt("economy_costToToggleDownPeaceful")); } else config.set("economy_costToToggleDownPeaceful", Integer.valueOf(0)); if(wconfig.isSet("useLWCIntegrationFix")) { config.set("useLWCIntegrationFix", wconfig.getBoolean("useLWCIntegrationFix")); } else config.set("useLWCIntegrationFix", false); config.set("DoNotChangeMe", Integer.valueOf(8)); config.save(configFile); saveConfig(); } catch(Exception e) { e.printStackTrace(); log.info("[FactionsPlus] An error occured while managing the configuration file (-18)"); getPluginLoader().disablePlugin(this); } if (!templatesFile.exists()) { FactionsPlusTemplates.createTemplatesFile(); } templates = YamlConfiguration.loadConfiguration(templatesFile); config = YamlConfiguration.loadConfiguration(configFile); FactionsPlusCommandManager.setup(); FactionsPlusHelpModifier.modify(); RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); if (permissionProvider != null) { permission = permissionProvider.getProvider(); } if(config.getBoolean("economy_enable")) { RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); } } if(getServer().getPluginManager().isPluginEnabled("DisguiseCraft")) { pm.registerEvents(this.DCListener, this); log.info("[FactionsPlus] Hooked into DisguiseCraft!"); isDisguiseCraftEnabled = true; } if(getServer().getPluginManager().isPluginEnabled("MobDisguise")) { pm.registerEvents(this.MDListener, this); log.info("[FactionsPlus] Hooked into MobDisguise!"); isMobDisguiseEnabled = true; } if(getServer().getPluginManager().isPluginEnabled("WorldEdit")) { worldEditPlugin = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit"); log.info("[FactionsPlus] Hooked into WorldEdit!"); isWorldEditEnabled = true; } if(getServer().getPluginManager().isPluginEnabled("WorldGuard")) { worldGuardPlugin = (WorldGuardPlugin) getServer().getPluginManager().getPlugin("WorldGuard"); log.info("[FactionsPlus] Hooked into WorldGuard!"); isWorldGuardEnabled = true; } if(config.getBoolean("useLWCIntegrationFix") == true) { if(getServer().getPluginManager().isPluginEnabled("LWC")) { pm.registerEvents(this.LWCListener, this); log.info("[FactionsPlus] Hooked into LWC!"); LWCFunctions.integrateLWC((LWCPlugin)getServer().getPluginManager().getPlugin("LWC")); isLWCEnabled = true; } else { log.info("[FactionsPlus] No LWC Found but Integration Option Is Enabled!"); } } FactionsPlus.config = YamlConfiguration.loadConfiguration(FactionsPlus.configFile); version = getDescription().getVersion(); FactionsPlusUpdate.checkUpdates(); log.info("[FactionsPlus] Ready."); try { Metrics metrics = new Metrics(this); metrics.start(); } catch (IOException e) { log.info("[FactionsPlus] Waah! Couldn't metrics-up! :'("); } } public void onDisable() { log.info("[FactionsPlus] Disabled."); } }
true
true
public void onEnable() { PluginManager pm = this.getServer().getPluginManager(); pm.registerEvents(this.FPListener, this); FactionsPlusJail.server = getServer(); FactionsVersion = (this.getServer().getPluginManager().getPlugin("Factions").getDescription().getVersion()); if(FactionsVersion.startsWith("1.6")) { isOnePointSix = true; } else { isOnePointSix = false; } log.info("[FactionsPlus] Factions version " + FactionsVersion + " - " + isOnePointSix.toString()); try { if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator).exists()) { log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator); new File("plugins" + File.separator + "FactionsPlus" + File.separator).mkdir(); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt").exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt").createNewFile(); log.info("[FactionsPlus] Created file: plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt"); } } catch (Exception e) { e.printStackTrace(); } if(!FactionsPlus.configFile.exists()) { try { FactionsPlus.configFile.createNewFile(); } catch (Exception e) { e.printStackTrace(); } } try { wconfig = YamlConfiguration.loadConfiguration(configFile); configFile.delete(); configFile.createNewFile(); config = YamlConfiguration.loadConfiguration(configFile); if(wconfig.isSet("disableUpdateCheck")) { config.set("disableUpdateCheck", wconfig.getBoolean("disableUpdateCheck")); } else config.set("disableUpdateCheck", false); if(wconfig.isSet("unDisguiseIfInOwnTerritory")) { config.set("unDisguiseIfInOwnTerritory", wconfig.getBoolean("unDisguiseIfInOwnTerritory")); } else config.set("unDisguiseIfInOwnTerritory", Boolean.valueOf(false)); if(wconfig.isSet("unDisguiseIfInEnemyTerritory")) { config.set("unDisguiseIfInEnemyTerritory", wconfig.getBoolean("unDisguiseIfInEnemyTerritory")); } else config.set("unDisguiseIfInEnemyTerritory", Boolean.valueOf(false)); if(wconfig.isSet("leadersCanSetWarps")) { config.set("leadersCanSetWarps", wconfig.getBoolean("leadersCanSetWarps")); } else config.set("leadersCanSetWarps", true); if(wconfig.isSet("officersCanSetWarps")) { config.set("officersCanSetWarps", wconfig.getBoolean("officersCanSetWarps")); } else config.set("officersCanSetWarps", true); if(wconfig.isSet("membersCanSetWarps")) { config.set("membersCanSetWarps", wconfig.getBoolean("membersCanSetWarps")); } else config.set("membersCanSetWarps", false); if(wconfig.isSet("warpSetting")) { config.set("warpSetting", wconfig.getInt("warpSetting")); } else config.set("warpSetting", Integer.valueOf(1)); if(wconfig.isSet("maxWarps")) { config.set("maxWarps", wconfig.getInt("maxWarps")); } else config.set("maxWarps", Integer.valueOf(5)); if(wconfig.isSet("mustBeInOwnTerritoryToCreate")) { config.set("mustBeInOwnTerritoryToCreate", wconfig.getBoolean("mustBeInOwnTerritoryToCreate")); } else config.set("mustBeInOwnTerritoryToCreate", true); if(wconfig.isSet("warpTeleportAllowedFromEnemyTerritory")){ config.set("homesTeleportAllowedFromEnemyTerritory", wconfig.getBoolean("homesTeleportAllowedFromEnemyTerritory")); } else config.set("homesTeleportAllowedFromEnemyTerritory", true); if(wconfig.isSet("warpTeleportAllowedFromDifferentWorld")){ config.set("warpTeleportAllowedFromDifferentWorld", wconfig.getBoolean("warpTeleportAllowedFromDifferentWorld")); } else config.set("warpTeleportAllowedFromDifferentWorld", true); if(wconfig.isSet("warpTeleportAllowedEnemyDistance")) { config.set("warpTeleportAllowedEnemyDistance", wconfig.getInt("warpTeleportAllowedEnemyDistance")); } else config.set("warpTeleportAllowedEnemyDistance", Integer.valueOf(35)); if(wconfig.isSet("warpTeleportIgnoreEnemiesIfInOwnTerritory")){ config.set("warpTeleportIgnoreEnemiesIfInOwnTerritory", wconfig.getBoolean("warpTeleportIgnoreEnemiesIfInOwnTerritory")); } else config.set("warpTeleportIgnoreEnemiesIfInOwnTerritory", true); if(wconfig.isSet("smokeEffectOnWarp")) { config.set("smokeEffectOnWarp", wconfig.getBoolean("smokeEffectOnWarp")); } else config.set("smokeEffectOnWarp", true); if(wconfig.isSet("powerBoostIfPeaceful")) { config.set("powerBoostIfPeaceful", wconfig.getInt("powerBoostIfPeaceful")); } else config.set("powerBoostIfPeaceful", Integer.valueOf(0)); if(wconfig.isSet("leadersCanSetJails")) { config.set("leadersCanSetJails", wconfig.getBoolean("leadersCanSetJails")); } else config.set("leadersCanSetJails", true); if(wconfig.isSet("officersCanSetJails")) { config.set("officersCanSetJails", wconfig.getBoolean("officersCanSetJails")); } else config.set("officersCanSetJails", true); if(wconfig.isSet("leadersCanSetRules")) { config.set("leadersCanSetRules", wconfig.getBoolean("leadersCanSetRules")); } else config.set("leadersCanSetRules", true); if(wconfig.isSet("officersCanSetRules")) { config.set("officersCanSetRules", wconfig.getBoolean("officersCanSetRules")); } else config.set("officersCanSetRules", true); if(wconfig.isSet("maxRulesPerFaction")) { config.set("maxRulesPerFaction", wconfig.getInt("maxRulesPerFaction")); } else config.set("maxRulesPerFaction", Integer.valueOf(12)); if(wconfig.isSet("membersCanSetJails")) { config.set("membersCanSetJails", wconfig.getBoolean("membersCanSetJails")); } else config.set("membersCanSetJails", false); if(wconfig.isSet("leadersCanJail")) { config.set("leadersCanJail", wconfig.getBoolean("leadersCanJail")); } else config.set("leadersCanJail", true); if(wconfig.isSet("officersCanJail")) { config.set("officersCanJail", wconfig.getBoolean("officersCanJail")); } else config.set("officersCanJail", true); if(wconfig.isSet("leadersCanAnnounce")) { config.set("leadersCanAnnounce", wconfig.getBoolean("leadersCanAnnounce")); } else config.set("leadersCanAnnounce", true); if(wconfig.isSet("officersCanAnnounce")) { config.set("officersCanAnnounce", wconfig.getBoolean("officersCanAnnounce")); } else config.set("officersCanAnnounce", true); if(wconfig.isSet("showLastAnnounceOnLogin")) { config.set("showLastAnnounceOnLogin", wconfig.getBoolean("showLastAnnounceOnLogin")); } else config.set("showLastAnnounceOnLogin", true); if(wconfig.isSet("showLastAnnounceOnLandEnter")) { config.set("showLastAnnounceOnLandEnter", wconfig.getBoolean("showLastAnnounceOnLandEnter")); } else config.set("showLastAnnounceOnLandEnter", true); if(wconfig.isSet("leadersCanFactionBan")) { config.set("leadersCanFactionBan", wconfig.getBoolean("leadersCanFactionBan")); } else config.set("leadersCanFactionBan", true); if(wconfig.isSet("officersCanFactionBan")) { config.set("officersCanFactionBan", wconfig.getBoolean("officersCanFactionBan")); } else config.set("officersCanFactionBan", true); if(wconfig.isSet("leaderCanNotBeBanned")) { config.set("leaderCanNotBeBanned", wconfig.getBoolean("leaderCanNotBeBanned")); } else config.set("leaderCanNotBeBanned", true); if(wconfig.isSet("leadersCanToggleState")) { config.set("leadersCanToggleState", wconfig.getBoolean("leadersCanToggleState")); } else config.set("leadersCanToggleState", false); if(wconfig.isSet("officersCanToggleState")) { config.set("officersCanToggleState", wconfig.getBoolean("officersCanToggleState")); } else config.set("officersCanToggleState", false); if(wconfig.isSet("membersCanToggleState")) { config.set("membersCanToggleState", wconfig.getBoolean("membersCanToggleState")); } else config.set("membersCanToggleState", false); if(wconfig.isSet("extraPowerLossIfDeathByOther")) { config.set("extraPowerLossIfDeathByOther", wconfig.getDouble("extraPowerLossIfDeathByOther")); } else config.set("extraPowerLossIfDeathByOther", Double.valueOf(0)); if(wconfig.isSet("extraPowerWhenKillPlayer")) { config.set("extraPowerWhenKillPlayer", wconfig.getDouble("extraPowerWhenKillPlayer")); } else config.set("extraPowerWhenKillPlayer", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathBySuicide")) { config.set("extraPowerLossIfDeathBySuicide", wconfig.getDouble("extraPowerLossIfDeathBySuicide")); } else config.set("extraPowerLossIfDeathBySuicide", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByPVP")) { config.set("extraPowerLossIfDeathByPVP", wconfig.getDouble("extraPowerLossIfDeathByPVP")); } else config.set("extraPowerLossIfDeathByPVP", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByMob")) { config.set("extraPowerLossIfDeathByMob", wconfig.getDouble("extraPowerLossIfDeathByMob")); } else config.set("extraPowerLossIfDeathByMob", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByCactus")) { config.set("extraPowerLossIfDeathByCactus", wconfig.getDouble("extraPowerLossIfDeathByCactus")); } else config.set("extraPowerLossIfDeathByCactus", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByTNT")) { config.set("extraPowerLossIfDeathByTNT", wconfig.getDouble("extraPowerLossIfDeathByTNT")); } else config.set("extraPowerLossIfDeathByTNT", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByFire")) { config.set("extraPowerLossIfDeathByFire", wconfig.getDouble("extraPowerLossIfDeathByFire")); } else config.set("extraPowerLossIfDeathByFire", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByPotion")) { config.set("extraPowerLossIfDeathByPotion", wconfig.getDouble("extraPowerLossIfDeathByPotion")); } else config.set("extraPowerLossIfDeathByPotion", Double.valueOf(0)); if(wconfig.isSet("enablePermissionGroups")) { config.set("enablePermissionGroups", wconfig.getBoolean("enablePermissionGroups")); } else config.set("enablePermissionGroups", Boolean.valueOf(false)); if(wconfig.isSet("economy_enable")) { config.set("economy_enable", wconfig.getBoolean("economy_enable")); } else config.set("economy_enable", Boolean.valueOf(false)); if(wconfig.isSet("economy_costToWarp")) { config.set("economy_costToWarp", wconfig.getInt("economy_costToWarp")); } else config.set("economy_costToWarp", Integer.valueOf(0)); if(wconfig.isSet("economy_costToCreateWarp")) { config.set("economy_costToCreateWarp", wconfig.getInt("economy_costToCreateWarp")); } else config.set("economy_costToCreateWarp", Integer.valueOf(0)); if(wconfig.isSet("economy_costToDeleteWarp")) { config.set("economy_costToDeleteWarp", wconfig.getInt("economy_costToDeleteWarp")); } else config.set("economy_costToDeleteWarp", Integer.valueOf(0)); if(wconfig.isSet("economy_costToAnnounce")) { config.set("economy_costToAnnounce", wconfig.getInt("economy_costToAnnounce")); } else config.set("economy_costToAnnounce", Integer.valueOf(0)); if(wconfig.isSet("economy_costToJail")) { config.set("economy_costToJail", wconfig.getInt("economy_costToJail")); } else config.set("economy_costToJail", Integer.valueOf(0)); if(wconfig.isSet("economy_costToSetJail")) { config.set("economy_costToSetJail", wconfig.getInt("economy_costToSetJail")); } else config.set("economy_costToSetJail", Integer.valueOf(0)); if(wconfig.isSet("economy_costToUnJail")) { config.set("economy_costToUnJail", wconfig.getInt("economy_costToUnJail")); } else config.set("economy_costToUnJail", Integer.valueOf(0)); if(wconfig.isSet("economy_costToToggleUpPeaceful")) { config.set("economy_costToToggleUpPeaceful", wconfig.getInt("economy_costToToggleUpPeaceful")); } else config.set("economy_costToToggleUpPeaceful", Integer.valueOf(0)); if(wconfig.isSet("economy_costToToggleDownPeaceful")) { config.set("economy_costToToggleDownPeaceful", wconfig.getInt("economy_costToToggleDownPeaceful")); } else config.set("economy_costToToggleDownPeaceful", Integer.valueOf(0)); if(wconfig.isSet("useLWCIntegrationFix")) { config.set("useLWCIntegrationFix", wconfig.getBoolean("useLWCIntegrationFix")); } else config.set("useLWCIntegrationFix", false); config.set("DoNotChangeMe", Integer.valueOf(8)); config.save(configFile); saveConfig(); } catch(Exception e) { e.printStackTrace(); log.info("[FactionsPlus] An error occured while managing the configuration file (-18)"); getPluginLoader().disablePlugin(this); } if (!templatesFile.exists()) { FactionsPlusTemplates.createTemplatesFile(); } templates = YamlConfiguration.loadConfiguration(templatesFile); config = YamlConfiguration.loadConfiguration(configFile); FactionsPlusCommandManager.setup(); FactionsPlusHelpModifier.modify(); RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); if (permissionProvider != null) { permission = permissionProvider.getProvider(); } if(config.getBoolean("economy_enable")) { RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); } } if(getServer().getPluginManager().isPluginEnabled("DisguiseCraft")) { pm.registerEvents(this.DCListener, this); log.info("[FactionsPlus] Hooked into DisguiseCraft!"); isDisguiseCraftEnabled = true; } if(getServer().getPluginManager().isPluginEnabled("MobDisguise")) { pm.registerEvents(this.MDListener, this); log.info("[FactionsPlus] Hooked into MobDisguise!"); isMobDisguiseEnabled = true; } if(getServer().getPluginManager().isPluginEnabled("WorldEdit")) { worldEditPlugin = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit"); log.info("[FactionsPlus] Hooked into WorldEdit!"); isWorldEditEnabled = true; } if(getServer().getPluginManager().isPluginEnabled("WorldGuard")) { worldGuardPlugin = (WorldGuardPlugin) getServer().getPluginManager().getPlugin("WorldGuard"); log.info("[FactionsPlus] Hooked into WorldGuard!"); isWorldGuardEnabled = true; } if(config.getBoolean("useLWCIntegrationFix") == true) { if(getServer().getPluginManager().isPluginEnabled("LWC")) { pm.registerEvents(this.LWCListener, this); log.info("[FactionsPlus] Hooked into LWC!"); LWCFunctions.integrateLWC((LWCPlugin)getServer().getPluginManager().getPlugin("LWC")); isLWCEnabled = true; } else { log.info("[FactionsPlus] No LWC Found but Integration Option Is Enabled!"); } } FactionsPlus.config = YamlConfiguration.loadConfiguration(FactionsPlus.configFile); version = getDescription().getVersion(); FactionsPlusUpdate.checkUpdates(); log.info("[FactionsPlus] Ready."); try { Metrics metrics = new Metrics(this); metrics.start(); } catch (IOException e) { log.info("[FactionsPlus] Waah! Couldn't metrics-up! :'("); } }
public void onEnable() { PluginManager pm = this.getServer().getPluginManager(); pm.registerEvents(this.FPListener, this); FactionsPlusJail.server = getServer(); FactionsVersion = (this.getServer().getPluginManager().getPlugin("Factions").getDescription().getVersion()); if(FactionsVersion.startsWith("1.6")) { isOnePointSix = true; } else { isOnePointSix = false; } log.info("[FactionsPlus] Factions version " + FactionsVersion + " - " + isOnePointSix.toString()); try { if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator).exists()) { log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator); new File("plugins" + File.separator + "FactionsPlus" + File.separator).mkdir(); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "warps" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "jails" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "announcements" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "frules" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator).exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator).mkdir(); log.info("[FactionsPlus] Added directory: plugins" + File.separator + "FactionsPlus" + File.separator + "fbans" + File.separator); } if(!new File("plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt").exists()) { new File("plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt").createNewFile(); log.info("[FactionsPlus] Created file: plugins" + File.separator + "FactionsPlus" + File.separator + "disabled_in_warzone.txt"); } } catch (Exception e) { e.printStackTrace(); } if(!FactionsPlus.configFile.exists()) { try { FactionsPlus.configFile.createNewFile(); } catch (Exception e) { e.printStackTrace(); } } try { wconfig = YamlConfiguration.loadConfiguration(configFile); configFile.delete(); configFile.createNewFile(); config = YamlConfiguration.loadConfiguration(configFile); if(wconfig.isSet("disableUpdateCheck")) { config.set("disableUpdateCheck", wconfig.getBoolean("disableUpdateCheck")); } else config.set("disableUpdateCheck", false); if(wconfig.isSet("unDisguiseIfInOwnTerritory")) { config.set("unDisguiseIfInOwnTerritory", wconfig.getBoolean("unDisguiseIfInOwnTerritory")); } else config.set("unDisguiseIfInOwnTerritory", Boolean.valueOf(false)); if(wconfig.isSet("unDisguiseIfInEnemyTerritory")) { config.set("unDisguiseIfInEnemyTerritory", wconfig.getBoolean("unDisguiseIfInEnemyTerritory")); } else config.set("unDisguiseIfInEnemyTerritory", Boolean.valueOf(false)); if(wconfig.isSet("leadersCanSetWarps")) { config.set("leadersCanSetWarps", wconfig.getBoolean("leadersCanSetWarps")); } else config.set("leadersCanSetWarps", true); if(wconfig.isSet("officersCanSetWarps")) { config.set("officersCanSetWarps", wconfig.getBoolean("officersCanSetWarps")); } else config.set("officersCanSetWarps", true); if(wconfig.isSet("membersCanSetWarps")) { config.set("membersCanSetWarps", wconfig.getBoolean("membersCanSetWarps")); } else config.set("membersCanSetWarps", false); if(wconfig.isSet("warpSetting")) { config.set("warpSetting", wconfig.getInt("warpSetting")); } else config.set("warpSetting", Integer.valueOf(1)); if(wconfig.isSet("maxWarps")) { config.set("maxWarps", wconfig.getInt("maxWarps")); } else config.set("maxWarps", Integer.valueOf(5)); if(wconfig.isSet("mustBeInOwnTerritoryToCreate")) { config.set("mustBeInOwnTerritoryToCreate", wconfig.getBoolean("mustBeInOwnTerritoryToCreate")); } else config.set("mustBeInOwnTerritoryToCreate", true); if(wconfig.isSet("warpTeleportAllowedFromEnemyTerritory")){ config.set("warpTeleportAllowedFromEnemyTerritory", wconfig.getBoolean("warpTeleportAllowedFromEnemyTerritory")); } else config.set("warpTeleportAllowedFromEnemyTerritory", true); if(wconfig.isSet("warpTeleportAllowedFromDifferentWorld")){ config.set("warpTeleportAllowedFromDifferentWorld", wconfig.getBoolean("warpTeleportAllowedFromDifferentWorld")); } else config.set("warpTeleportAllowedFromDifferentWorld", true); if(wconfig.isSet("warpTeleportAllowedEnemyDistance")) { config.set("warpTeleportAllowedEnemyDistance", wconfig.getInt("warpTeleportAllowedEnemyDistance")); } else config.set("warpTeleportAllowedEnemyDistance", Integer.valueOf(35)); if(wconfig.isSet("warpTeleportIgnoreEnemiesIfInOwnTerritory")){ config.set("warpTeleportIgnoreEnemiesIfInOwnTerritory", wconfig.getBoolean("warpTeleportIgnoreEnemiesIfInOwnTerritory")); } else config.set("warpTeleportIgnoreEnemiesIfInOwnTerritory", true); if(wconfig.isSet("smokeEffectOnWarp")) { config.set("smokeEffectOnWarp", wconfig.getBoolean("smokeEffectOnWarp")); } else config.set("smokeEffectOnWarp", true); if(wconfig.isSet("powerBoostIfPeaceful")) { config.set("powerBoostIfPeaceful", wconfig.getInt("powerBoostIfPeaceful")); } else config.set("powerBoostIfPeaceful", Integer.valueOf(0)); if(wconfig.isSet("leadersCanSetJails")) { config.set("leadersCanSetJails", wconfig.getBoolean("leadersCanSetJails")); } else config.set("leadersCanSetJails", true); if(wconfig.isSet("officersCanSetJails")) { config.set("officersCanSetJails", wconfig.getBoolean("officersCanSetJails")); } else config.set("officersCanSetJails", true); if(wconfig.isSet("leadersCanSetRules")) { config.set("leadersCanSetRules", wconfig.getBoolean("leadersCanSetRules")); } else config.set("leadersCanSetRules", true); if(wconfig.isSet("officersCanSetRules")) { config.set("officersCanSetRules", wconfig.getBoolean("officersCanSetRules")); } else config.set("officersCanSetRules", true); if(wconfig.isSet("maxRulesPerFaction")) { config.set("maxRulesPerFaction", wconfig.getInt("maxRulesPerFaction")); } else config.set("maxRulesPerFaction", Integer.valueOf(12)); if(wconfig.isSet("membersCanSetJails")) { config.set("membersCanSetJails", wconfig.getBoolean("membersCanSetJails")); } else config.set("membersCanSetJails", false); if(wconfig.isSet("leadersCanJail")) { config.set("leadersCanJail", wconfig.getBoolean("leadersCanJail")); } else config.set("leadersCanJail", true); if(wconfig.isSet("officersCanJail")) { config.set("officersCanJail", wconfig.getBoolean("officersCanJail")); } else config.set("officersCanJail", true); if(wconfig.isSet("leadersCanAnnounce")) { config.set("leadersCanAnnounce", wconfig.getBoolean("leadersCanAnnounce")); } else config.set("leadersCanAnnounce", true); if(wconfig.isSet("officersCanAnnounce")) { config.set("officersCanAnnounce", wconfig.getBoolean("officersCanAnnounce")); } else config.set("officersCanAnnounce", true); if(wconfig.isSet("showLastAnnounceOnLogin")) { config.set("showLastAnnounceOnLogin", wconfig.getBoolean("showLastAnnounceOnLogin")); } else config.set("showLastAnnounceOnLogin", true); if(wconfig.isSet("showLastAnnounceOnLandEnter")) { config.set("showLastAnnounceOnLandEnter", wconfig.getBoolean("showLastAnnounceOnLandEnter")); } else config.set("showLastAnnounceOnLandEnter", true); if(wconfig.isSet("leadersCanFactionBan")) { config.set("leadersCanFactionBan", wconfig.getBoolean("leadersCanFactionBan")); } else config.set("leadersCanFactionBan", true); if(wconfig.isSet("officersCanFactionBan")) { config.set("officersCanFactionBan", wconfig.getBoolean("officersCanFactionBan")); } else config.set("officersCanFactionBan", true); if(wconfig.isSet("leaderCanNotBeBanned")) { config.set("leaderCanNotBeBanned", wconfig.getBoolean("leaderCanNotBeBanned")); } else config.set("leaderCanNotBeBanned", true); if(wconfig.isSet("leadersCanToggleState")) { config.set("leadersCanToggleState", wconfig.getBoolean("leadersCanToggleState")); } else config.set("leadersCanToggleState", false); if(wconfig.isSet("officersCanToggleState")) { config.set("officersCanToggleState", wconfig.getBoolean("officersCanToggleState")); } else config.set("officersCanToggleState", false); if(wconfig.isSet("membersCanToggleState")) { config.set("membersCanToggleState", wconfig.getBoolean("membersCanToggleState")); } else config.set("membersCanToggleState", false); if(wconfig.isSet("extraPowerLossIfDeathByOther")) { config.set("extraPowerLossIfDeathByOther", wconfig.getDouble("extraPowerLossIfDeathByOther")); } else config.set("extraPowerLossIfDeathByOther", Double.valueOf(0)); if(wconfig.isSet("extraPowerWhenKillPlayer")) { config.set("extraPowerWhenKillPlayer", wconfig.getDouble("extraPowerWhenKillPlayer")); } else config.set("extraPowerWhenKillPlayer", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathBySuicide")) { config.set("extraPowerLossIfDeathBySuicide", wconfig.getDouble("extraPowerLossIfDeathBySuicide")); } else config.set("extraPowerLossIfDeathBySuicide", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByPVP")) { config.set("extraPowerLossIfDeathByPVP", wconfig.getDouble("extraPowerLossIfDeathByPVP")); } else config.set("extraPowerLossIfDeathByPVP", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByMob")) { config.set("extraPowerLossIfDeathByMob", wconfig.getDouble("extraPowerLossIfDeathByMob")); } else config.set("extraPowerLossIfDeathByMob", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByCactus")) { config.set("extraPowerLossIfDeathByCactus", wconfig.getDouble("extraPowerLossIfDeathByCactus")); } else config.set("extraPowerLossIfDeathByCactus", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByTNT")) { config.set("extraPowerLossIfDeathByTNT", wconfig.getDouble("extraPowerLossIfDeathByTNT")); } else config.set("extraPowerLossIfDeathByTNT", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByFire")) { config.set("extraPowerLossIfDeathByFire", wconfig.getDouble("extraPowerLossIfDeathByFire")); } else config.set("extraPowerLossIfDeathByFire", Double.valueOf(0)); if(wconfig.isSet("extraPowerLossIfDeathByPotion")) { config.set("extraPowerLossIfDeathByPotion", wconfig.getDouble("extraPowerLossIfDeathByPotion")); } else config.set("extraPowerLossIfDeathByPotion", Double.valueOf(0)); if(wconfig.isSet("enablePermissionGroups")) { config.set("enablePermissionGroups", wconfig.getBoolean("enablePermissionGroups")); } else config.set("enablePermissionGroups", Boolean.valueOf(false)); if(wconfig.isSet("economy_enable")) { config.set("economy_enable", wconfig.getBoolean("economy_enable")); } else config.set("economy_enable", Boolean.valueOf(false)); if(wconfig.isSet("economy_costToWarp")) { config.set("economy_costToWarp", wconfig.getInt("economy_costToWarp")); } else config.set("economy_costToWarp", Integer.valueOf(0)); if(wconfig.isSet("economy_costToCreateWarp")) { config.set("economy_costToCreateWarp", wconfig.getInt("economy_costToCreateWarp")); } else config.set("economy_costToCreateWarp", Integer.valueOf(0)); if(wconfig.isSet("economy_costToDeleteWarp")) { config.set("economy_costToDeleteWarp", wconfig.getInt("economy_costToDeleteWarp")); } else config.set("economy_costToDeleteWarp", Integer.valueOf(0)); if(wconfig.isSet("economy_costToAnnounce")) { config.set("economy_costToAnnounce", wconfig.getInt("economy_costToAnnounce")); } else config.set("economy_costToAnnounce", Integer.valueOf(0)); if(wconfig.isSet("economy_costToJail")) { config.set("economy_costToJail", wconfig.getInt("economy_costToJail")); } else config.set("economy_costToJail", Integer.valueOf(0)); if(wconfig.isSet("economy_costToSetJail")) { config.set("economy_costToSetJail", wconfig.getInt("economy_costToSetJail")); } else config.set("economy_costToSetJail", Integer.valueOf(0)); if(wconfig.isSet("economy_costToUnJail")) { config.set("economy_costToUnJail", wconfig.getInt("economy_costToUnJail")); } else config.set("economy_costToUnJail", Integer.valueOf(0)); if(wconfig.isSet("economy_costToToggleUpPeaceful")) { config.set("economy_costToToggleUpPeaceful", wconfig.getInt("economy_costToToggleUpPeaceful")); } else config.set("economy_costToToggleUpPeaceful", Integer.valueOf(0)); if(wconfig.isSet("economy_costToToggleDownPeaceful")) { config.set("economy_costToToggleDownPeaceful", wconfig.getInt("economy_costToToggleDownPeaceful")); } else config.set("economy_costToToggleDownPeaceful", Integer.valueOf(0)); if(wconfig.isSet("useLWCIntegrationFix")) { config.set("useLWCIntegrationFix", wconfig.getBoolean("useLWCIntegrationFix")); } else config.set("useLWCIntegrationFix", false); config.set("DoNotChangeMe", Integer.valueOf(8)); config.save(configFile); saveConfig(); } catch(Exception e) { e.printStackTrace(); log.info("[FactionsPlus] An error occured while managing the configuration file (-18)"); getPluginLoader().disablePlugin(this); } if (!templatesFile.exists()) { FactionsPlusTemplates.createTemplatesFile(); } templates = YamlConfiguration.loadConfiguration(templatesFile); config = YamlConfiguration.loadConfiguration(configFile); FactionsPlusCommandManager.setup(); FactionsPlusHelpModifier.modify(); RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); if (permissionProvider != null) { permission = permissionProvider.getProvider(); } if(config.getBoolean("economy_enable")) { RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); } } if(getServer().getPluginManager().isPluginEnabled("DisguiseCraft")) { pm.registerEvents(this.DCListener, this); log.info("[FactionsPlus] Hooked into DisguiseCraft!"); isDisguiseCraftEnabled = true; } if(getServer().getPluginManager().isPluginEnabled("MobDisguise")) { pm.registerEvents(this.MDListener, this); log.info("[FactionsPlus] Hooked into MobDisguise!"); isMobDisguiseEnabled = true; } if(getServer().getPluginManager().isPluginEnabled("WorldEdit")) { worldEditPlugin = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit"); log.info("[FactionsPlus] Hooked into WorldEdit!"); isWorldEditEnabled = true; } if(getServer().getPluginManager().isPluginEnabled("WorldGuard")) { worldGuardPlugin = (WorldGuardPlugin) getServer().getPluginManager().getPlugin("WorldGuard"); log.info("[FactionsPlus] Hooked into WorldGuard!"); isWorldGuardEnabled = true; } if(config.getBoolean("useLWCIntegrationFix") == true) { if(getServer().getPluginManager().isPluginEnabled("LWC")) { pm.registerEvents(this.LWCListener, this); log.info("[FactionsPlus] Hooked into LWC!"); LWCFunctions.integrateLWC((LWCPlugin)getServer().getPluginManager().getPlugin("LWC")); isLWCEnabled = true; } else { log.info("[FactionsPlus] No LWC Found but Integration Option Is Enabled!"); } } FactionsPlus.config = YamlConfiguration.loadConfiguration(FactionsPlus.configFile); version = getDescription().getVersion(); FactionsPlusUpdate.checkUpdates(); log.info("[FactionsPlus] Ready."); try { Metrics metrics = new Metrics(this); metrics.start(); } catch (IOException e) { log.info("[FactionsPlus] Waah! Couldn't metrics-up! :'("); } }
diff --git a/SolarPowerCalcWeb/test/au/edu/qut/inn372/greenhat/dao/EquipmentDAOTest.java b/SolarPowerCalcWeb/test/au/edu/qut/inn372/greenhat/dao/EquipmentDAOTest.java index fe4123e..1f8fbae 100644 --- a/SolarPowerCalcWeb/test/au/edu/qut/inn372/greenhat/dao/EquipmentDAOTest.java +++ b/SolarPowerCalcWeb/test/au/edu/qut/inn372/greenhat/dao/EquipmentDAOTest.java @@ -1,28 +1,28 @@ package au.edu.qut.inn372.greenhat.dao; import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.Before; import org.junit.Test; import au.edu.qut.inn372.greenhat.bean.Equipment; import au.edu.qut.inn372.greenhat.dao.gae.EquipmentDAOImpl; public class EquipmentDAOTest { EquipmentDAO dao; @Before public void setUp() throws Exception { dao = new EquipmentDAOImpl(); } @Test public void testGetEquipments() { List<Equipment> equipments = dao.getEquipments(); Equipment[] list = new Equipment[equipments.size()]; equipments.toArray(list); - assertEquals(equipments.size(), 3); + assertEquals(equipments.size(), 4); } }
true
true
public void testGetEquipments() { List<Equipment> equipments = dao.getEquipments(); Equipment[] list = new Equipment[equipments.size()]; equipments.toArray(list); assertEquals(equipments.size(), 3); }
public void testGetEquipments() { List<Equipment> equipments = dao.getEquipments(); Equipment[] list = new Equipment[equipments.size()]; equipments.toArray(list); assertEquals(equipments.size(), 4); }
diff --git a/src/main/java/com/bergerkiller/bukkit/nolagg/lighting/LightingService.java b/src/main/java/com/bergerkiller/bukkit/nolagg/lighting/LightingService.java index a103461..1424e2c 100644 --- a/src/main/java/com/bergerkiller/bukkit/nolagg/lighting/LightingService.java +++ b/src/main/java/com/bergerkiller/bukkit/nolagg/lighting/LightingService.java @@ -1,206 +1,216 @@ package com.bergerkiller.bukkit.nolagg.lighting; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.bergerkiller.bukkit.common.AsyncTask; import com.bergerkiller.bukkit.common.bases.IntVector2; import com.bergerkiller.bukkit.common.utils.WorldUtil; public class LightingService extends AsyncTask { private static AsyncTask fixThread = null; private static final LinkedList<LightingTask> tasks = new LinkedList<LightingTask>(); private static final LinkedList<LightingTaskRegion> regions = new LinkedList<LightingTaskRegion>(); private static final Set<String> recipientsForDone = new HashSet<String>(); private static int taskChunkCount = 0; private static LightingTask currentTask; public static void scheduleWorld(final World world) { // Obtain the folder where regions of the world are stored File regionFolderTmp = WorldUtil.getWorldFolder(world); // Special dim folder for nether and the_end if (world.getEnvironment() == Environment.NETHER) { regionFolderTmp = new File(regionFolderTmp, "DIM-1"); } else if (world.getEnvironment() == Environment.THE_END) { regionFolderTmp = new File(regionFolderTmp, "DIM1"); } // Final region folder appending final File regionFolder = new File(regionFolderTmp, "region"); if (regionFolder.exists()) { synchronized (regions) { for (String regionFileName : regionFolder.list()) { regions.add(new LightingTaskRegion(world, regionFolder, regionFileName)); taskChunkCount += 1024; } } } // Start the fixing thread if (fixThread == null) { fixThread = new LightingService().start(true); } } /** * Adds a player who will be notified of the lighting operations being completed * * @param player to add, null for console */ public static void addRecipient(CommandSender sender) { synchronized (recipientsForDone) { recipientsForDone.add((sender instanceof Player) ? sender.getName() : null); } } /** * Schedules a square chunk area for lighting fixing * * @param world the chunks are in * @param middleX * @param middleZ * @param radius */ public static void scheduleArea(World world, int middleX, int middleZ, int radius) { List<IntVector2> chunks = new ArrayList<IntVector2>(); for (int a = -radius; a <= radius; a++) { for (int b = -radius; b <= radius; b++) { chunks.add(new IntVector2(middleX + a, middleZ + b)); } } schedule(world, chunks); } public static void schedule(World world, List<IntVector2> chunks) { schedule(new LightingTask(world, chunks)); } public static void schedule(LightingTask task) { synchronized (tasks) { tasks.offer(task); taskChunkCount += task.getChunkCount(); } if (fixThread == null) { fixThread = new LightingService().start(true); } } /** * Gets whether this service si currently processing something * * @return True if processing, False if not */ public static boolean isProcessing() { return fixThread != null; } /** * Checks whether the chunk specified is being processed on * * @param chunk to check * @return True if the chunk is being processed, False if not */ public static boolean isProcessing(Chunk chunk) { final LightingTask current = currentTask; if (current == null) { return false; } else { return current.world == chunk.getWorld() && current.containsChunk(chunk.getX(), chunk.getZ()); } } /** * Orders this service to abort all tasks, finishing the current task in an * orderly fashion. */ public static void abort() { // Clear regions synchronized (regions) { regions.clear(); } // Clear lighting tasks synchronized (tasks) { tasks.clear(); taskChunkCount = 0; } // Finish the current lighting task if available final LightingTask current = currentTask; if (fixThread != null && current != null) { NoLaggLighting.plugin.log(Level.INFO, "Processing lighting in the remaining " + current.getFaults() + " chunks..."); fixThread.stop(); // Sync tasks no longer execute: make sure that we tick them while (fixThread.isRunning()) { current.tickTask(); sleep(20); } fixThread = null; } } /** * Gets the amount of chunks that are still faulty * * @return faulty chunk count */ public static int getChunkFaults() { final LightingTask current = currentTask; return taskChunkCount + (current == null ? 0 : current.getFaults()); } @Override public void run() { synchronized (tasks) { currentTask = tasks.poll(); } // No task, maybe a region? if (currentTask == null) { LightingTaskRegion reg; - synchronized (regions) { - reg = regions.poll(); - } - if (reg != null) { - currentTask = reg.createTask(); - taskChunkCount -= 1024; + while (true) { + synchronized (regions) { + reg = regions.poll(); + } + if (reg == null) { + // No region tasks, abort + break; + } else { + currentTask = reg.createTask(); + taskChunkCount -= 1024; + if (currentTask != null) { + // We have a task, start working on it + break; + } + } } } else { + // New task polled - decrement chunk count taskChunkCount -= currentTask.getChunkCount(); } if (currentTask == null) { // Messages final String message = ChatColor.GREEN + "All lighting operations are completed."; synchronized (recipientsForDone) { for (String player : recipientsForDone) { CommandSender recip = player == null ? Bukkit.getConsoleSender() : Bukkit.getPlayer(player); if (recip != null) { recip.sendMessage(message); } } recipientsForDone.clear(); } // Stop task and abort this.stop(); fixThread = null; return; } // Operate on the task // Load currentTask.startLoading(); currentTask.waitForCompletion(); // Fix currentTask.fix(); // Apply currentTask.startApplying(); currentTask.waitForCompletion(); } }
false
true
public void run() { synchronized (tasks) { currentTask = tasks.poll(); } // No task, maybe a region? if (currentTask == null) { LightingTaskRegion reg; synchronized (regions) { reg = regions.poll(); } if (reg != null) { currentTask = reg.createTask(); taskChunkCount -= 1024; } } else { taskChunkCount -= currentTask.getChunkCount(); } if (currentTask == null) { // Messages final String message = ChatColor.GREEN + "All lighting operations are completed."; synchronized (recipientsForDone) { for (String player : recipientsForDone) { CommandSender recip = player == null ? Bukkit.getConsoleSender() : Bukkit.getPlayer(player); if (recip != null) { recip.sendMessage(message); } } recipientsForDone.clear(); } // Stop task and abort this.stop(); fixThread = null; return; } // Operate on the task // Load currentTask.startLoading(); currentTask.waitForCompletion(); // Fix currentTask.fix(); // Apply currentTask.startApplying(); currentTask.waitForCompletion(); }
public void run() { synchronized (tasks) { currentTask = tasks.poll(); } // No task, maybe a region? if (currentTask == null) { LightingTaskRegion reg; while (true) { synchronized (regions) { reg = regions.poll(); } if (reg == null) { // No region tasks, abort break; } else { currentTask = reg.createTask(); taskChunkCount -= 1024; if (currentTask != null) { // We have a task, start working on it break; } } } } else { // New task polled - decrement chunk count taskChunkCount -= currentTask.getChunkCount(); } if (currentTask == null) { // Messages final String message = ChatColor.GREEN + "All lighting operations are completed."; synchronized (recipientsForDone) { for (String player : recipientsForDone) { CommandSender recip = player == null ? Bukkit.getConsoleSender() : Bukkit.getPlayer(player); if (recip != null) { recip.sendMessage(message); } } recipientsForDone.clear(); } // Stop task and abort this.stop(); fixThread = null; return; } // Operate on the task // Load currentTask.startLoading(); currentTask.waitForCompletion(); // Fix currentTask.fix(); // Apply currentTask.startApplying(); currentTask.waitForCompletion(); }
diff --git a/processor-core/src/main/java/de/plushnikov/intellij/lombok/processor/SynchronizedProcessor.java b/processor-core/src/main/java/de/plushnikov/intellij/lombok/processor/SynchronizedProcessor.java index e720fb77..eb97f73e 100644 --- a/processor-core/src/main/java/de/plushnikov/intellij/lombok/processor/SynchronizedProcessor.java +++ b/processor-core/src/main/java/de/plushnikov/intellij/lombok/processor/SynchronizedProcessor.java @@ -1,70 +1,70 @@ package de.plushnikov.intellij.lombok.processor; import com.intellij.codeInsight.intention.QuickFixFactory; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiAnnotation; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiField; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiModifier; import com.intellij.psi.util.PsiTreeUtil; import de.plushnikov.intellij.lombok.problem.LombokProblem; import de.plushnikov.intellij.lombok.problem.ProblemNewBuilder; import de.plushnikov.intellij.lombok.util.PsiAnnotationUtil; import lombok.Synchronized; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collection; /** * Inspect and validate @Synchronized lombok annotation * * @author Plushnikov Michail */ public class SynchronizedProcessor extends AbstractLombokProcessor { public static final String CLASS_NAME = Synchronized.class.getName(); public SynchronizedProcessor() { super(CLASS_NAME, PsiElement.class); } @Override public Collection<LombokProblem> verifyAnnotation(@NotNull PsiAnnotation psiAnnotation) { Collection<LombokProblem> result = new ArrayList<LombokProblem>(2); final ProblemNewBuilder problemNewBuilder = new ProblemNewBuilder(result); PsiMethod psiMethod = PsiTreeUtil.getParentOfType(psiAnnotation, PsiMethod.class); if (null != psiMethod) { if (psiMethod.hasModifierProperty(PsiModifier.ABSTRACT)) { problemNewBuilder.addError("'@Synchronized' is legal only on concrete methods.", QuickFixFactory.getInstance().createModifierListFix(psiMethod, PsiModifier.ABSTRACT, false, false) ); } final String lockFieldName = PsiAnnotationUtil.getAnnotationValue(psiAnnotation, "value", String.class); if (StringUtil.isNotEmpty(lockFieldName)) { final PsiClass containingClass = psiMethod.getContainingClass(); if (null != containingClass) { final PsiField lockField = containingClass.findFieldByName(lockFieldName, true); if (null != lockField) { - if (lockField.hasModifierProperty(PsiModifier.FINAL)) { + if (!lockField.hasModifierProperty(PsiModifier.FINAL)) { problemNewBuilder.addWarning(String.format("Synchronization on a non-final field %s.", lockFieldName), QuickFixFactory.getInstance().createModifierListFix(lockField, PsiModifier.FINAL, true, false)); } } else { problemNewBuilder.addError(String.format("The field %s does not exist.", lockFieldName)); //TODO add QuickFix for creating this field } } } } else { problemNewBuilder.addError("'@Synchronized' is legal only on methods."); } return result; } }
true
true
public Collection<LombokProblem> verifyAnnotation(@NotNull PsiAnnotation psiAnnotation) { Collection<LombokProblem> result = new ArrayList<LombokProblem>(2); final ProblemNewBuilder problemNewBuilder = new ProblemNewBuilder(result); PsiMethod psiMethod = PsiTreeUtil.getParentOfType(psiAnnotation, PsiMethod.class); if (null != psiMethod) { if (psiMethod.hasModifierProperty(PsiModifier.ABSTRACT)) { problemNewBuilder.addError("'@Synchronized' is legal only on concrete methods.", QuickFixFactory.getInstance().createModifierListFix(psiMethod, PsiModifier.ABSTRACT, false, false) ); } final String lockFieldName = PsiAnnotationUtil.getAnnotationValue(psiAnnotation, "value", String.class); if (StringUtil.isNotEmpty(lockFieldName)) { final PsiClass containingClass = psiMethod.getContainingClass(); if (null != containingClass) { final PsiField lockField = containingClass.findFieldByName(lockFieldName, true); if (null != lockField) { if (lockField.hasModifierProperty(PsiModifier.FINAL)) { problemNewBuilder.addWarning(String.format("Synchronization on a non-final field %s.", lockFieldName), QuickFixFactory.getInstance().createModifierListFix(lockField, PsiModifier.FINAL, true, false)); } } else { problemNewBuilder.addError(String.format("The field %s does not exist.", lockFieldName)); //TODO add QuickFix for creating this field } } } } else { problemNewBuilder.addError("'@Synchronized' is legal only on methods."); } return result; }
public Collection<LombokProblem> verifyAnnotation(@NotNull PsiAnnotation psiAnnotation) { Collection<LombokProblem> result = new ArrayList<LombokProblem>(2); final ProblemNewBuilder problemNewBuilder = new ProblemNewBuilder(result); PsiMethod psiMethod = PsiTreeUtil.getParentOfType(psiAnnotation, PsiMethod.class); if (null != psiMethod) { if (psiMethod.hasModifierProperty(PsiModifier.ABSTRACT)) { problemNewBuilder.addError("'@Synchronized' is legal only on concrete methods.", QuickFixFactory.getInstance().createModifierListFix(psiMethod, PsiModifier.ABSTRACT, false, false) ); } final String lockFieldName = PsiAnnotationUtil.getAnnotationValue(psiAnnotation, "value", String.class); if (StringUtil.isNotEmpty(lockFieldName)) { final PsiClass containingClass = psiMethod.getContainingClass(); if (null != containingClass) { final PsiField lockField = containingClass.findFieldByName(lockFieldName, true); if (null != lockField) { if (!lockField.hasModifierProperty(PsiModifier.FINAL)) { problemNewBuilder.addWarning(String.format("Synchronization on a non-final field %s.", lockFieldName), QuickFixFactory.getInstance().createModifierListFix(lockField, PsiModifier.FINAL, true, false)); } } else { problemNewBuilder.addError(String.format("The field %s does not exist.", lockFieldName)); //TODO add QuickFix for creating this field } } } } else { problemNewBuilder.addError("'@Synchronized' is legal only on methods."); } return result; }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/TasksUiPlugin.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/TasksUiPlugin.java index a46943c8c..1bfb5d88d 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/TasksUiPlugin.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/TasksUiPlugin.java @@ -1,1171 +1,1171 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.tasks.ui; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.eclipse.core.internal.net.ProxyManager; import org.eclipse.core.net.proxy.IProxyChangeListener; import org.eclipse.core.net.proxy.IProxyService; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ISaveContext; import org.eclipse.core.resources.ISaveParticipant; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.Preferences.IPropertyChangeListener; import org.eclipse.core.runtime.Preferences.PropertyChangeEvent; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.text.hyperlink.IHyperlinkDetector; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.mylyn.context.core.ContextCorePlugin; import org.eclipse.mylyn.internal.context.core.ContextPreferenceContstants; import org.eclipse.mylyn.internal.tasks.core.LocalRepositoryConnector; import org.eclipse.mylyn.internal.tasks.core.ScheduledTaskContainer; import org.eclipse.mylyn.internal.tasks.core.TaskActivityManager; import org.eclipse.mylyn.internal.tasks.core.TaskDataManager; import org.eclipse.mylyn.internal.tasks.ui.IDynamicSubMenuContributor; import org.eclipse.mylyn.internal.tasks.ui.ITaskHighlighter; import org.eclipse.mylyn.internal.tasks.ui.ITaskListNotificationProvider; import org.eclipse.mylyn.internal.tasks.ui.ITasksUiConstants; import org.eclipse.mylyn.internal.tasks.ui.OfflineCachingStorage; import org.eclipse.mylyn.internal.tasks.ui.OfflineFileStorage; import org.eclipse.mylyn.internal.tasks.ui.RepositoryAwareStatusHandler; import org.eclipse.mylyn.internal.tasks.ui.TaskEditorBloatMonitor; import org.eclipse.mylyn.internal.tasks.ui.TaskListBackupManager; import org.eclipse.mylyn.internal.tasks.ui.TaskListColorsAndFonts; import org.eclipse.mylyn.internal.tasks.ui.TaskListNotificationManager; import org.eclipse.mylyn.internal.tasks.ui.TaskListSynchronizationScheduler; import org.eclipse.mylyn.internal.tasks.ui.TaskRepositoryUtil; import org.eclipse.mylyn.internal.tasks.ui.TasksUiPreferenceConstants; import org.eclipse.mylyn.internal.tasks.ui.notifications.AbstractNotification; import org.eclipse.mylyn.internal.tasks.ui.notifications.TaskListNotification; import org.eclipse.mylyn.internal.tasks.ui.notifications.TaskListNotificationQueryIncoming; import org.eclipse.mylyn.internal.tasks.ui.notifications.TaskListNotificationReminder; import org.eclipse.mylyn.internal.tasks.ui.util.TaskListSaveManager; import org.eclipse.mylyn.internal.tasks.ui.util.TaskListWriter; import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiExtensionReader; import org.eclipse.mylyn.internal.tasks.ui.views.TaskRepositoriesView; import org.eclipse.mylyn.internal.tasks.ui.wizards.EditRepositoryWizard; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.tasks.core.AbstractAttributeFactory; import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector; import org.eclipse.mylyn.tasks.core.AbstractRepositoryQuery; import org.eclipse.mylyn.tasks.core.AbstractTask; import org.eclipse.mylyn.tasks.core.AbstractTaskContainer; import org.eclipse.mylyn.tasks.core.AbstractTaskDataHandler; import org.eclipse.mylyn.tasks.core.ITaskActivityListener; import org.eclipse.mylyn.tasks.core.RepositoryTaskAttribute; import org.eclipse.mylyn.tasks.core.RepositoryTaskData; import org.eclipse.mylyn.tasks.core.RepositoryTemplate; import org.eclipse.mylyn.tasks.core.TaskComment; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.core.TaskRepositoryManager; import org.eclipse.mylyn.tasks.core.AbstractTask.PriorityLevel; import org.eclipse.mylyn.tasks.core.AbstractTask.RepositoryTaskSyncState; import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorFactory; import org.eclipse.mylyn.web.core.WebClientUtil; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IStartup; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.ui.progress.UIJob; import org.osgi.framework.BundleContext; /** * Main entry point for the Tasks UI. * * @author Mik Kersten * @since 2.0 */ public class TasksUiPlugin extends AbstractUIPlugin implements IStartup { private static final int LINK_PROVIDER_TIMEOUT_SECONDS = 5; public static final String LABEL_VIEW_REPOSITORIES = "Task Repositories"; public static final String ID_PLUGIN = "org.eclipse.mylyn.tasks.ui"; private static final String FOLDER_OFFLINE = "offline"; private static final String DIRECTORY_METADATA = ".metadata"; private static final String NAME_DATA_DIR = ".mylyn"; private static final char DEFAULT_PATH_SEPARATOR = '/'; private static final int NOTIFICATION_DELAY = 5000; private static TasksUiPlugin INSTANCE; private static TaskListManager taskListManager; private static TaskActivityManager taskActivityManager; private static TaskRepositoryManager taskRepositoryManager; private static TaskListSynchronizationScheduler synchronizationScheduler; private static RepositorySynchronizationManager synchronizationManager; private static Map<String, AbstractRepositoryConnectorUi> repositoryConnectorUiMap = new HashMap<String, AbstractRepositoryConnectorUi>(); private TaskListSaveManager taskListSaveManager; private TaskListNotificationManager taskListNotificationManager; private TaskListBackupManager taskListBackupManager; private TaskDataManager taskDataManager; private Set<AbstractTaskEditorFactory> taskEditorFactories = new HashSet<AbstractTaskEditorFactory>(); private Set<IHyperlinkDetector> hyperlinkDetectors = new HashSet<IHyperlinkDetector>(); private TreeSet<AbstractTaskRepositoryLinkProvider> repositoryLinkProviders = new TreeSet<AbstractTaskRepositoryLinkProvider>( new OrderComparator()); private TaskListWriter taskListWriter; private ITaskHighlighter highlighter; private boolean initialized = false; private Map<String, Image> brandingIcons = new HashMap<String, Image>(); private Map<String, ImageDescriptor> overlayIcons = new HashMap<String, ImageDescriptor>(); private Set<AbstractDuplicateDetector> duplicateDetectors = new HashSet<AbstractDuplicateDetector>(); private ISaveParticipant saveParticipant; private TaskEditorBloatMonitor taskEditorBloatManager; private static final boolean DEBUG_HTTPCLIENT = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.mylyn.tasks.ui/debug/httpclient")); private static final class OrderComparator implements Comparator<AbstractTaskRepositoryLinkProvider> { public int compare(AbstractTaskRepositoryLinkProvider p1, AbstractTaskRepositoryLinkProvider p2) { return p1.getOrder() - p2.getOrder(); } } public enum TaskListSaveMode { ONE_HOUR, THREE_HOURS, DAY; @Override public String toString() { switch (this) { case ONE_HOUR: return "1 hour"; case THREE_HOURS: return "3 hours"; case DAY: return "1 day"; default: return "3 hours"; } } public static TaskListSaveMode fromString(String string) { if (string == null) return null; if (string.equals("1 hour")) return ONE_HOUR; if (string.equals("3 hours")) return THREE_HOURS; if (string.equals("1 day")) return DAY; return null; } public static long fromStringToLong(String string) { long hour = 3600 * 1000; switch (fromString(string)) { case ONE_HOUR: return hour; case THREE_HOURS: return hour * 3; case DAY: return hour * 24; default: return hour * 3; } } } public enum ReportOpenMode { EDITOR, INTERNAL_BROWSER, EXTERNAL_BROWSER; } private static ITaskActivityListener CONTEXT_TASK_ACTIVITY_LISTENER = new ITaskActivityListener() { public void taskActivated(final AbstractTask task) { ContextCorePlugin.getContextManager().activateContext(task.getHandleIdentifier()); } public void taskDeactivated(final AbstractTask task) { ContextCorePlugin.getContextManager().deactivateContext(task.getHandleIdentifier()); } public void activityChanged(ScheduledTaskContainer week) { // ignore } public void taskListRead() { // ignore } }; private static ITaskListNotificationProvider REMINDER_NOTIFICATION_PROVIDER = new ITaskListNotificationProvider() { public Set<AbstractNotification> getNotifications() { Date currentDate = new Date(); Collection<AbstractTask> allTasks = TasksUiPlugin.getTaskListManager().getTaskList().getAllTasks(); Set<AbstractNotification> reminders = new HashSet<AbstractNotification>(); for (AbstractTask task : allTasks) { if (!task.isCompleted() && task.getScheduledForDate() != null && !task.isReminded() && task.getScheduledForDate().compareTo(currentDate) < 0) { reminders.add(new TaskListNotificationReminder(task)); task.setReminded(true); } } return reminders; } }; private static ITaskListNotificationProvider INCOMING_NOTIFICATION_PROVIDER = new ITaskListNotificationProvider() { public Set<AbstractNotification> getNotifications() { Set<AbstractNotification> notifications = new HashSet<AbstractNotification>(); // Incoming Changes for (TaskRepository repository : getRepositoryManager().getAllRepositories()) { AbstractRepositoryConnector connector = getRepositoryManager().getRepositoryConnector( repository.getConnectorKind()); AbstractRepositoryConnectorUi connectorUi = getConnectorUi(repository.getConnectorKind()); if (connectorUi != null && !connectorUi.isCustomNotificationHandling()) { for (AbstractTask repositoryTask : TasksUiPlugin.getTaskListManager() .getTaskList() .getRepositoryTasks(repository.getUrl())) { if ((repositoryTask.getLastReadTimeStamp() == null || repositoryTask.getSynchronizationState() == RepositoryTaskSyncState.INCOMING) && repositoryTask.isNotified() == false) { TaskListNotification notification = INSTANCE.getIncommingNotification(connector, repositoryTask); notifications.add(notification); repositoryTask.setNotified(true); } } } } // New query hits for (AbstractRepositoryQuery query : TasksUiPlugin.getTaskListManager().getTaskList().getQueries()) { AbstractRepositoryConnectorUi connectorUi = getConnectorUi(query.getRepositoryKind()); if (!connectorUi.isCustomNotificationHandling()) { for (AbstractTask hit : query.getChildren()) { if (hit.isNotified() == false) { notifications.add(new TaskListNotificationQueryIncoming(hit)); hit.setNotified(true); } } } } return notifications; } }; private final IPropertyChangeListener PREFERENCE_LISTENER = new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { // TODO: do we ever get here? if (event.getProperty().equals(ContextPreferenceContstants.PREF_DATA_DIR)) { if (event.getOldValue() instanceof String) { reloadDataDirectory(true); } } } }; private final org.eclipse.jface.util.IPropertyChangeListener PROPERTY_LISTENER = new org.eclipse.jface.util.IPropertyChangeListener() { public void propertyChange(org.eclipse.jface.util.PropertyChangeEvent event) { if (event.getProperty().equals(ContextPreferenceContstants.PREF_DATA_DIR)) { if (event.getOldValue() instanceof String) { reloadDataDirectory(true); } } } }; private class TasksUiInitializationJob extends UIJob { public TasksUiInitializationJob() { super("Initializing Task List"); setSystem(true); } @Override public IStatus runInUIThread(IProgressMonitor monitor) { // NOTE: failure in one part of the initialization should // not prevent others monitor.beginTask("Initializing Task List", 5); try { // Needs to run after workbench is loaded because it // relies on images. TasksUiExtensionReader.initWorkbenchUiExtensions(); // Needs to happen asynchronously to avoid bug 159706 if (taskListManager.getTaskList().getActiveTask() != null) { taskListManager.activateTask(taskListManager.getTaskList().getActiveTask()); } taskListManager.initActivityHistory(); } catch (Throwable t) { StatusHandler.fail(t, "Could not initialize task activity", false); } monitor.worked(1); try { taskListNotificationManager = new TaskListNotificationManager(); taskListNotificationManager.addNotificationProvider(REMINDER_NOTIFICATION_PROVIDER); taskListNotificationManager.addNotificationProvider(INCOMING_NOTIFICATION_PROVIDER); taskListNotificationManager.startNotification(NOTIFICATION_DELAY); getPreferenceStore().addPropertyChangeListener(taskListNotificationManager); } catch (Throwable t) { StatusHandler.fail(t, "Could not initialize notifications", false); } monitor.worked(1); try { taskListBackupManager = new TaskListBackupManager(); getPreferenceStore().addPropertyChangeListener(taskListBackupManager); synchronizationScheduler = new TaskListSynchronizationScheduler(true); synchronizationScheduler.startSynchJob(); } catch (Throwable t) { StatusHandler.fail(t, "Could not initialize task list backup and synchronization", false); } monitor.worked(1); try { taskListSaveManager = new TaskListSaveManager(); taskListManager.setTaskListSaveManager(taskListSaveManager); ContextCorePlugin.getDefault().getPluginPreferences().addPropertyChangeListener(PREFERENCE_LISTENER); getPreferenceStore().addPropertyChangeListener(PROPERTY_LISTENER); getPreferenceStore().addPropertyChangeListener(synchronizationScheduler); getPreferenceStore().addPropertyChangeListener(taskListManager); // TODO: get rid of this, hack to make decorators show // up on startup TaskRepositoriesView repositoriesView = TaskRepositoriesView.getFromActivePerspective(); if (repositoriesView != null) { repositoriesView.getViewer().refresh(); } checkForCredentials(); taskEditorBloatManager = new TaskEditorBloatMonitor(); taskEditorBloatManager.install(PlatformUI.getWorkbench()); } catch (Throwable t) { StatusHandler.fail(t, "Could not finish Tasks UI initialization", false); } finally { monitor.done(); } return new Status(IStatus.OK, TasksUiPlugin.ID_PLUGIN, IStatus.OK, "", null); } } public TasksUiPlugin() { super(); INSTANCE = this; } @Override public void start(BundleContext context) throws Exception { super.start(context); // NOTE: startup order is very sensitive try { StatusHandler.setDefaultStatusHandler(new RepositoryAwareStatusHandler()); WebClientUtil.setLoggingEnabled(DEBUG_HTTPCLIENT); initializeDefaultPreferences(getPreferenceStore()); taskListWriter = new TaskListWriter(); File dataDir = new File(getDataDirectory()); dataDir.mkdirs(); String path = getDataDirectory() + File.separator + ITasksUiConstants.DEFAULT_TASK_LIST_FILE; File taskListFile = new File(path); taskListManager = new TaskListManager(taskListWriter, taskListFile); taskActivityManager = TaskActivityManager.getInstance(); taskRepositoryManager = new TaskRepositoryManager(taskListManager.getTaskList()); IProxyService proxyService = ProxyManager.getProxyManager(); IProxyChangeListener proxyChangeListener = new TasksUiProxyChangeListener(taskRepositoryManager); proxyService.addProxyChangeListener(proxyChangeListener); synchronizationManager = new RepositorySynchronizationManager(); // NOTE: initializing extensions in start(..) has caused race // conditions previously TasksUiExtensionReader.initStartupExtensions(taskListWriter); taskRepositoryManager.readRepositories(getRepositoriesFilePath()); // instantiates taskDataManager startOfflineStorageManager(); loadTemplateRepositories(); // NOTE: task list must be read before Task List view can be // initialized taskListManager.init(); taskListManager.addActivityListener(CONTEXT_TASK_ACTIVITY_LISTENER); // readExistingOrCreateNewList() must be called after repositories have been read in taskListManager.readExistingOrCreateNewList(); initialized = true; // if the taskListManager didn't initialize do it here if (!taskActivityManager.isInitialized()) { taskActivityManager.init(taskRepositoryManager, taskListManager.getTaskList()); taskActivityManager.setEndHour(getPreferenceStore().getInt(TasksUiPreferenceConstants.PLANNING_ENDHOUR)); } saveParticipant = new ISaveParticipant() { public void doneSaving(ISaveContext context) { } public void prepareToSave(ISaveContext context) throws CoreException { } public void rollback(ISaveContext context) { } public void saving(ISaveContext context) throws CoreException { if (context.getKind() == ISaveContext.FULL_SAVE) { taskListManager.saveTaskList(); taskDataManager.stop(); } } }; ResourcesPlugin.getWorkspace().addSaveParticipant(this, saveParticipant); new TasksUiInitializationJob().schedule(); } catch (Exception e) { e.printStackTrace(); StatusHandler.fail(e, "Mylyn Task List initialization failed", false); } } private void loadTemplateRepositories() { // Add standard local task repository if (taskRepositoryManager.getRepository(LocalRepositoryConnector.REPOSITORY_URL) == null) { TaskRepository localRepository = new TaskRepository(LocalRepositoryConnector.CONNECTOR_KIND, LocalRepositoryConnector.REPOSITORY_URL, LocalRepositoryConnector.REPOSITORY_VERSION); localRepository.setRepositoryLabel(LocalRepositoryConnector.REPOSITORY_LABEL); localRepository.setAnonymous(true); taskRepositoryManager.addRepository(localRepository, getRepositoriesFilePath()); } // Add the automatically created templates for (AbstractRepositoryConnector connector : taskRepositoryManager.getRepositoryConnectors()) { connector.setTaskDataManager(taskDataManager); for (RepositoryTemplate template : connector.getTemplates()) { if (template.addAutomatically && !TaskRepositoryUtil.isAddAutomaticallyDisabled(template.repositoryUrl)) { try { TaskRepository taskRepository = taskRepositoryManager.getRepository( connector.getConnectorKind(), template.repositoryUrl); if (taskRepository == null) { taskRepository = new TaskRepository(connector.getConnectorKind(), template.repositoryUrl, template.version); taskRepository.setRepositoryLabel(template.label); taskRepository.setAnonymous(true); taskRepositoryManager.addRepository(taskRepository, getRepositoriesFilePath()); } } catch (Throwable t) { StatusHandler.fail(t, "Could not load repository template", false); } } } } } private void checkForCredentials() { for (TaskRepository repository : taskRepositoryManager.getAllRepositories()) { AbstractRepositoryConnector connector = getRepositoryManager().getRepositoryConnector( repository.getConnectorKind()); boolean promptForCredentials = true; if (connector != null) { promptForCredentials = connector.isUserManaged() && !connector.hasCredentialsManagement(); } if (!repository.isAnonymous() && !repository.isOffline() && promptForCredentials && (repository.getUserName() == null || repository.getPassword() == null || "".equals(repository.getUserName()) || "".equals(repository.getPassword()))) { try { EditRepositoryWizard wizard = new EditRepositoryWizard(repository); Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); if (shell != null && !shell.isDisposed()) { WizardDialog dialog = new WizardDialog(shell, wizard); dialog.create(); // dialog.setTitle("Repository Credentials Missing"); dialog.setErrorMessage("Authentication credentials missing."); dialog.setBlockOnOpen(true); if (dialog.open() == Dialog.CANCEL) { dialog.close(); return; } } } catch (Exception e) { StatusHandler.fail(e, e.getMessage(), true); } } } } public void earlyStartup() { // ignore } @Override public void stop(BundleContext context) throws Exception { try { if (ResourcesPlugin.getWorkspace() != null) { ResourcesPlugin.getWorkspace().removeSaveParticipant(this); } if (PlatformUI.isWorkbenchRunning()) { getPreferenceStore().removePropertyChangeListener(taskListNotificationManager); getPreferenceStore().removePropertyChangeListener(taskListBackupManager); getPreferenceStore().removePropertyChangeListener(taskListManager); getPreferenceStore().removePropertyChangeListener(synchronizationScheduler); getPreferenceStore().removePropertyChangeListener(PROPERTY_LISTENER); taskListManager.getTaskList().removeChangeListener(taskListSaveManager); taskListManager.dispose(); TaskListColorsAndFonts.dispose(); if (ContextCorePlugin.getDefault() != null) { ContextCorePlugin.getDefault().getPluginPreferences().removePropertyChangeListener( PREFERENCE_LISTENER); } taskEditorBloatManager.dispose(PlatformUI.getWorkbench()); INSTANCE = null; } } catch (Exception e) { StatusHandler.log(e, "Mylyn Task List stop terminated abnormally"); } finally { super.stop(context); } } public String getDefaultDataDirectory() { return ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/' + DIRECTORY_METADATA + '/' + NAME_DATA_DIR; } /** * Only attempt once per startup. */ private boolean attemptMigration = true; public synchronized String getDataDirectory() { if (attemptMigration) { migrateFromLegacyDirectory(); attemptMigration = false; } // return ContextCorePlugin.getDefault().getContextStore().getRootDirectory().getAbsolutePath(); return getPreferenceStore().getString(ContextPreferenceContstants.PREF_DATA_DIR); } @Deprecated private void migrateFromLegacyDirectory() { // Migrate .mylar data folder to .metadata/.mylyn String oldDefaultDataPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/' + ".mylar"; File oldDefaultDataDir = new File(oldDefaultDataPath); if (oldDefaultDataDir.exists()) { // && !newDefaultDataDir.exists()) { File metadata = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/' + DIRECTORY_METADATA); if (!metadata.exists()) { if (!metadata.mkdirs()) { StatusHandler.log("Unable to create metadata folder: " + metadata.getAbsolutePath(), this); } } File newDefaultDataDir = new File(getPreferenceStore().getString(ContextPreferenceContstants.PREF_DATA_DIR)); if (metadata.exists()) { if (!oldDefaultDataDir.renameTo(newDefaultDataDir)) { StatusHandler.log("Could not migrate legacy data from " + oldDefaultDataDir.getAbsolutePath() + " to " + TasksUiPlugin.getDefault().getDefaultDataDirectory(), this); } else { StatusHandler.log("Migrated legacy task data from " + oldDefaultDataDir.getAbsolutePath() + " to " + TasksUiPlugin.getDefault().getDefaultDataDirectory(), this); } } } } public void setDataDirectory(String newPath) { getTaskListManager().saveTaskList(); ContextCorePlugin.getContextManager().saveActivityContext(); getPreferenceStore().setValue(ContextPreferenceContstants.PREF_DATA_DIR, newPath); ContextCorePlugin.getDefault().getContextStore().contextStoreMoved(); } /** * Only support task data versions post 0.7 * * @param withProgress */ public void reloadDataDirectory(boolean withProgress) { getTaskListManager().getTaskActivationHistory().clear(); getRepositoryManager().readRepositories(getRepositoriesFilePath()); loadTemplateRepositories(); getTaskListManager().resetTaskList(); getTaskListManager().setTaskListFile( new File(getDataDirectory() + File.separator + ITasksUiConstants.DEFAULT_TASK_LIST_FILE)); ContextCorePlugin.getContextManager().loadActivityMetaContext(); getTaskListManager().readExistingOrCreateNewList(); getTaskListManager().initActivityHistory(); checkForCredentials(); } @Override protected void initializeDefaultPreferences(IPreferenceStore store) { store.setDefault(ContextPreferenceContstants.PREF_DATA_DIR, getDefaultDataDirectory()); store.setDefault(TasksUiPreferenceConstants.GROUP_SUBTASKS, true); store.setDefault(TasksUiPreferenceConstants.NOTIFICATIONS_ENABLED, true); store.setDefault(TasksUiPreferenceConstants.FILTER_PRIORITY, PriorityLevel.P5.toString()); store.setDefault(TasksUiPreferenceConstants.EDITOR_TASKS_RICH, true); store.setDefault(TasksUiPreferenceConstants.ACTIVATE_WHEN_OPENED, false); store.setDefault(TasksUiPreferenceConstants.SHOW_TRIM, false); store.setDefault(TasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_ENABLED, true); store.setDefault(TasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_MILISECONDS, "" + (20 * 60 * 1000)); store.setDefault(TasksUiPreferenceConstants.BACKUP_SCHEDULE, 1); store.setDefault(TasksUiPreferenceConstants.BACKUP_MAXFILES, 20); store.setDefault(TasksUiPreferenceConstants.BACKUP_LAST, 0f); store.setDefault(TasksUiPreferenceConstants.FILTER_ARCHIVE_MODE, true); store.setDefault(TasksUiPreferenceConstants.ACTIVATE_MULTIPLE, false); store.setValue(TasksUiPreferenceConstants.ACTIVATE_MULTIPLE, false); store.setDefault(TasksUiPreferenceConstants.PLANNING_STARTHOUR, 9); store.setDefault(TasksUiPreferenceConstants.PLANNING_ENDHOUR, 18); } public static TaskListManager getTaskListManager() { return taskListManager; } public static TaskActivityManager getTaskActivityManager() { return taskActivityManager; } public static TaskListNotificationManager getTaskListNotificationManager() { return INSTANCE.taskListNotificationManager; } /** * Returns the shared instance. */ public static TasksUiPlugin getDefault() { return INSTANCE; } public boolean groupSubtasks(AbstractTaskContainer container) { boolean groupSubtasks = TasksUiPlugin.getDefault().getPreferenceStore().getBoolean( TasksUiPreferenceConstants.GROUP_SUBTASKS); if (container instanceof AbstractTask) { AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(((AbstractTask) container).getConnectorKind()); if (connectorUi != null) { if (connectorUi.forceSubtaskHierarchy()) { groupSubtasks = true; } } } if (container instanceof AbstractRepositoryQuery) { AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(((AbstractRepositoryQuery) container).getRepositoryKind()); if (connectorUi != null) { if (connectorUi.forceSubtaskHierarchy()) { groupSubtasks = true; } } } return groupSubtasks; } private Map<String, List<IDynamicSubMenuContributor>> menuContributors = new HashMap<String, List<IDynamicSubMenuContributor>>(); public Map<String, List<IDynamicSubMenuContributor>> getDynamicMenuMap() { return menuContributors; } public void addDynamicPopupContributor(String menuPath, IDynamicSubMenuContributor contributor) { List<IDynamicSubMenuContributor> contributors = menuContributors.get(menuPath); if (contributors == null) { contributors = new ArrayList<IDynamicSubMenuContributor>(); menuContributors.put(menuPath, contributors); } contributors.add(contributor); } public String[] getSaveOptions() { String[] options = { TaskListSaveMode.ONE_HOUR.toString(), TaskListSaveMode.THREE_HOURS.toString(), TaskListSaveMode.DAY.toString() }; return options; } public String getBackupFolderPath() { return getDataDirectory() + DEFAULT_PATH_SEPARATOR + ITasksUiConstants.DEFAULT_BACKUP_FOLDER_NAME; } public ITaskHighlighter getHighlighter() { return highlighter; } public void setHighlighter(ITaskHighlighter highlighter) { this.highlighter = highlighter; } public Set<AbstractTaskEditorFactory> getTaskEditorFactories() { return taskEditorFactories; } public void addContextEditor(AbstractTaskEditorFactory contextEditor) { if (contextEditor != null) this.taskEditorFactories.add(contextEditor); } public static TaskRepositoryManager getRepositoryManager() { return taskRepositoryManager; } public void addBrandingIcon(String repositoryType, Image icon) { brandingIcons.put(repositoryType, icon); } public Image getBrandingIcon(String repositoryType) { return brandingIcons.get(repositoryType); } public void addOverlayIcon(String repositoryType, ImageDescriptor icon) { overlayIcons.put(repositoryType, icon); } public ImageDescriptor getOverlayIcon(String repositoryType) { return overlayIcons.get(repositoryType); } public boolean isInitialized() { return initialized; } public IHyperlinkDetector[] getTaskHyperlinkDetectors() { return hyperlinkDetectors.toArray(new IHyperlinkDetector[1]); } public void addTaskHyperlinkDetector(IHyperlinkDetector listener) { if (listener != null) this.hyperlinkDetectors.add(listener); } public void addRepositoryLinkProvider(AbstractTaskRepositoryLinkProvider repositoryLinkProvider) { if (repositoryLinkProvider != null) this.repositoryLinkProviders.add(repositoryLinkProvider); } public TaskListBackupManager getBackupManager() { return taskListBackupManager; } private void startOfflineStorageManager() { //IPath offlineReportsPath = Platform.getStateLocation(TasksUiPlugin.getDefault().getBundle()); File root = new File(this.getDataDirectory() + '/' + FOLDER_OFFLINE); OfflineFileStorage storage = new OfflineFileStorage(root); OfflineCachingStorage cachedStorage = new OfflineCachingStorage(storage); taskDataManager = new TaskDataManager(taskRepositoryManager, cachedStorage); taskDataManager.start(); } public static TaskDataManager getTaskDataManager() { if (INSTANCE == null || INSTANCE.taskDataManager == null) { StatusHandler.fail(null, "Offline reports file not created, try restarting.", true); return null; } else { return INSTANCE.taskDataManager; } } public void addRepositoryConnectorUi(AbstractRepositoryConnectorUi repositoryConnectorUi) { if (!repositoryConnectorUiMap.values().contains(repositoryConnectorUi)) { repositoryConnectorUiMap.put(repositoryConnectorUi.getConnectorKind(), repositoryConnectorUi); } } public static AbstractRepositoryConnectorUi getConnectorUi(String kind) { return repositoryConnectorUiMap.get(kind); } public static TaskListSynchronizationScheduler getSynchronizationScheduler() { return synchronizationScheduler; } public static RepositorySynchronizationManager getSynchronizationManager() { return synchronizationManager; } public void addDuplicateDetector(AbstractDuplicateDetector duplicateDetector) { if (duplicateDetector != null) { duplicateDetectors.add(duplicateDetector); } } public Set<AbstractDuplicateDetector> getDuplicateSearchCollectorsList() { return duplicateDetectors; } public String getRepositoriesFilePath() { return getDataDirectory() + File.separator + TaskRepositoryManager.DEFAULT_REPOSITORIES_FILE; } public boolean canSetRepositoryForResource(IResource resource) { if (resource == null) { return false; } // find first provider that can link repository for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { TaskRepository repository = linkProvider.getTaskRepository(resource, getRepositoryManager()); if (repository != null) { return linkProvider.canSetTaskRepository(resource); } } // find first provider that can set new repository for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { if (linkProvider.canSetTaskRepository(resource)) { return true; } } return false; } /** * Associate a Task Repository with a workbench project * * @param resource * project or resource belonging to a project * @param repository * task repository to associate with given project * @throws CoreException */ public void setRepositoryForResource(IResource resource, TaskRepository repository) throws CoreException { if (resource == null || repository == null) { return; } for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { TaskRepository r = linkProvider.getTaskRepository(resource, getRepositoryManager()); boolean canSetRepository = linkProvider.canSetTaskRepository(resource); if (r != null && !canSetRepository) { return; } if (canSetRepository) { linkProvider.setTaskRepository(resource, repository); return; } } } /** * Retrieve the task repository that has been associated with the given project (or resource belonging to a project) * * NOTE: if call does not return in LINK_PROVIDER_TIMEOUT_SECONDS, the provide will be disabled until the next time * that the Workbench starts. * * API-3.0: remove "silent" parameter */ public TaskRepository getRepositoryForResource(IResource resource, boolean silent) { if (resource == null) { return null; } Set<AbstractTaskRepositoryLinkProvider> defectiveLinkProviders = new HashSet<AbstractTaskRepositoryLinkProvider>(); for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { long startTime = System.nanoTime(); TaskRepository repository = linkProvider.getTaskRepository(resource, getRepositoryManager()); long elapsed = System.nanoTime() - startTime; if (elapsed > LINK_PROVIDER_TIMEOUT_SECONDS * 1000 * 1000 * 1000) { defectiveLinkProviders.add(linkProvider); } if (repository != null) { return repository; } } if (!defectiveLinkProviders.isEmpty()) { repositoryLinkProviders.removeAll(defectiveLinkProviders); StatusHandler.log(new Status(IStatus.WARNING, ID_PLUGIN, "Repository link provider took over 5s to execute and was timed out: " + defectiveLinkProviders)); } if (!silent) { MessageDialog.openInformation(null, "No Repository Found", "No repository was found. Associate a Task Repository with this project via the project's property page."); } return null; } /** * Public for testing. */ public static TaskListSaveManager getTaskListSaveManager() { return INSTANCE.taskListSaveManager; } public String getNextNewRepositoryTaskId() { return getTaskDataManager().getNewRepositoryTaskId(); } /** * TODO: move, uses and exposes internal class. * * @Deprecated */ public TaskListNotification getIncommingNotification(AbstractRepositoryConnector connector, AbstractTask task) { TaskListNotification notification = new TaskListNotification(task); RepositoryTaskData newTaskData = getTaskDataManager().getNewTaskData(task.getRepositoryUrl(), task.getTaskId()); RepositoryTaskData oldTaskData = getTaskDataManager().getOldTaskData(task.getRepositoryUrl(), task.getTaskId()); try { if (task.getSynchronizationState().equals(RepositoryTaskSyncState.INCOMING) && task.getLastReadTimeStamp() == null) { notification.setDescription("New unread task "); } else if (newTaskData != null && oldTaskData != null) { StringBuilder description = new StringBuilder(); String changedDescription = getChangedDescription(newTaskData, oldTaskData); - String chnagedAttributes = getChangedAttributes(newTaskData, oldTaskData); + String changedAttributes = getChangedAttributes(newTaskData, oldTaskData); if (!"".equals(changedDescription.trim())) { description.append(changedDescription); - if (!"".equals(chnagedAttributes)) { + if (!"".equals(changedAttributes)) { description.append('\n'); } } - if (!"".equals(chnagedAttributes)) { - description.append(chnagedAttributes); + if (!"".equals(changedAttributes)) { + description.append(changedAttributes); } notification.setDescription(description.toString()); if (connector != null) { AbstractTaskDataHandler offlineHandler = connector.getTaskDataHandler(); if (offlineHandler != null && newTaskData.getLastModified() != null) { Date modified = newTaskData.getAttributeFactory().getDateForAttributeType( RepositoryTaskAttribute.DATE_MODIFIED, newTaskData.getLastModified()); notification.setDate(modified); } } } else { notification.setDescription("Unread task"); } } catch (Throwable t) { StatusHandler.fail(t, "Could not format notification for: " + task, false); } return notification; } private static String getChangedDescription(RepositoryTaskData newTaskData, RepositoryTaskData oldTaskData) { String descriptionText = ""; if (newTaskData.getComments().size() > oldTaskData.getComments().size()) { List<TaskComment> taskComments = newTaskData.getComments(); if (taskComments != null && taskComments.size() > 0) { TaskComment lastComment = taskComments.get(taskComments.size() - 1); if (lastComment != null) { // descriptionText += "Comment by " + lastComment.getAuthor() + ":\n "; descriptionText += lastComment.getAuthor() + ": "; descriptionText += cleanValue(lastComment.getText()); } } } return descriptionText; } private static String getChangedAttributes(RepositoryTaskData newTaskData, RepositoryTaskData oldTaskData) { List<Change> changes = new ArrayList<Change>(); for (RepositoryTaskAttribute newAttribute : newTaskData.getAttributes()) { if (ignoreAttribute(newTaskData, newAttribute)) { continue; } List<String> newValues = newAttribute.getValues(); if (newValues != null) { RepositoryTaskAttribute oldAttribute = oldTaskData.getAttribute(newAttribute.getId()); if (oldAttribute == null) { changes.add(getDiff(newTaskData, newAttribute, null, newValues)); } if (oldAttribute != null) { List<String> oldValues = oldAttribute.getValues(); if (!oldValues.equals(newValues)) { changes.add(getDiff(newTaskData, newAttribute, oldValues, newValues)); } } } } for (RepositoryTaskAttribute oldAttribute : oldTaskData.getAttributes()) { if (ignoreAttribute(oldTaskData, oldAttribute)) { continue; } RepositoryTaskAttribute attribute = newTaskData.getAttribute(oldAttribute.getId()); List<String> values = oldAttribute.getValues(); if (attribute == null && values != null && !values.isEmpty()) { changes.add(getDiff(oldTaskData, oldAttribute, values, null)); } } if (changes.isEmpty()) { return ""; } String details = ""; String sep = ""; int n = 0; for (Change change : changes) { String removed = cleanValues(change.removed); String added = cleanValues(change.added); details += sep + " " + change.field + " " + removed; if (removed.length() > 30) { // details += "\n "; details += "\n "; } details += " -> " + added; sep = "\n"; n++; if (n > 5) { details += "\nOpen to view more changes"; break; } } // if (!details.equals("")) { // return details; // return "Attributes Changed:\n" + details; // } return details; } private static String cleanValues(List<String> values) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String value : values) { if (!first) { sb.append(", "); } sb.append(cleanValue(value)); first = false; } return sb.toString(); } private static String cleanValue(String value) { String commentText = value.replaceAll("\\s", " ").trim(); if (commentText.length() > 60) { commentText = commentText.substring(0, 55) + "..."; } return commentText; } private static boolean ignoreAttribute(RepositoryTaskData taskData, RepositoryTaskAttribute attribute) { AbstractAttributeFactory factory = taskData.getAttributeFactory(); return (attribute.getId().equals(factory.mapCommonAttributeKey(RepositoryTaskAttribute.DATE_MODIFIED)) || attribute.getId().equals(factory.mapCommonAttributeKey(RepositoryTaskAttribute.DATE_CREATION)) || "delta_ts".equals(attribute.getId()) || "longdesclength".equals(attribute.getId())); } private static Change getDiff(RepositoryTaskData taskData, RepositoryTaskAttribute attribute, List<String> oldValues, List<String> newValues) { // AbstractAttributeFactory factory = taskData.getAttributeFactory(); // if (attribute.getId().equals(factory.mapCommonAttributeKey(RepositoryTaskAttribute.DATE_MODIFIED)) // || attribute.getId().equals(factory.mapCommonAttributeKey(RepositoryTaskAttribute.DATE_CREATION))) { // if (newValues != null && newValues.size() > 0) { // for (int i = 0; i < newValues.size(); i++) { // newValues.set(i, factory.getDateForAttributeType(attribute.getId(), newValues.get(i)).toString()); // } // } // // Change change = new Change(attribute.getName(), newValues); // if (oldValues != null) { // for (String value : oldValues) { // value = factory.getDateForAttributeType(attribute.getId(), value).toString(); // if (change.added.contains(value)) { // change.added.remove(value); // } else { // change.removed.add(value); // } // } // } // return change; // } Change change = new Change(attribute.getName(), newValues); if (oldValues != null) { for (String value : oldValues) { if (change.added.contains(value)) { change.added.remove(value); } else { change.removed.add(value); } } } return change; } private static class Change { final String field; final List<String> added; final List<String> removed = new ArrayList<String>(); public Change(String field, List<String> newValues) { this.field = field; if (newValues != null) { this.added = new ArrayList<String>(newValues); } else { this.added = new ArrayList<String>(); } } } }
false
true
private void migrateFromLegacyDirectory() { // Migrate .mylar data folder to .metadata/.mylyn String oldDefaultDataPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/' + ".mylar"; File oldDefaultDataDir = new File(oldDefaultDataPath); if (oldDefaultDataDir.exists()) { // && !newDefaultDataDir.exists()) { File metadata = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/' + DIRECTORY_METADATA); if (!metadata.exists()) { if (!metadata.mkdirs()) { StatusHandler.log("Unable to create metadata folder: " + metadata.getAbsolutePath(), this); } } File newDefaultDataDir = new File(getPreferenceStore().getString(ContextPreferenceContstants.PREF_DATA_DIR)); if (metadata.exists()) { if (!oldDefaultDataDir.renameTo(newDefaultDataDir)) { StatusHandler.log("Could not migrate legacy data from " + oldDefaultDataDir.getAbsolutePath() + " to " + TasksUiPlugin.getDefault().getDefaultDataDirectory(), this); } else { StatusHandler.log("Migrated legacy task data from " + oldDefaultDataDir.getAbsolutePath() + " to " + TasksUiPlugin.getDefault().getDefaultDataDirectory(), this); } } } } public void setDataDirectory(String newPath) { getTaskListManager().saveTaskList(); ContextCorePlugin.getContextManager().saveActivityContext(); getPreferenceStore().setValue(ContextPreferenceContstants.PREF_DATA_DIR, newPath); ContextCorePlugin.getDefault().getContextStore().contextStoreMoved(); } /** * Only support task data versions post 0.7 * * @param withProgress */ public void reloadDataDirectory(boolean withProgress) { getTaskListManager().getTaskActivationHistory().clear(); getRepositoryManager().readRepositories(getRepositoriesFilePath()); loadTemplateRepositories(); getTaskListManager().resetTaskList(); getTaskListManager().setTaskListFile( new File(getDataDirectory() + File.separator + ITasksUiConstants.DEFAULT_TASK_LIST_FILE)); ContextCorePlugin.getContextManager().loadActivityMetaContext(); getTaskListManager().readExistingOrCreateNewList(); getTaskListManager().initActivityHistory(); checkForCredentials(); } @Override protected void initializeDefaultPreferences(IPreferenceStore store) { store.setDefault(ContextPreferenceContstants.PREF_DATA_DIR, getDefaultDataDirectory()); store.setDefault(TasksUiPreferenceConstants.GROUP_SUBTASKS, true); store.setDefault(TasksUiPreferenceConstants.NOTIFICATIONS_ENABLED, true); store.setDefault(TasksUiPreferenceConstants.FILTER_PRIORITY, PriorityLevel.P5.toString()); store.setDefault(TasksUiPreferenceConstants.EDITOR_TASKS_RICH, true); store.setDefault(TasksUiPreferenceConstants.ACTIVATE_WHEN_OPENED, false); store.setDefault(TasksUiPreferenceConstants.SHOW_TRIM, false); store.setDefault(TasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_ENABLED, true); store.setDefault(TasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_MILISECONDS, "" + (20 * 60 * 1000)); store.setDefault(TasksUiPreferenceConstants.BACKUP_SCHEDULE, 1); store.setDefault(TasksUiPreferenceConstants.BACKUP_MAXFILES, 20); store.setDefault(TasksUiPreferenceConstants.BACKUP_LAST, 0f); store.setDefault(TasksUiPreferenceConstants.FILTER_ARCHIVE_MODE, true); store.setDefault(TasksUiPreferenceConstants.ACTIVATE_MULTIPLE, false); store.setValue(TasksUiPreferenceConstants.ACTIVATE_MULTIPLE, false); store.setDefault(TasksUiPreferenceConstants.PLANNING_STARTHOUR, 9); store.setDefault(TasksUiPreferenceConstants.PLANNING_ENDHOUR, 18); } public static TaskListManager getTaskListManager() { return taskListManager; } public static TaskActivityManager getTaskActivityManager() { return taskActivityManager; } public static TaskListNotificationManager getTaskListNotificationManager() { return INSTANCE.taskListNotificationManager; } /** * Returns the shared instance. */ public static TasksUiPlugin getDefault() { return INSTANCE; } public boolean groupSubtasks(AbstractTaskContainer container) { boolean groupSubtasks = TasksUiPlugin.getDefault().getPreferenceStore().getBoolean( TasksUiPreferenceConstants.GROUP_SUBTASKS); if (container instanceof AbstractTask) { AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(((AbstractTask) container).getConnectorKind()); if (connectorUi != null) { if (connectorUi.forceSubtaskHierarchy()) { groupSubtasks = true; } } } if (container instanceof AbstractRepositoryQuery) { AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(((AbstractRepositoryQuery) container).getRepositoryKind()); if (connectorUi != null) { if (connectorUi.forceSubtaskHierarchy()) { groupSubtasks = true; } } } return groupSubtasks; } private Map<String, List<IDynamicSubMenuContributor>> menuContributors = new HashMap<String, List<IDynamicSubMenuContributor>>(); public Map<String, List<IDynamicSubMenuContributor>> getDynamicMenuMap() { return menuContributors; } public void addDynamicPopupContributor(String menuPath, IDynamicSubMenuContributor contributor) { List<IDynamicSubMenuContributor> contributors = menuContributors.get(menuPath); if (contributors == null) { contributors = new ArrayList<IDynamicSubMenuContributor>(); menuContributors.put(menuPath, contributors); } contributors.add(contributor); } public String[] getSaveOptions() { String[] options = { TaskListSaveMode.ONE_HOUR.toString(), TaskListSaveMode.THREE_HOURS.toString(), TaskListSaveMode.DAY.toString() }; return options; } public String getBackupFolderPath() { return getDataDirectory() + DEFAULT_PATH_SEPARATOR + ITasksUiConstants.DEFAULT_BACKUP_FOLDER_NAME; } public ITaskHighlighter getHighlighter() { return highlighter; } public void setHighlighter(ITaskHighlighter highlighter) { this.highlighter = highlighter; } public Set<AbstractTaskEditorFactory> getTaskEditorFactories() { return taskEditorFactories; } public void addContextEditor(AbstractTaskEditorFactory contextEditor) { if (contextEditor != null) this.taskEditorFactories.add(contextEditor); } public static TaskRepositoryManager getRepositoryManager() { return taskRepositoryManager; } public void addBrandingIcon(String repositoryType, Image icon) { brandingIcons.put(repositoryType, icon); } public Image getBrandingIcon(String repositoryType) { return brandingIcons.get(repositoryType); } public void addOverlayIcon(String repositoryType, ImageDescriptor icon) { overlayIcons.put(repositoryType, icon); } public ImageDescriptor getOverlayIcon(String repositoryType) { return overlayIcons.get(repositoryType); } public boolean isInitialized() { return initialized; } public IHyperlinkDetector[] getTaskHyperlinkDetectors() { return hyperlinkDetectors.toArray(new IHyperlinkDetector[1]); } public void addTaskHyperlinkDetector(IHyperlinkDetector listener) { if (listener != null) this.hyperlinkDetectors.add(listener); } public void addRepositoryLinkProvider(AbstractTaskRepositoryLinkProvider repositoryLinkProvider) { if (repositoryLinkProvider != null) this.repositoryLinkProviders.add(repositoryLinkProvider); } public TaskListBackupManager getBackupManager() { return taskListBackupManager; } private void startOfflineStorageManager() { //IPath offlineReportsPath = Platform.getStateLocation(TasksUiPlugin.getDefault().getBundle()); File root = new File(this.getDataDirectory() + '/' + FOLDER_OFFLINE); OfflineFileStorage storage = new OfflineFileStorage(root); OfflineCachingStorage cachedStorage = new OfflineCachingStorage(storage); taskDataManager = new TaskDataManager(taskRepositoryManager, cachedStorage); taskDataManager.start(); } public static TaskDataManager getTaskDataManager() { if (INSTANCE == null || INSTANCE.taskDataManager == null) { StatusHandler.fail(null, "Offline reports file not created, try restarting.", true); return null; } else { return INSTANCE.taskDataManager; } } public void addRepositoryConnectorUi(AbstractRepositoryConnectorUi repositoryConnectorUi) { if (!repositoryConnectorUiMap.values().contains(repositoryConnectorUi)) { repositoryConnectorUiMap.put(repositoryConnectorUi.getConnectorKind(), repositoryConnectorUi); } } public static AbstractRepositoryConnectorUi getConnectorUi(String kind) { return repositoryConnectorUiMap.get(kind); } public static TaskListSynchronizationScheduler getSynchronizationScheduler() { return synchronizationScheduler; } public static RepositorySynchronizationManager getSynchronizationManager() { return synchronizationManager; } public void addDuplicateDetector(AbstractDuplicateDetector duplicateDetector) { if (duplicateDetector != null) { duplicateDetectors.add(duplicateDetector); } } public Set<AbstractDuplicateDetector> getDuplicateSearchCollectorsList() { return duplicateDetectors; } public String getRepositoriesFilePath() { return getDataDirectory() + File.separator + TaskRepositoryManager.DEFAULT_REPOSITORIES_FILE; } public boolean canSetRepositoryForResource(IResource resource) { if (resource == null) { return false; } // find first provider that can link repository for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { TaskRepository repository = linkProvider.getTaskRepository(resource, getRepositoryManager()); if (repository != null) { return linkProvider.canSetTaskRepository(resource); } } // find first provider that can set new repository for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { if (linkProvider.canSetTaskRepository(resource)) { return true; } } return false; } /** * Associate a Task Repository with a workbench project * * @param resource * project or resource belonging to a project * @param repository * task repository to associate with given project * @throws CoreException */ public void setRepositoryForResource(IResource resource, TaskRepository repository) throws CoreException { if (resource == null || repository == null) { return; } for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { TaskRepository r = linkProvider.getTaskRepository(resource, getRepositoryManager()); boolean canSetRepository = linkProvider.canSetTaskRepository(resource); if (r != null && !canSetRepository) { return; } if (canSetRepository) { linkProvider.setTaskRepository(resource, repository); return; } } } /** * Retrieve the task repository that has been associated with the given project (or resource belonging to a project) * * NOTE: if call does not return in LINK_PROVIDER_TIMEOUT_SECONDS, the provide will be disabled until the next time * that the Workbench starts. * * API-3.0: remove "silent" parameter */ public TaskRepository getRepositoryForResource(IResource resource, boolean silent) { if (resource == null) { return null; } Set<AbstractTaskRepositoryLinkProvider> defectiveLinkProviders = new HashSet<AbstractTaskRepositoryLinkProvider>(); for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { long startTime = System.nanoTime(); TaskRepository repository = linkProvider.getTaskRepository(resource, getRepositoryManager()); long elapsed = System.nanoTime() - startTime; if (elapsed > LINK_PROVIDER_TIMEOUT_SECONDS * 1000 * 1000 * 1000) { defectiveLinkProviders.add(linkProvider); } if (repository != null) { return repository; } } if (!defectiveLinkProviders.isEmpty()) { repositoryLinkProviders.removeAll(defectiveLinkProviders); StatusHandler.log(new Status(IStatus.WARNING, ID_PLUGIN, "Repository link provider took over 5s to execute and was timed out: " + defectiveLinkProviders)); } if (!silent) { MessageDialog.openInformation(null, "No Repository Found", "No repository was found. Associate a Task Repository with this project via the project's property page."); } return null; } /** * Public for testing. */ public static TaskListSaveManager getTaskListSaveManager() { return INSTANCE.taskListSaveManager; } public String getNextNewRepositoryTaskId() { return getTaskDataManager().getNewRepositoryTaskId(); } /** * TODO: move, uses and exposes internal class. * * @Deprecated */ public TaskListNotification getIncommingNotification(AbstractRepositoryConnector connector, AbstractTask task) { TaskListNotification notification = new TaskListNotification(task); RepositoryTaskData newTaskData = getTaskDataManager().getNewTaskData(task.getRepositoryUrl(), task.getTaskId()); RepositoryTaskData oldTaskData = getTaskDataManager().getOldTaskData(task.getRepositoryUrl(), task.getTaskId()); try { if (task.getSynchronizationState().equals(RepositoryTaskSyncState.INCOMING) && task.getLastReadTimeStamp() == null) { notification.setDescription("New unread task "); } else if (newTaskData != null && oldTaskData != null) { StringBuilder description = new StringBuilder(); String changedDescription = getChangedDescription(newTaskData, oldTaskData); String chnagedAttributes = getChangedAttributes(newTaskData, oldTaskData); if (!"".equals(changedDescription.trim())) { description.append(changedDescription); if (!"".equals(chnagedAttributes)) { description.append('\n'); } } if (!"".equals(chnagedAttributes)) { description.append(chnagedAttributes); } notification.setDescription(description.toString()); if (connector != null) { AbstractTaskDataHandler offlineHandler = connector.getTaskDataHandler(); if (offlineHandler != null && newTaskData.getLastModified() != null) { Date modified = newTaskData.getAttributeFactory().getDateForAttributeType( RepositoryTaskAttribute.DATE_MODIFIED, newTaskData.getLastModified()); notification.setDate(modified); } } } else { notification.setDescription("Unread task"); } } catch (Throwable t) { StatusHandler.fail(t, "Could not format notification for: " + task, false); } return notification; } private static String getChangedDescription(RepositoryTaskData newTaskData, RepositoryTaskData oldTaskData) { String descriptionText = ""; if (newTaskData.getComments().size() > oldTaskData.getComments().size()) { List<TaskComment> taskComments = newTaskData.getComments(); if (taskComments != null && taskComments.size() > 0) { TaskComment lastComment = taskComments.get(taskComments.size() - 1); if (lastComment != null) { // descriptionText += "Comment by " + lastComment.getAuthor() + ":\n "; descriptionText += lastComment.getAuthor() + ": "; descriptionText += cleanValue(lastComment.getText()); } } } return descriptionText; } private static String getChangedAttributes(RepositoryTaskData newTaskData, RepositoryTaskData oldTaskData) { List<Change> changes = new ArrayList<Change>(); for (RepositoryTaskAttribute newAttribute : newTaskData.getAttributes()) { if (ignoreAttribute(newTaskData, newAttribute)) { continue; } List<String> newValues = newAttribute.getValues(); if (newValues != null) { RepositoryTaskAttribute oldAttribute = oldTaskData.getAttribute(newAttribute.getId()); if (oldAttribute == null) { changes.add(getDiff(newTaskData, newAttribute, null, newValues)); } if (oldAttribute != null) { List<String> oldValues = oldAttribute.getValues(); if (!oldValues.equals(newValues)) { changes.add(getDiff(newTaskData, newAttribute, oldValues, newValues)); } } } } for (RepositoryTaskAttribute oldAttribute : oldTaskData.getAttributes()) { if (ignoreAttribute(oldTaskData, oldAttribute)) { continue; } RepositoryTaskAttribute attribute = newTaskData.getAttribute(oldAttribute.getId()); List<String> values = oldAttribute.getValues(); if (attribute == null && values != null && !values.isEmpty()) { changes.add(getDiff(oldTaskData, oldAttribute, values, null)); } } if (changes.isEmpty()) { return ""; } String details = ""; String sep = ""; int n = 0; for (Change change : changes) { String removed = cleanValues(change.removed); String added = cleanValues(change.added); details += sep + " " + change.field + " " + removed; if (removed.length() > 30) { // details += "\n "; details += "\n "; } details += " -> " + added; sep = "\n"; n++; if (n > 5) { details += "\nOpen to view more changes"; break; } } // if (!details.equals("")) { // return details; // return "Attributes Changed:\n" + details; // } return details; } private static String cleanValues(List<String> values) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String value : values) { if (!first) { sb.append(", "); } sb.append(cleanValue(value)); first = false; } return sb.toString(); } private static String cleanValue(String value) { String commentText = value.replaceAll("\\s", " ").trim(); if (commentText.length() > 60) { commentText = commentText.substring(0, 55) + "..."; } return commentText; } private static boolean ignoreAttribute(RepositoryTaskData taskData, RepositoryTaskAttribute attribute) { AbstractAttributeFactory factory = taskData.getAttributeFactory(); return (attribute.getId().equals(factory.mapCommonAttributeKey(RepositoryTaskAttribute.DATE_MODIFIED)) || attribute.getId().equals(factory.mapCommonAttributeKey(RepositoryTaskAttribute.DATE_CREATION)) || "delta_ts".equals(attribute.getId()) || "longdesclength".equals(attribute.getId())); } private static Change getDiff(RepositoryTaskData taskData, RepositoryTaskAttribute attribute, List<String> oldValues, List<String> newValues) { // AbstractAttributeFactory factory = taskData.getAttributeFactory(); // if (attribute.getId().equals(factory.mapCommonAttributeKey(RepositoryTaskAttribute.DATE_MODIFIED)) // || attribute.getId().equals(factory.mapCommonAttributeKey(RepositoryTaskAttribute.DATE_CREATION))) { // if (newValues != null && newValues.size() > 0) { // for (int i = 0; i < newValues.size(); i++) { // newValues.set(i, factory.getDateForAttributeType(attribute.getId(), newValues.get(i)).toString()); // } // } // // Change change = new Change(attribute.getName(), newValues); // if (oldValues != null) { // for (String value : oldValues) { // value = factory.getDateForAttributeType(attribute.getId(), value).toString(); // if (change.added.contains(value)) { // change.added.remove(value); // } else { // change.removed.add(value); // } // } // } // return change; // } Change change = new Change(attribute.getName(), newValues); if (oldValues != null) { for (String value : oldValues) { if (change.added.contains(value)) { change.added.remove(value); } else { change.removed.add(value); } } } return change; } private static class Change { final String field; final List<String> added; final List<String> removed = new ArrayList<String>(); public Change(String field, List<String> newValues) { this.field = field; if (newValues != null) { this.added = new ArrayList<String>(newValues); } else { this.added = new ArrayList<String>(); } } } }
private void migrateFromLegacyDirectory() { // Migrate .mylar data folder to .metadata/.mylyn String oldDefaultDataPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/' + ".mylar"; File oldDefaultDataDir = new File(oldDefaultDataPath); if (oldDefaultDataDir.exists()) { // && !newDefaultDataDir.exists()) { File metadata = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/' + DIRECTORY_METADATA); if (!metadata.exists()) { if (!metadata.mkdirs()) { StatusHandler.log("Unable to create metadata folder: " + metadata.getAbsolutePath(), this); } } File newDefaultDataDir = new File(getPreferenceStore().getString(ContextPreferenceContstants.PREF_DATA_DIR)); if (metadata.exists()) { if (!oldDefaultDataDir.renameTo(newDefaultDataDir)) { StatusHandler.log("Could not migrate legacy data from " + oldDefaultDataDir.getAbsolutePath() + " to " + TasksUiPlugin.getDefault().getDefaultDataDirectory(), this); } else { StatusHandler.log("Migrated legacy task data from " + oldDefaultDataDir.getAbsolutePath() + " to " + TasksUiPlugin.getDefault().getDefaultDataDirectory(), this); } } } } public void setDataDirectory(String newPath) { getTaskListManager().saveTaskList(); ContextCorePlugin.getContextManager().saveActivityContext(); getPreferenceStore().setValue(ContextPreferenceContstants.PREF_DATA_DIR, newPath); ContextCorePlugin.getDefault().getContextStore().contextStoreMoved(); } /** * Only support task data versions post 0.7 * * @param withProgress */ public void reloadDataDirectory(boolean withProgress) { getTaskListManager().getTaskActivationHistory().clear(); getRepositoryManager().readRepositories(getRepositoriesFilePath()); loadTemplateRepositories(); getTaskListManager().resetTaskList(); getTaskListManager().setTaskListFile( new File(getDataDirectory() + File.separator + ITasksUiConstants.DEFAULT_TASK_LIST_FILE)); ContextCorePlugin.getContextManager().loadActivityMetaContext(); getTaskListManager().readExistingOrCreateNewList(); getTaskListManager().initActivityHistory(); checkForCredentials(); } @Override protected void initializeDefaultPreferences(IPreferenceStore store) { store.setDefault(ContextPreferenceContstants.PREF_DATA_DIR, getDefaultDataDirectory()); store.setDefault(TasksUiPreferenceConstants.GROUP_SUBTASKS, true); store.setDefault(TasksUiPreferenceConstants.NOTIFICATIONS_ENABLED, true); store.setDefault(TasksUiPreferenceConstants.FILTER_PRIORITY, PriorityLevel.P5.toString()); store.setDefault(TasksUiPreferenceConstants.EDITOR_TASKS_RICH, true); store.setDefault(TasksUiPreferenceConstants.ACTIVATE_WHEN_OPENED, false); store.setDefault(TasksUiPreferenceConstants.SHOW_TRIM, false); store.setDefault(TasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_ENABLED, true); store.setDefault(TasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_MILISECONDS, "" + (20 * 60 * 1000)); store.setDefault(TasksUiPreferenceConstants.BACKUP_SCHEDULE, 1); store.setDefault(TasksUiPreferenceConstants.BACKUP_MAXFILES, 20); store.setDefault(TasksUiPreferenceConstants.BACKUP_LAST, 0f); store.setDefault(TasksUiPreferenceConstants.FILTER_ARCHIVE_MODE, true); store.setDefault(TasksUiPreferenceConstants.ACTIVATE_MULTIPLE, false); store.setValue(TasksUiPreferenceConstants.ACTIVATE_MULTIPLE, false); store.setDefault(TasksUiPreferenceConstants.PLANNING_STARTHOUR, 9); store.setDefault(TasksUiPreferenceConstants.PLANNING_ENDHOUR, 18); } public static TaskListManager getTaskListManager() { return taskListManager; } public static TaskActivityManager getTaskActivityManager() { return taskActivityManager; } public static TaskListNotificationManager getTaskListNotificationManager() { return INSTANCE.taskListNotificationManager; } /** * Returns the shared instance. */ public static TasksUiPlugin getDefault() { return INSTANCE; } public boolean groupSubtasks(AbstractTaskContainer container) { boolean groupSubtasks = TasksUiPlugin.getDefault().getPreferenceStore().getBoolean( TasksUiPreferenceConstants.GROUP_SUBTASKS); if (container instanceof AbstractTask) { AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(((AbstractTask) container).getConnectorKind()); if (connectorUi != null) { if (connectorUi.forceSubtaskHierarchy()) { groupSubtasks = true; } } } if (container instanceof AbstractRepositoryQuery) { AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(((AbstractRepositoryQuery) container).getRepositoryKind()); if (connectorUi != null) { if (connectorUi.forceSubtaskHierarchy()) { groupSubtasks = true; } } } return groupSubtasks; } private Map<String, List<IDynamicSubMenuContributor>> menuContributors = new HashMap<String, List<IDynamicSubMenuContributor>>(); public Map<String, List<IDynamicSubMenuContributor>> getDynamicMenuMap() { return menuContributors; } public void addDynamicPopupContributor(String menuPath, IDynamicSubMenuContributor contributor) { List<IDynamicSubMenuContributor> contributors = menuContributors.get(menuPath); if (contributors == null) { contributors = new ArrayList<IDynamicSubMenuContributor>(); menuContributors.put(menuPath, contributors); } contributors.add(contributor); } public String[] getSaveOptions() { String[] options = { TaskListSaveMode.ONE_HOUR.toString(), TaskListSaveMode.THREE_HOURS.toString(), TaskListSaveMode.DAY.toString() }; return options; } public String getBackupFolderPath() { return getDataDirectory() + DEFAULT_PATH_SEPARATOR + ITasksUiConstants.DEFAULT_BACKUP_FOLDER_NAME; } public ITaskHighlighter getHighlighter() { return highlighter; } public void setHighlighter(ITaskHighlighter highlighter) { this.highlighter = highlighter; } public Set<AbstractTaskEditorFactory> getTaskEditorFactories() { return taskEditorFactories; } public void addContextEditor(AbstractTaskEditorFactory contextEditor) { if (contextEditor != null) this.taskEditorFactories.add(contextEditor); } public static TaskRepositoryManager getRepositoryManager() { return taskRepositoryManager; } public void addBrandingIcon(String repositoryType, Image icon) { brandingIcons.put(repositoryType, icon); } public Image getBrandingIcon(String repositoryType) { return brandingIcons.get(repositoryType); } public void addOverlayIcon(String repositoryType, ImageDescriptor icon) { overlayIcons.put(repositoryType, icon); } public ImageDescriptor getOverlayIcon(String repositoryType) { return overlayIcons.get(repositoryType); } public boolean isInitialized() { return initialized; } public IHyperlinkDetector[] getTaskHyperlinkDetectors() { return hyperlinkDetectors.toArray(new IHyperlinkDetector[1]); } public void addTaskHyperlinkDetector(IHyperlinkDetector listener) { if (listener != null) this.hyperlinkDetectors.add(listener); } public void addRepositoryLinkProvider(AbstractTaskRepositoryLinkProvider repositoryLinkProvider) { if (repositoryLinkProvider != null) this.repositoryLinkProviders.add(repositoryLinkProvider); } public TaskListBackupManager getBackupManager() { return taskListBackupManager; } private void startOfflineStorageManager() { //IPath offlineReportsPath = Platform.getStateLocation(TasksUiPlugin.getDefault().getBundle()); File root = new File(this.getDataDirectory() + '/' + FOLDER_OFFLINE); OfflineFileStorage storage = new OfflineFileStorage(root); OfflineCachingStorage cachedStorage = new OfflineCachingStorage(storage); taskDataManager = new TaskDataManager(taskRepositoryManager, cachedStorage); taskDataManager.start(); } public static TaskDataManager getTaskDataManager() { if (INSTANCE == null || INSTANCE.taskDataManager == null) { StatusHandler.fail(null, "Offline reports file not created, try restarting.", true); return null; } else { return INSTANCE.taskDataManager; } } public void addRepositoryConnectorUi(AbstractRepositoryConnectorUi repositoryConnectorUi) { if (!repositoryConnectorUiMap.values().contains(repositoryConnectorUi)) { repositoryConnectorUiMap.put(repositoryConnectorUi.getConnectorKind(), repositoryConnectorUi); } } public static AbstractRepositoryConnectorUi getConnectorUi(String kind) { return repositoryConnectorUiMap.get(kind); } public static TaskListSynchronizationScheduler getSynchronizationScheduler() { return synchronizationScheduler; } public static RepositorySynchronizationManager getSynchronizationManager() { return synchronizationManager; } public void addDuplicateDetector(AbstractDuplicateDetector duplicateDetector) { if (duplicateDetector != null) { duplicateDetectors.add(duplicateDetector); } } public Set<AbstractDuplicateDetector> getDuplicateSearchCollectorsList() { return duplicateDetectors; } public String getRepositoriesFilePath() { return getDataDirectory() + File.separator + TaskRepositoryManager.DEFAULT_REPOSITORIES_FILE; } public boolean canSetRepositoryForResource(IResource resource) { if (resource == null) { return false; } // find first provider that can link repository for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { TaskRepository repository = linkProvider.getTaskRepository(resource, getRepositoryManager()); if (repository != null) { return linkProvider.canSetTaskRepository(resource); } } // find first provider that can set new repository for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { if (linkProvider.canSetTaskRepository(resource)) { return true; } } return false; } /** * Associate a Task Repository with a workbench project * * @param resource * project or resource belonging to a project * @param repository * task repository to associate with given project * @throws CoreException */ public void setRepositoryForResource(IResource resource, TaskRepository repository) throws CoreException { if (resource == null || repository == null) { return; } for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { TaskRepository r = linkProvider.getTaskRepository(resource, getRepositoryManager()); boolean canSetRepository = linkProvider.canSetTaskRepository(resource); if (r != null && !canSetRepository) { return; } if (canSetRepository) { linkProvider.setTaskRepository(resource, repository); return; } } } /** * Retrieve the task repository that has been associated with the given project (or resource belonging to a project) * * NOTE: if call does not return in LINK_PROVIDER_TIMEOUT_SECONDS, the provide will be disabled until the next time * that the Workbench starts. * * API-3.0: remove "silent" parameter */ public TaskRepository getRepositoryForResource(IResource resource, boolean silent) { if (resource == null) { return null; } Set<AbstractTaskRepositoryLinkProvider> defectiveLinkProviders = new HashSet<AbstractTaskRepositoryLinkProvider>(); for (AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) { long startTime = System.nanoTime(); TaskRepository repository = linkProvider.getTaskRepository(resource, getRepositoryManager()); long elapsed = System.nanoTime() - startTime; if (elapsed > LINK_PROVIDER_TIMEOUT_SECONDS * 1000 * 1000 * 1000) { defectiveLinkProviders.add(linkProvider); } if (repository != null) { return repository; } } if (!defectiveLinkProviders.isEmpty()) { repositoryLinkProviders.removeAll(defectiveLinkProviders); StatusHandler.log(new Status(IStatus.WARNING, ID_PLUGIN, "Repository link provider took over 5s to execute and was timed out: " + defectiveLinkProviders)); } if (!silent) { MessageDialog.openInformation(null, "No Repository Found", "No repository was found. Associate a Task Repository with this project via the project's property page."); } return null; } /** * Public for testing. */ public static TaskListSaveManager getTaskListSaveManager() { return INSTANCE.taskListSaveManager; } public String getNextNewRepositoryTaskId() { return getTaskDataManager().getNewRepositoryTaskId(); } /** * TODO: move, uses and exposes internal class. * * @Deprecated */ public TaskListNotification getIncommingNotification(AbstractRepositoryConnector connector, AbstractTask task) { TaskListNotification notification = new TaskListNotification(task); RepositoryTaskData newTaskData = getTaskDataManager().getNewTaskData(task.getRepositoryUrl(), task.getTaskId()); RepositoryTaskData oldTaskData = getTaskDataManager().getOldTaskData(task.getRepositoryUrl(), task.getTaskId()); try { if (task.getSynchronizationState().equals(RepositoryTaskSyncState.INCOMING) && task.getLastReadTimeStamp() == null) { notification.setDescription("New unread task "); } else if (newTaskData != null && oldTaskData != null) { StringBuilder description = new StringBuilder(); String changedDescription = getChangedDescription(newTaskData, oldTaskData); String changedAttributes = getChangedAttributes(newTaskData, oldTaskData); if (!"".equals(changedDescription.trim())) { description.append(changedDescription); if (!"".equals(changedAttributes)) { description.append('\n'); } } if (!"".equals(changedAttributes)) { description.append(changedAttributes); } notification.setDescription(description.toString()); if (connector != null) { AbstractTaskDataHandler offlineHandler = connector.getTaskDataHandler(); if (offlineHandler != null && newTaskData.getLastModified() != null) { Date modified = newTaskData.getAttributeFactory().getDateForAttributeType( RepositoryTaskAttribute.DATE_MODIFIED, newTaskData.getLastModified()); notification.setDate(modified); } } } else { notification.setDescription("Unread task"); } } catch (Throwable t) { StatusHandler.fail(t, "Could not format notification for: " + task, false); } return notification; } private static String getChangedDescription(RepositoryTaskData newTaskData, RepositoryTaskData oldTaskData) { String descriptionText = ""; if (newTaskData.getComments().size() > oldTaskData.getComments().size()) { List<TaskComment> taskComments = newTaskData.getComments(); if (taskComments != null && taskComments.size() > 0) { TaskComment lastComment = taskComments.get(taskComments.size() - 1); if (lastComment != null) { // descriptionText += "Comment by " + lastComment.getAuthor() + ":\n "; descriptionText += lastComment.getAuthor() + ": "; descriptionText += cleanValue(lastComment.getText()); } } } return descriptionText; } private static String getChangedAttributes(RepositoryTaskData newTaskData, RepositoryTaskData oldTaskData) { List<Change> changes = new ArrayList<Change>(); for (RepositoryTaskAttribute newAttribute : newTaskData.getAttributes()) { if (ignoreAttribute(newTaskData, newAttribute)) { continue; } List<String> newValues = newAttribute.getValues(); if (newValues != null) { RepositoryTaskAttribute oldAttribute = oldTaskData.getAttribute(newAttribute.getId()); if (oldAttribute == null) { changes.add(getDiff(newTaskData, newAttribute, null, newValues)); } if (oldAttribute != null) { List<String> oldValues = oldAttribute.getValues(); if (!oldValues.equals(newValues)) { changes.add(getDiff(newTaskData, newAttribute, oldValues, newValues)); } } } } for (RepositoryTaskAttribute oldAttribute : oldTaskData.getAttributes()) { if (ignoreAttribute(oldTaskData, oldAttribute)) { continue; } RepositoryTaskAttribute attribute = newTaskData.getAttribute(oldAttribute.getId()); List<String> values = oldAttribute.getValues(); if (attribute == null && values != null && !values.isEmpty()) { changes.add(getDiff(oldTaskData, oldAttribute, values, null)); } } if (changes.isEmpty()) { return ""; } String details = ""; String sep = ""; int n = 0; for (Change change : changes) { String removed = cleanValues(change.removed); String added = cleanValues(change.added); details += sep + " " + change.field + " " + removed; if (removed.length() > 30) { // details += "\n "; details += "\n "; } details += " -> " + added; sep = "\n"; n++; if (n > 5) { details += "\nOpen to view more changes"; break; } } // if (!details.equals("")) { // return details; // return "Attributes Changed:\n" + details; // } return details; } private static String cleanValues(List<String> values) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String value : values) { if (!first) { sb.append(", "); } sb.append(cleanValue(value)); first = false; } return sb.toString(); } private static String cleanValue(String value) { String commentText = value.replaceAll("\\s", " ").trim(); if (commentText.length() > 60) { commentText = commentText.substring(0, 55) + "..."; } return commentText; } private static boolean ignoreAttribute(RepositoryTaskData taskData, RepositoryTaskAttribute attribute) { AbstractAttributeFactory factory = taskData.getAttributeFactory(); return (attribute.getId().equals(factory.mapCommonAttributeKey(RepositoryTaskAttribute.DATE_MODIFIED)) || attribute.getId().equals(factory.mapCommonAttributeKey(RepositoryTaskAttribute.DATE_CREATION)) || "delta_ts".equals(attribute.getId()) || "longdesclength".equals(attribute.getId())); } private static Change getDiff(RepositoryTaskData taskData, RepositoryTaskAttribute attribute, List<String> oldValues, List<String> newValues) { // AbstractAttributeFactory factory = taskData.getAttributeFactory(); // if (attribute.getId().equals(factory.mapCommonAttributeKey(RepositoryTaskAttribute.DATE_MODIFIED)) // || attribute.getId().equals(factory.mapCommonAttributeKey(RepositoryTaskAttribute.DATE_CREATION))) { // if (newValues != null && newValues.size() > 0) { // for (int i = 0; i < newValues.size(); i++) { // newValues.set(i, factory.getDateForAttributeType(attribute.getId(), newValues.get(i)).toString()); // } // } // // Change change = new Change(attribute.getName(), newValues); // if (oldValues != null) { // for (String value : oldValues) { // value = factory.getDateForAttributeType(attribute.getId(), value).toString(); // if (change.added.contains(value)) { // change.added.remove(value); // } else { // change.removed.add(value); // } // } // } // return change; // } Change change = new Change(attribute.getName(), newValues); if (oldValues != null) { for (String value : oldValues) { if (change.added.contains(value)) { change.added.remove(value); } else { change.removed.add(value); } } } return change; } private static class Change { final String field; final List<String> added; final List<String> removed = new ArrayList<String>(); public Change(String field, List<String> newValues) { this.field = field; if (newValues != null) { this.added = new ArrayList<String>(newValues); } else { this.added = new ArrayList<String>(); } } } }
diff --git a/src/net/sf/hajdbc/util/concurrent/CronThreadPoolExecutor.java b/src/net/sf/hajdbc/util/concurrent/CronThreadPoolExecutor.java index ae04771e..184cdb36 100644 --- a/src/net/sf/hajdbc/util/concurrent/CronThreadPoolExecutor.java +++ b/src/net/sf/hajdbc/util/concurrent/CronThreadPoolExecutor.java @@ -1,117 +1,117 @@ /* * HA-JDBC: High-Availability JDBC * Copyright (c) 2004-2007 Paul Ferraro * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact: [email protected] */ package net.sf.hajdbc.util.concurrent; import java.util.Date; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.quartz.CronExpression; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Scheduled thread-pool executor implementation that leverages a Quartz CronExpression to calculate future execution times for scheduled tasks. * * @author Paul Ferraro * @since 1.1 */ public class CronThreadPoolExecutor extends ScheduledThreadPoolExecutor implements CronExecutorService { protected static Logger logger = LoggerFactory.getLogger(CronThreadPoolExecutor.class); /** * Constructs a new CronThreadPoolExecutor. * @param corePoolSize * @param handler */ public CronThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler) { super(corePoolSize, DaemonThreadFactory.getInstance(), handler); } /** * Constructs a new CronThreadPoolExecutor. * @param corePoolSize */ public CronThreadPoolExecutor(int corePoolSize) { super(corePoolSize, DaemonThreadFactory.getInstance()); } /** * @see net.sf.hajdbc.util.concurrent.CronExecutorService#schedule(java.lang.Runnable, org.quartz.CronExpression) */ public void schedule(final Runnable task, final CronExpression expression) { if (task == null) throw new NullPointerException(); this.setCorePoolSize(this.getCorePoolSize() + 1); Runnable scheduleTask = new Runnable() { /** * @see java.lang.Runnable#run() */ public void run() { Date time = expression.getNextValidTimeAfter(new Date()); try { while (time != null) { long delay = Math.max(time.getTime() - System.currentTimeMillis(), 0); try { CronThreadPoolExecutor.this.schedule(task, delay, TimeUnit.MILLISECONDS).get(); time = expression.getNextValidTimeAfter(new Date()); } catch (ExecutionException e) { logger.warn(e.toString(), e.getCause()); } } } catch (RejectedExecutionException e) { // Occurs if executor was already shutdown when schedule() is called } catch (CancellationException e) { - // Occurs when scheduled, but not yet executed tasks are cancelled during shutdown + // Occurs when scheduled, but not yet executed tasks are canceled during shutdown } catch (InterruptedException e) { // Occurs when executing tasks are interrupted during shutdownNow() } } }; this.execute(scheduleTask); } }
true
true
public void schedule(final Runnable task, final CronExpression expression) { if (task == null) throw new NullPointerException(); this.setCorePoolSize(this.getCorePoolSize() + 1); Runnable scheduleTask = new Runnable() { /** * @see java.lang.Runnable#run() */ public void run() { Date time = expression.getNextValidTimeAfter(new Date()); try { while (time != null) { long delay = Math.max(time.getTime() - System.currentTimeMillis(), 0); try { CronThreadPoolExecutor.this.schedule(task, delay, TimeUnit.MILLISECONDS).get(); time = expression.getNextValidTimeAfter(new Date()); } catch (ExecutionException e) { logger.warn(e.toString(), e.getCause()); } } } catch (RejectedExecutionException e) { // Occurs if executor was already shutdown when schedule() is called } catch (CancellationException e) { // Occurs when scheduled, but not yet executed tasks are cancelled during shutdown } catch (InterruptedException e) { // Occurs when executing tasks are interrupted during shutdownNow() } } }; this.execute(scheduleTask); }
public void schedule(final Runnable task, final CronExpression expression) { if (task == null) throw new NullPointerException(); this.setCorePoolSize(this.getCorePoolSize() + 1); Runnable scheduleTask = new Runnable() { /** * @see java.lang.Runnable#run() */ public void run() { Date time = expression.getNextValidTimeAfter(new Date()); try { while (time != null) { long delay = Math.max(time.getTime() - System.currentTimeMillis(), 0); try { CronThreadPoolExecutor.this.schedule(task, delay, TimeUnit.MILLISECONDS).get(); time = expression.getNextValidTimeAfter(new Date()); } catch (ExecutionException e) { logger.warn(e.toString(), e.getCause()); } } } catch (RejectedExecutionException e) { // Occurs if executor was already shutdown when schedule() is called } catch (CancellationException e) { // Occurs when scheduled, but not yet executed tasks are canceled during shutdown } catch (InterruptedException e) { // Occurs when executing tasks are interrupted during shutdownNow() } } }; this.execute(scheduleTask); }
diff --git a/src/sofia/internal/JarResources.java b/src/sofia/internal/JarResources.java index 5dbee62..d944e9b 100644 --- a/src/sofia/internal/JarResources.java +++ b/src/sofia/internal/JarResources.java @@ -1,221 +1,218 @@ package sofia.internal; import java.io.InputStream; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.DisplayMetrics; /** * <p> * Since we want to distribute Sofia as a single JAR (or a set of JARs), we * cannot make use of the standard Android resource structure that regular * APKs use, because all of the resources would have to be copied into the * application projects. * </p><p> * Instead, for things like images, we store them embedded in the JARs, and * this class provides a better interface for accessing them. * </p> * * @author Tony Allevato * @author Last changed by $Author: edwards $ * @version $Date: 2012/08/04 15:52 $ */ public class JarResources { //~ Methods ............................................................... // ---------------------------------------------------------- /** * Get an image resource by name, taking the current device's DPI into * account. The image may be a traditional Android resource, in which * case the normal resource mechanism is used to look it up, or it may * be stored in the application/context package. If stored in the * application's package, the package should have a subpackage named * "images", with one or more of its own subpackages that match the DPI * identifiers used in resources: "ldpi", "mdpi", "hdpi", and/or "xhdpi". * Image files are held in these dpi-based subpackages. The "images" * subpackage itself will also be searched, with images it contains * treated at the same DPI as the device. * * @param context The context for determining the display resolution, * and also the application's package. * @param name The name of the image file, including its extension. * @return A {@code Bitmap} containing the image, or null if no * image could be found. */ public static Bitmap getBitmap(Context context, String name) { return getBitmap(context, null, name); } // ---------------------------------------------------------- /** * Get an image resource by name, taking the current device's DPI into * account. The image may be a traditional Android resource, in which * case the normal resource mechanism is used to look it up, or it may * be stored in the application/context package. If stored in a package * relative to the specified class (or application). The package * containing the class parameter should have a subpackage named "images", * with one or more of its own subpackages that match the DPI identifiers * used in resources: "ldpi", "mdpi", "hdpi", and/or "xhdpi". Image files * are held in these dpi-based subpackages. The "images" subpackage * itself will also be searched, with images it contains treated at the * same DPI as the device. * * @param context The context for determining the display resolution, * and also the application's package, if the image isn't * found in package of the specified klass. * @param klass The class representing the package where the images are * located. The search will also look in the application * package determined by the context if no image is found * with respect to klass' package (or if klass is null). * @param name The name of the image file, including its extension. * @return An {@code Bitmap} containing the image, or null if no * image could be found. */ public static Bitmap getBitmap( Context context, Class<?> klass, String name) { // First, try for a resource by this name: - if (klass != null) + int id = context.getResources().getIdentifier( + name, "drawable", context.getPackageName()); + if (id != 0) { - int id = context.getResources().getIdentifier( - name, "drawable", context.getPackageName()); - if (id != 0) - { - return BitmapFactory.decodeResource( - context.getResources(), id); - } + return BitmapFactory.decodeResource( + context.getResources(), id); } // If no resource was found ... DisplayMetrics metrics = context.getResources().getDisplayMetrics(); int foundDensity = -1; // Pattern is declared outside the loop because it is intended to // be used after the loop int pattern = 0; for (; pattern < CUTOFF.length; pattern++) { if (metrics.densityDpi < CUTOFF[pattern]) { break; } } // pattern now contains the search pattern, 0-3. If no pattern // was found in CUTOFF, pattern == CUTOFF.length == 3, which // defaults to the xhdpi pattern. // First, try to find image using the package of the given class InputStream stream = null; if (klass != null) { for (int attempt : SEARCH_PATTERN[pattern]) { stream = klass.getResourceAsStream( "images/" + DENSITY_NAME[attempt] + "/" + name); if (stream != null) { foundDensity = attempt; break; } } if (stream == null) { // If we make it here, try for the default (no density) name stream = klass.getResourceAsStream("images/" + name); } } if (stream == null) { // OK, now search using the app/context package instead of // klass' package String base = context.getPackageName().replace('.', '/'); if (!base.endsWith("/")) { base += "/"; } base += "images/"; ClassLoader loader = (klass == null) ? JarResources.class.getClassLoader() : klass.getClass().getClassLoader(); for (int attempt : SEARCH_PATTERN[pattern]) { stream = loader.getResourceAsStream( base + DENSITY_NAME[attempt] + "/" + name); if (stream != null) { foundDensity = attempt; break; } } if (stream == null) { // If we make it here, try for the default (no density) name stream = loader.getResourceAsStream(base + name); } } Bitmap result = null; if (stream != null) { result = BitmapFactory.decodeStream(stream); if (foundDensity >= 0) { result.setDensity(DENSITY[foundDensity]); } } return result; } // Map from ints 0-3 to corresponding density names here private static final String[] DENSITY_NAME = { "ldpi", "mdpi", "hdpi", "xhdpi" }; // constants for the int codes private static final int LDPI = 0; private static final int MDPI = 1; private static final int HDPI = 2; private static final int XHDPI = 3; // DPI density for each name private static final int[] DENSITY = { 120, 160, 240, 320 }; // See http://developer.android.com/guide/practices/screens_support.html // Values based on info in Table 1 on that page. private static final int[] CUTOFF = { 140, // upper limit for ldpi, which is ~120dpi 200, // upper limit for mdpi, which is ~160dpi 280 // upper limit for hdpi, which is ~240dpi // 400 is upper limit for xhdpi, which is ~320dpi // don't worry about xxhigh, since xhdpi should scale well }; // Search starts with the preferred resolution, and then goes high-to-low // on the assumption that higher res images scale down better than // attempting to scale up lower res images. private static final int[][] SEARCH_PATTERN = { { LDPI, XHDPI, HDPI, MDPI }, // for ldpi screens { MDPI, XHDPI, HDPI, LDPI }, // for mdpi screens { HDPI, XHDPI, MDPI, LDPI }, // for hdpi screens { XHDPI, HDPI, MDPI, LDPI } // for xhdpi screens }; }
false
true
public static Bitmap getBitmap( Context context, Class<?> klass, String name) { // First, try for a resource by this name: if (klass != null) { int id = context.getResources().getIdentifier( name, "drawable", context.getPackageName()); if (id != 0) { return BitmapFactory.decodeResource( context.getResources(), id); } } // If no resource was found ... DisplayMetrics metrics = context.getResources().getDisplayMetrics(); int foundDensity = -1; // Pattern is declared outside the loop because it is intended to // be used after the loop int pattern = 0; for (; pattern < CUTOFF.length; pattern++) { if (metrics.densityDpi < CUTOFF[pattern]) { break; } } // pattern now contains the search pattern, 0-3. If no pattern // was found in CUTOFF, pattern == CUTOFF.length == 3, which // defaults to the xhdpi pattern. // First, try to find image using the package of the given class InputStream stream = null; if (klass != null) { for (int attempt : SEARCH_PATTERN[pattern]) { stream = klass.getResourceAsStream( "images/" + DENSITY_NAME[attempt] + "/" + name); if (stream != null) { foundDensity = attempt; break; } } if (stream == null) { // If we make it here, try for the default (no density) name stream = klass.getResourceAsStream("images/" + name); } } if (stream == null) { // OK, now search using the app/context package instead of // klass' package String base = context.getPackageName().replace('.', '/'); if (!base.endsWith("/")) { base += "/"; } base += "images/"; ClassLoader loader = (klass == null) ? JarResources.class.getClassLoader() : klass.getClass().getClassLoader(); for (int attempt : SEARCH_PATTERN[pattern]) { stream = loader.getResourceAsStream( base + DENSITY_NAME[attempt] + "/" + name); if (stream != null) { foundDensity = attempt; break; } } if (stream == null) { // If we make it here, try for the default (no density) name stream = loader.getResourceAsStream(base + name); } } Bitmap result = null; if (stream != null) { result = BitmapFactory.decodeStream(stream); if (foundDensity >= 0) { result.setDensity(DENSITY[foundDensity]); } } return result; }
public static Bitmap getBitmap( Context context, Class<?> klass, String name) { // First, try for a resource by this name: int id = context.getResources().getIdentifier( name, "drawable", context.getPackageName()); if (id != 0) { return BitmapFactory.decodeResource( context.getResources(), id); } // If no resource was found ... DisplayMetrics metrics = context.getResources().getDisplayMetrics(); int foundDensity = -1; // Pattern is declared outside the loop because it is intended to // be used after the loop int pattern = 0; for (; pattern < CUTOFF.length; pattern++) { if (metrics.densityDpi < CUTOFF[pattern]) { break; } } // pattern now contains the search pattern, 0-3. If no pattern // was found in CUTOFF, pattern == CUTOFF.length == 3, which // defaults to the xhdpi pattern. // First, try to find image using the package of the given class InputStream stream = null; if (klass != null) { for (int attempt : SEARCH_PATTERN[pattern]) { stream = klass.getResourceAsStream( "images/" + DENSITY_NAME[attempt] + "/" + name); if (stream != null) { foundDensity = attempt; break; } } if (stream == null) { // If we make it here, try for the default (no density) name stream = klass.getResourceAsStream("images/" + name); } } if (stream == null) { // OK, now search using the app/context package instead of // klass' package String base = context.getPackageName().replace('.', '/'); if (!base.endsWith("/")) { base += "/"; } base += "images/"; ClassLoader loader = (klass == null) ? JarResources.class.getClassLoader() : klass.getClass().getClassLoader(); for (int attempt : SEARCH_PATTERN[pattern]) { stream = loader.getResourceAsStream( base + DENSITY_NAME[attempt] + "/" + name); if (stream != null) { foundDensity = attempt; break; } } if (stream == null) { // If we make it here, try for the default (no density) name stream = loader.getResourceAsStream(base + name); } } Bitmap result = null; if (stream != null) { result = BitmapFactory.decodeStream(stream); if (foundDensity >= 0) { result.setDensity(DENSITY[foundDensity]); } } return result; }
diff --git a/server/src/main/java/io/druid/segment/realtime/plumber/Sink.java b/server/src/main/java/io/druid/segment/realtime/plumber/Sink.java index 91edc45e26..e2759406ee 100644 --- a/server/src/main/java/io/druid/segment/realtime/plumber/Sink.java +++ b/server/src/main/java/io/druid/segment/realtime/plumber/Sink.java @@ -1,219 +1,219 @@ /* * Druid - a distributed column store. * Copyright (C) 2012, 2013 Metamarkets Group 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 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package io.druid.segment.realtime.plumber; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.metamx.common.IAE; import com.metamx.common.ISE; import com.metamx.common.logger.Logger; import io.druid.data.input.InputRow; import io.druid.query.aggregation.AggregatorFactory; import io.druid.segment.incremental.IncrementalIndex; import io.druid.segment.incremental.IncrementalIndexSchema; import io.druid.segment.realtime.FireHydrant; import io.druid.segment.realtime.Schema; import io.druid.timeline.DataSegment; import org.joda.time.Interval; import javax.annotation.Nullable; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** */ public class Sink implements Iterable<FireHydrant> { private static final Logger log = new Logger(Sink.class); private volatile FireHydrant currIndex; private final Interval interval; private final Schema schema; private final String version; private final CopyOnWriteArrayList<FireHydrant> hydrants = new CopyOnWriteArrayList<FireHydrant>(); public Sink( Interval interval, Schema schema, String version ) { this.schema = schema; this.interval = interval; this.version = version; makeNewCurrIndex(interval.getStartMillis(), schema); } public Sink( Interval interval, Schema schema, String version, List<FireHydrant> hydrants ) { this.schema = schema; this.interval = interval; this.version = version; for (int i = 0; i < hydrants.size(); ++i) { final FireHydrant hydrant = hydrants.get(i); if (hydrant.getCount() != i) { throw new ISE("hydrant[%s] not the right count[%s]", hydrant, i); } } this.hydrants.addAll(hydrants); makeNewCurrIndex(interval.getStartMillis(), schema); } public String getVersion() { return version; } public Interval getInterval() { return interval; } public FireHydrant getCurrIndex() { return currIndex; } public int add(InputRow row) { if (currIndex == null) { throw new IAE("No currIndex but given row[%s]", row); } synchronized (currIndex) { return currIndex.getIndex().add(row); } } public boolean isEmpty() { synchronized (currIndex) { return hydrants.size() == 1 && currIndex.getIndex().isEmpty(); } } /** * If currIndex is A, creates a new index B, sets currIndex to B and returns A. * * @return the current index after swapping in a new one */ public FireHydrant swap() { return makeNewCurrIndex(interval.getStartMillis(), schema); } public boolean swappable() { synchronized (currIndex) { return currIndex.getIndex() != null && currIndex.getIndex().size() != 0; } } public DataSegment getSegment() { return new DataSegment( schema.getDataSource(), interval, version, ImmutableMap.<String, Object>of(), Lists.<String>newArrayList(), Lists.transform( Arrays.asList(schema.getAggregators()), new Function<AggregatorFactory, String>() { @Override public String apply(@Nullable AggregatorFactory input) { return input.getName(); } } ), schema.getShardSpec(), null, 0 ); } private FireHydrant makeNewCurrIndex(long minTimestamp, Schema schema) { IncrementalIndex newIndex = new IncrementalIndex( new IncrementalIndexSchema.Builder() .withMinTimestamp(minTimestamp) .withQueryGranularity(schema.getIndexGranularity()) .withSpatialDimensions(schema.getSpatialDimensions()) .withMetrics(schema.getAggregators()) .build() ); FireHydrant old; if (currIndex == null) { // Only happens on initialization, cannot synchronize on null old = currIndex; - currIndex = new FireHydrant(newIndex, hydrants.size(), version); + currIndex = new FireHydrant(newIndex, hydrants.size(), getSegment().getIdentifier()); hydrants.add(currIndex); } else { synchronized (currIndex) { old = currIndex; - currIndex = new FireHydrant(newIndex, hydrants.size(), version); + currIndex = new FireHydrant(newIndex, hydrants.size(), getSegment().getIdentifier()); hydrants.add(currIndex); } } return old; } @Override public Iterator<FireHydrant> iterator() { return Iterators.filter( hydrants.iterator(), new Predicate<FireHydrant>() { @Override public boolean apply(@Nullable FireHydrant input) { final IncrementalIndex index = input.getIndex(); return index == null || index.size() != 0; } } ); } @Override public String toString() { return "Sink{" + "interval=" + interval + ", schema=" + schema + '}'; } }
false
true
private FireHydrant makeNewCurrIndex(long minTimestamp, Schema schema) { IncrementalIndex newIndex = new IncrementalIndex( new IncrementalIndexSchema.Builder() .withMinTimestamp(minTimestamp) .withQueryGranularity(schema.getIndexGranularity()) .withSpatialDimensions(schema.getSpatialDimensions()) .withMetrics(schema.getAggregators()) .build() ); FireHydrant old; if (currIndex == null) { // Only happens on initialization, cannot synchronize on null old = currIndex; currIndex = new FireHydrant(newIndex, hydrants.size(), version); hydrants.add(currIndex); } else { synchronized (currIndex) { old = currIndex; currIndex = new FireHydrant(newIndex, hydrants.size(), version); hydrants.add(currIndex); } } return old; }
private FireHydrant makeNewCurrIndex(long minTimestamp, Schema schema) { IncrementalIndex newIndex = new IncrementalIndex( new IncrementalIndexSchema.Builder() .withMinTimestamp(minTimestamp) .withQueryGranularity(schema.getIndexGranularity()) .withSpatialDimensions(schema.getSpatialDimensions()) .withMetrics(schema.getAggregators()) .build() ); FireHydrant old; if (currIndex == null) { // Only happens on initialization, cannot synchronize on null old = currIndex; currIndex = new FireHydrant(newIndex, hydrants.size(), getSegment().getIdentifier()); hydrants.add(currIndex); } else { synchronized (currIndex) { old = currIndex; currIndex = new FireHydrant(newIndex, hydrants.size(), getSegment().getIdentifier()); hydrants.add(currIndex); } } return old; }
diff --git a/MipsCompiler/src/mainCompiler.java b/MipsCompiler/src/mainCompiler.java index 05553ef..3a2d798 100644 --- a/MipsCompiler/src/mainCompiler.java +++ b/MipsCompiler/src/mainCompiler.java @@ -1,689 +1,689 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import java.util.regex.*; import java.lang.String; /** * * @author Troxel */ public class mainCompiler { /** * @param args * the command line arguments */ public static void main(String[] args) { // TODO code application logic here String labelRegex = "^[a-zA-Z_]+:"; Pattern label = Pattern.compile(labelRegex); Pattern register = Pattern.compile("^\\$[0-9]?[0-9]"); HashMap labelLoc = new HashMap(); int instCount = 0; int byteLine = 0; int lastByte = 0; int maxMem = 0; ArrayList<int[]> memplacement = new ArrayList<int[]>(); String filename = ""; try { filename = args[0]; } catch (Exception e) { Scanner consolein = new Scanner(System.in); System.out .println("Give the path or filename of source code to compile:"); filename = consolein.next(); consolein.close(); } boolean data = false; File infile = new File(filename); String[] tempParams = infile.getName().split("\\.(?=[^\\.]+$)"); String temp = tempParams[0]; File exeFile = new File(temp + ".exe.mif"); File memFile = new File(temp + ".mem.mif"); // Create file if it doesn't already exist try { exeFile.createNewFile(); Scanner input = new Scanner(infile); FileWriter fw; FileWriter memfw; try { String instruction = ""; int code = 0; ArrayList<String> instructionLines = new ArrayList<String>(); ArrayList<String> origInstruction = new ArrayList<String>(); ArrayList<String[]> Symbols = new ArrayList<String[]>(); String parameters = ""; String[] params; int index; int lineNum = 0; // initialize memory file writers memfw = new FileWriter(memFile); PrintWriter mempw = new PrintWriter(memfw); mempw.print("WIDTH = 32; \r\n-- data width \r\n" + "DEPTH = 256; \r\n-- number of memory slots \r\n" + "-- thus, the total size is 256 x 32 bits\r\n" + "ADDRESS_RADIX = HEX; \r\nDATA_RADIX = HEX; \r\n" + "CONTENT BEGIN \r\n"); // initialize executable file writers fw = new FileWriter(exeFile); PrintWriter pw = new PrintWriter(fw); pw.print("WIDTH = 32; \r\n-- data width \r\n" + "DEPTH = 256; \r\n-- number of memory slots \r\n" + "-- thus, the total size is 256 x 32 bits\r\n" + "ADDRESS_RADIX = HEX; \r\nDATA_RADIX = HEX; \r\n" + "CONTENT BEGIN \r\n"); code = 0; // start reading the file while (input.hasNextLine()) { params = input.nextLine().split("#"); if (params.length > 0) { instruction = params[0].trim(); } else { instruction = ""; } if (instruction.contains(".data")) { data = true; lineNum++; instCount++; byteLine = 0; } if (!data) { if (instruction.contains(":")) { params = instruction.split(":"); index = ContainsSymbol(Symbols, params[0].trim()); if (index > -1) { if (Symbols.get(index)[1].contains("-1")) { Symbols.set( index, new String[] { params[0].trim(), String.valueOf(lineNum * 4) }); } else { System.out.println("Symbol error (Line: " + lineNum + "): Symbol already exists."); } } else { Symbols.add(new String[] { params[0], String.valueOf(lineNum * 4) }); } if (params.length > 1) { instruction = params[1].trim(); } else { instruction = ""; } } if (instruction.length() > 0) { instructionLines.add(instruction); origInstruction.add(instruction); parameters = instruction.split(" ", 2)[1].trim(); params = parameters.split(","); for (int i = 0; i < params.length; i++) { if (!(params[i].trim().startsWith("$")) && !isNumber(params[i].trim())) { index = ContainsSymbol(Symbols, params[i].trim()); if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1] .contains("-1")) { instructionLines .set(lineNum, instructionLines .get(lineNum) .replace( Symbols.get(index)[0], Symbols.get(index)[1])); } } else { Symbols.add(new String[] { params[i].trim(), "-1" }); } } } lineNum++; instCount++; } } else { if (instruction.contains(":")) { params = instruction.split(":"); index = ContainsSymbol(Symbols, params[0].trim()); if (index > -1) { if (Symbols.get(index)[1].contains("-1")) { Symbols.set(index, new String[] { params[0].trim(), - String.valueOf(byteLine) }); + String.valueOf(byteLine/4) }); } else { System.out.println("Symbol error (Line: " + lineNum + "): Symbol already exists."); } } else { Symbols.add(new String[] { params[0], - String.valueOf(byteLine) }); + String.valueOf(byteLine/4) }); } if (params.length > 1) { instruction = params[1].trim(); } else { instruction = ""; } } if (instruction.length() > 0) { params = instruction.split(" ", 2); switch (params[0]) { case ".ascii": temp = params[0].replaceAll("\"", ""); for (int i = 0; i < temp.length(); i++) { code |= ((byte) temp.charAt(i)) << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } } break; case ".byte": code |= Integer.valueOf(params[1].trim()) .intValue() << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } break; case ".asciiz": temp = params[1].replaceAll("\"", "") + ((char) (0)); for (int i = 0; i < temp.length(); i++) { code |= ((byte) temp.charAt(i)) << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } } break; case "org": memplacement.add(new int[] { byteLine - byteLine % 4, code }); code = 0; byteLine = Integer.valueOf(params[1].trim()) .intValue(); break; default: } } } } if (byteLine % 4 != 0 && byteLine - 4 != lastByte) { memplacement.add(new int[] { byteLine - (byteLine % 4), code }); code = 0; } for (int i = 0; i <= 256; i = i + 4) { mempw.printf("%02x : %08x; -- %s\r\n", i / 4, GetWord(memplacement, i), i); } for (lineNum = 0; lineNum < instructionLines.size(); lineNum++) { instruction = instructionLines.get(lineNum); System.out.println(origInstruction.get(lineNum)); parameters = instruction.split(" ", 2)[1].trim(); instruction = instruction.split(" ", 2)[0].trim(); params = parameters.split(","); for (int i = 0; i < params.length; i++) { if (!(params[i].trim().startsWith("$")) && !isNumber(params[i].trim())) { if (params[i].contains("(")) { index = ContainsSymbol(Symbols, params[i] .trim().split("\\(")[0]); if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1].contains("-1")) { params[i] = params[i].replace( Symbols.get(index)[0], Symbols.get(index)[1]); } } else { System.out.println("ERROR Symbol " + params[i].trim() + " does not exist."); } if (!(params[i].trim().split("\\(")[1] .startsWith("$")) && !isNumber(params[i].trim().split( "\\(")[1].replace(")", ""))) { index = ContainsSymbol(Symbols, params[i] .trim().split("\\(")[1].replace( ")", "")); } } else { index = ContainsSymbol(Symbols, params[i].trim()); } if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1].contains("-1")) { params[i] = params[i].replace( Symbols.get(index)[0], Symbols.get(index)[1]); } } else { System.out .println("ERROR Symbol " + params[i].trim() + " does not exist."); } } } try { code = 0; switch (instruction) { // R-Type case "add": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x20; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "and": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x24; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jalr": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= 0x09; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jr": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= 0x08; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "nor": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x27; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "or": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sll": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 6; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sllv": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 21; code |= 0x04; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "slt": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x2A; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "srl": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[2].trim()) .intValue() << 5; code |= 0x02; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sub": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x22; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "xor": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; // I-Type case "addi": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 8 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "andi": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 12 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "beq": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[2].trim()) .intValue()/4 - lineNum; code |= 4 << 26; // origInstruction = origInstruction.split(" ")[0] + // origInstruction.split(" ")[1] + // origInstruction.split(" ")[2] + // (labelLoc.get(origInstruction.split(" ")[3])).toString(); pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "bne": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[2].trim()) .intValue()/4 - lineNum; code |= 0x05 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lb": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x20 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lh": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x21 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lui": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x0F << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "li": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= (byte) (Integer.valueOf(params[1].trim()) .intValue() & 0xFF); code |= 0x0F << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); lineNum++; code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= (byte) ((Integer.valueOf(params[1].trim()) .intValue() >> 8) & 0xFF); code |= 0x0D << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lw": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].trim().split("\\(")[0]) .intValue(); code |= Integer.valueOf( params[1].trim().split("\\(")[1].replace( ")", "").replace("$", "")) .intValue() << 21; code |= 0x23 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "ori": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 0x0D << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sw": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].trim().split("\\(")[0]) .intValue(); code |= Integer.valueOf( params[1].trim().split("\\(")[1].replace( ")", "").replace("$", "")) .intValue() << 21; code |= 0x2B << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; // J-Type case "j": code = Integer.valueOf(params[0].trim()).intValue() << 2; code |= 2 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jal": code = Integer.valueOf(params[0].trim()).intValue() << 2; code |= 3 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "nop": code = 0; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); default: if (!(instruction.startsWith("#"))) { System.out.println("Error reading instruction"); } } } catch (Exception e) { e.printStackTrace(); System.out.println("Syntax Error Line " + lineNum); } } // Finish the files pw.print("END;\r\n"); mempw.print("END;\r\n"); // close the writers pw.close(); mempw.close(); try { memfw.close(); fw.close(); } catch (IOException e) { System.out.println("Could not Close FileWriter"); } } catch (IOException e) { System.out.println("Could not open FileWriter"); fw = null; } } catch (IOException e) { System.out.println("File couldn't be created"); } } private static int ContainsSymbol(ArrayList<String[]> symbols, String target) { for (int i = 0; i < symbols.size(); i++) { if (symbols.get(i)[0].contains(target)) { return i; } } return -1; } private static String getLabel(ArrayList<String[]> symbols, int address){ for(int i = 0; i < symbols.size(); i++){ if (symbols.get(i)[1].equals(String.valueOf(address))){ return symbols.get(i)[0]+": "; } } return ""; } private static int GetWord(ArrayList<int[]> codes, int target) { for (int i = 0; i < codes.size(); i++) { if (codes.get(i)[0] == target) { return codes.get(i)[1]; } } return 0; } public static boolean isNumber(String sCheck) { try { double num = Double.parseDouble(sCheck); } catch (NumberFormatException nfe) { return false; } return true; } }
false
true
public static void main(String[] args) { // TODO code application logic here String labelRegex = "^[a-zA-Z_]+:"; Pattern label = Pattern.compile(labelRegex); Pattern register = Pattern.compile("^\\$[0-9]?[0-9]"); HashMap labelLoc = new HashMap(); int instCount = 0; int byteLine = 0; int lastByte = 0; int maxMem = 0; ArrayList<int[]> memplacement = new ArrayList<int[]>(); String filename = ""; try { filename = args[0]; } catch (Exception e) { Scanner consolein = new Scanner(System.in); System.out .println("Give the path or filename of source code to compile:"); filename = consolein.next(); consolein.close(); } boolean data = false; File infile = new File(filename); String[] tempParams = infile.getName().split("\\.(?=[^\\.]+$)"); String temp = tempParams[0]; File exeFile = new File(temp + ".exe.mif"); File memFile = new File(temp + ".mem.mif"); // Create file if it doesn't already exist try { exeFile.createNewFile(); Scanner input = new Scanner(infile); FileWriter fw; FileWriter memfw; try { String instruction = ""; int code = 0; ArrayList<String> instructionLines = new ArrayList<String>(); ArrayList<String> origInstruction = new ArrayList<String>(); ArrayList<String[]> Symbols = new ArrayList<String[]>(); String parameters = ""; String[] params; int index; int lineNum = 0; // initialize memory file writers memfw = new FileWriter(memFile); PrintWriter mempw = new PrintWriter(memfw); mempw.print("WIDTH = 32; \r\n-- data width \r\n" + "DEPTH = 256; \r\n-- number of memory slots \r\n" + "-- thus, the total size is 256 x 32 bits\r\n" + "ADDRESS_RADIX = HEX; \r\nDATA_RADIX = HEX; \r\n" + "CONTENT BEGIN \r\n"); // initialize executable file writers fw = new FileWriter(exeFile); PrintWriter pw = new PrintWriter(fw); pw.print("WIDTH = 32; \r\n-- data width \r\n" + "DEPTH = 256; \r\n-- number of memory slots \r\n" + "-- thus, the total size is 256 x 32 bits\r\n" + "ADDRESS_RADIX = HEX; \r\nDATA_RADIX = HEX; \r\n" + "CONTENT BEGIN \r\n"); code = 0; // start reading the file while (input.hasNextLine()) { params = input.nextLine().split("#"); if (params.length > 0) { instruction = params[0].trim(); } else { instruction = ""; } if (instruction.contains(".data")) { data = true; lineNum++; instCount++; byteLine = 0; } if (!data) { if (instruction.contains(":")) { params = instruction.split(":"); index = ContainsSymbol(Symbols, params[0].trim()); if (index > -1) { if (Symbols.get(index)[1].contains("-1")) { Symbols.set( index, new String[] { params[0].trim(), String.valueOf(lineNum * 4) }); } else { System.out.println("Symbol error (Line: " + lineNum + "): Symbol already exists."); } } else { Symbols.add(new String[] { params[0], String.valueOf(lineNum * 4) }); } if (params.length > 1) { instruction = params[1].trim(); } else { instruction = ""; } } if (instruction.length() > 0) { instructionLines.add(instruction); origInstruction.add(instruction); parameters = instruction.split(" ", 2)[1].trim(); params = parameters.split(","); for (int i = 0; i < params.length; i++) { if (!(params[i].trim().startsWith("$")) && !isNumber(params[i].trim())) { index = ContainsSymbol(Symbols, params[i].trim()); if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1] .contains("-1")) { instructionLines .set(lineNum, instructionLines .get(lineNum) .replace( Symbols.get(index)[0], Symbols.get(index)[1])); } } else { Symbols.add(new String[] { params[i].trim(), "-1" }); } } } lineNum++; instCount++; } } else { if (instruction.contains(":")) { params = instruction.split(":"); index = ContainsSymbol(Symbols, params[0].trim()); if (index > -1) { if (Symbols.get(index)[1].contains("-1")) { Symbols.set(index, new String[] { params[0].trim(), String.valueOf(byteLine) }); } else { System.out.println("Symbol error (Line: " + lineNum + "): Symbol already exists."); } } else { Symbols.add(new String[] { params[0], String.valueOf(byteLine) }); } if (params.length > 1) { instruction = params[1].trim(); } else { instruction = ""; } } if (instruction.length() > 0) { params = instruction.split(" ", 2); switch (params[0]) { case ".ascii": temp = params[0].replaceAll("\"", ""); for (int i = 0; i < temp.length(); i++) { code |= ((byte) temp.charAt(i)) << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } } break; case ".byte": code |= Integer.valueOf(params[1].trim()) .intValue() << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } break; case ".asciiz": temp = params[1].replaceAll("\"", "") + ((char) (0)); for (int i = 0; i < temp.length(); i++) { code |= ((byte) temp.charAt(i)) << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } } break; case "org": memplacement.add(new int[] { byteLine - byteLine % 4, code }); code = 0; byteLine = Integer.valueOf(params[1].trim()) .intValue(); break; default: } } } } if (byteLine % 4 != 0 && byteLine - 4 != lastByte) { memplacement.add(new int[] { byteLine - (byteLine % 4), code }); code = 0; } for (int i = 0; i <= 256; i = i + 4) { mempw.printf("%02x : %08x; -- %s\r\n", i / 4, GetWord(memplacement, i), i); } for (lineNum = 0; lineNum < instructionLines.size(); lineNum++) { instruction = instructionLines.get(lineNum); System.out.println(origInstruction.get(lineNum)); parameters = instruction.split(" ", 2)[1].trim(); instruction = instruction.split(" ", 2)[0].trim(); params = parameters.split(","); for (int i = 0; i < params.length; i++) { if (!(params[i].trim().startsWith("$")) && !isNumber(params[i].trim())) { if (params[i].contains("(")) { index = ContainsSymbol(Symbols, params[i] .trim().split("\\(")[0]); if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1].contains("-1")) { params[i] = params[i].replace( Symbols.get(index)[0], Symbols.get(index)[1]); } } else { System.out.println("ERROR Symbol " + params[i].trim() + " does not exist."); } if (!(params[i].trim().split("\\(")[1] .startsWith("$")) && !isNumber(params[i].trim().split( "\\(")[1].replace(")", ""))) { index = ContainsSymbol(Symbols, params[i] .trim().split("\\(")[1].replace( ")", "")); } } else { index = ContainsSymbol(Symbols, params[i].trim()); } if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1].contains("-1")) { params[i] = params[i].replace( Symbols.get(index)[0], Symbols.get(index)[1]); } } else { System.out .println("ERROR Symbol " + params[i].trim() + " does not exist."); } } } try { code = 0; switch (instruction) { // R-Type case "add": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x20; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "and": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x24; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jalr": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= 0x09; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jr": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= 0x08; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "nor": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x27; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "or": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sll": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 6; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sllv": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 21; code |= 0x04; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "slt": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x2A; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "srl": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[2].trim()) .intValue() << 5; code |= 0x02; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sub": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x22; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "xor": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; // I-Type case "addi": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 8 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "andi": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 12 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "beq": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[2].trim()) .intValue()/4 - lineNum; code |= 4 << 26; // origInstruction = origInstruction.split(" ")[0] + // origInstruction.split(" ")[1] + // origInstruction.split(" ")[2] + // (labelLoc.get(origInstruction.split(" ")[3])).toString(); pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "bne": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[2].trim()) .intValue()/4 - lineNum; code |= 0x05 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lb": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x20 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lh": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x21 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lui": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x0F << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "li": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= (byte) (Integer.valueOf(params[1].trim()) .intValue() & 0xFF); code |= 0x0F << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); lineNum++; code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= (byte) ((Integer.valueOf(params[1].trim()) .intValue() >> 8) & 0xFF); code |= 0x0D << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lw": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].trim().split("\\(")[0]) .intValue(); code |= Integer.valueOf( params[1].trim().split("\\(")[1].replace( ")", "").replace("$", "")) .intValue() << 21; code |= 0x23 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "ori": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 0x0D << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sw": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].trim().split("\\(")[0]) .intValue(); code |= Integer.valueOf( params[1].trim().split("\\(")[1].replace( ")", "").replace("$", "")) .intValue() << 21; code |= 0x2B << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; // J-Type case "j": code = Integer.valueOf(params[0].trim()).intValue() << 2; code |= 2 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jal": code = Integer.valueOf(params[0].trim()).intValue() << 2; code |= 3 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "nop": code = 0; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); default: if (!(instruction.startsWith("#"))) { System.out.println("Error reading instruction"); } } } catch (Exception e) { e.printStackTrace(); System.out.println("Syntax Error Line " + lineNum); } } // Finish the files pw.print("END;\r\n"); mempw.print("END;\r\n"); // close the writers pw.close(); mempw.close(); try { memfw.close(); fw.close(); } catch (IOException e) { System.out.println("Could not Close FileWriter"); } } catch (IOException e) { System.out.println("Could not open FileWriter"); fw = null; } } catch (IOException e) { System.out.println("File couldn't be created"); } }
public static void main(String[] args) { // TODO code application logic here String labelRegex = "^[a-zA-Z_]+:"; Pattern label = Pattern.compile(labelRegex); Pattern register = Pattern.compile("^\\$[0-9]?[0-9]"); HashMap labelLoc = new HashMap(); int instCount = 0; int byteLine = 0; int lastByte = 0; int maxMem = 0; ArrayList<int[]> memplacement = new ArrayList<int[]>(); String filename = ""; try { filename = args[0]; } catch (Exception e) { Scanner consolein = new Scanner(System.in); System.out .println("Give the path or filename of source code to compile:"); filename = consolein.next(); consolein.close(); } boolean data = false; File infile = new File(filename); String[] tempParams = infile.getName().split("\\.(?=[^\\.]+$)"); String temp = tempParams[0]; File exeFile = new File(temp + ".exe.mif"); File memFile = new File(temp + ".mem.mif"); // Create file if it doesn't already exist try { exeFile.createNewFile(); Scanner input = new Scanner(infile); FileWriter fw; FileWriter memfw; try { String instruction = ""; int code = 0; ArrayList<String> instructionLines = new ArrayList<String>(); ArrayList<String> origInstruction = new ArrayList<String>(); ArrayList<String[]> Symbols = new ArrayList<String[]>(); String parameters = ""; String[] params; int index; int lineNum = 0; // initialize memory file writers memfw = new FileWriter(memFile); PrintWriter mempw = new PrintWriter(memfw); mempw.print("WIDTH = 32; \r\n-- data width \r\n" + "DEPTH = 256; \r\n-- number of memory slots \r\n" + "-- thus, the total size is 256 x 32 bits\r\n" + "ADDRESS_RADIX = HEX; \r\nDATA_RADIX = HEX; \r\n" + "CONTENT BEGIN \r\n"); // initialize executable file writers fw = new FileWriter(exeFile); PrintWriter pw = new PrintWriter(fw); pw.print("WIDTH = 32; \r\n-- data width \r\n" + "DEPTH = 256; \r\n-- number of memory slots \r\n" + "-- thus, the total size is 256 x 32 bits\r\n" + "ADDRESS_RADIX = HEX; \r\nDATA_RADIX = HEX; \r\n" + "CONTENT BEGIN \r\n"); code = 0; // start reading the file while (input.hasNextLine()) { params = input.nextLine().split("#"); if (params.length > 0) { instruction = params[0].trim(); } else { instruction = ""; } if (instruction.contains(".data")) { data = true; lineNum++; instCount++; byteLine = 0; } if (!data) { if (instruction.contains(":")) { params = instruction.split(":"); index = ContainsSymbol(Symbols, params[0].trim()); if (index > -1) { if (Symbols.get(index)[1].contains("-1")) { Symbols.set( index, new String[] { params[0].trim(), String.valueOf(lineNum * 4) }); } else { System.out.println("Symbol error (Line: " + lineNum + "): Symbol already exists."); } } else { Symbols.add(new String[] { params[0], String.valueOf(lineNum * 4) }); } if (params.length > 1) { instruction = params[1].trim(); } else { instruction = ""; } } if (instruction.length() > 0) { instructionLines.add(instruction); origInstruction.add(instruction); parameters = instruction.split(" ", 2)[1].trim(); params = parameters.split(","); for (int i = 0; i < params.length; i++) { if (!(params[i].trim().startsWith("$")) && !isNumber(params[i].trim())) { index = ContainsSymbol(Symbols, params[i].trim()); if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1] .contains("-1")) { instructionLines .set(lineNum, instructionLines .get(lineNum) .replace( Symbols.get(index)[0], Symbols.get(index)[1])); } } else { Symbols.add(new String[] { params[i].trim(), "-1" }); } } } lineNum++; instCount++; } } else { if (instruction.contains(":")) { params = instruction.split(":"); index = ContainsSymbol(Symbols, params[0].trim()); if (index > -1) { if (Symbols.get(index)[1].contains("-1")) { Symbols.set(index, new String[] { params[0].trim(), String.valueOf(byteLine/4) }); } else { System.out.println("Symbol error (Line: " + lineNum + "): Symbol already exists."); } } else { Symbols.add(new String[] { params[0], String.valueOf(byteLine/4) }); } if (params.length > 1) { instruction = params[1].trim(); } else { instruction = ""; } } if (instruction.length() > 0) { params = instruction.split(" ", 2); switch (params[0]) { case ".ascii": temp = params[0].replaceAll("\"", ""); for (int i = 0; i < temp.length(); i++) { code |= ((byte) temp.charAt(i)) << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } } break; case ".byte": code |= Integer.valueOf(params[1].trim()) .intValue() << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } break; case ".asciiz": temp = params[1].replaceAll("\"", "") + ((char) (0)); for (int i = 0; i < temp.length(); i++) { code |= ((byte) temp.charAt(i)) << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } } break; case "org": memplacement.add(new int[] { byteLine - byteLine % 4, code }); code = 0; byteLine = Integer.valueOf(params[1].trim()) .intValue(); break; default: } } } } if (byteLine % 4 != 0 && byteLine - 4 != lastByte) { memplacement.add(new int[] { byteLine - (byteLine % 4), code }); code = 0; } for (int i = 0; i <= 256; i = i + 4) { mempw.printf("%02x : %08x; -- %s\r\n", i / 4, GetWord(memplacement, i), i); } for (lineNum = 0; lineNum < instructionLines.size(); lineNum++) { instruction = instructionLines.get(lineNum); System.out.println(origInstruction.get(lineNum)); parameters = instruction.split(" ", 2)[1].trim(); instruction = instruction.split(" ", 2)[0].trim(); params = parameters.split(","); for (int i = 0; i < params.length; i++) { if (!(params[i].trim().startsWith("$")) && !isNumber(params[i].trim())) { if (params[i].contains("(")) { index = ContainsSymbol(Symbols, params[i] .trim().split("\\(")[0]); if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1].contains("-1")) { params[i] = params[i].replace( Symbols.get(index)[0], Symbols.get(index)[1]); } } else { System.out.println("ERROR Symbol " + params[i].trim() + " does not exist."); } if (!(params[i].trim().split("\\(")[1] .startsWith("$")) && !isNumber(params[i].trim().split( "\\(")[1].replace(")", ""))) { index = ContainsSymbol(Symbols, params[i] .trim().split("\\(")[1].replace( ")", "")); } } else { index = ContainsSymbol(Symbols, params[i].trim()); } if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1].contains("-1")) { params[i] = params[i].replace( Symbols.get(index)[0], Symbols.get(index)[1]); } } else { System.out .println("ERROR Symbol " + params[i].trim() + " does not exist."); } } } try { code = 0; switch (instruction) { // R-Type case "add": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x20; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "and": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x24; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jalr": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= 0x09; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jr": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= 0x08; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "nor": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x27; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "or": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sll": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 6; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sllv": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 21; code |= 0x04; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "slt": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x2A; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "srl": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[2].trim()) .intValue() << 5; code |= 0x02; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sub": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x22; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "xor": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; // I-Type case "addi": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 8 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "andi": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 12 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "beq": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[2].trim()) .intValue()/4 - lineNum; code |= 4 << 26; // origInstruction = origInstruction.split(" ")[0] + // origInstruction.split(" ")[1] + // origInstruction.split(" ")[2] + // (labelLoc.get(origInstruction.split(" ")[3])).toString(); pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "bne": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[2].trim()) .intValue()/4 - lineNum; code |= 0x05 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lb": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x20 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lh": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x21 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lui": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x0F << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "li": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= (byte) (Integer.valueOf(params[1].trim()) .intValue() & 0xFF); code |= 0x0F << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); lineNum++; code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= (byte) ((Integer.valueOf(params[1].trim()) .intValue() >> 8) & 0xFF); code |= 0x0D << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lw": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].trim().split("\\(")[0]) .intValue(); code |= Integer.valueOf( params[1].trim().split("\\(")[1].replace( ")", "").replace("$", "")) .intValue() << 21; code |= 0x23 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "ori": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 0x0D << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sw": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].trim().split("\\(")[0]) .intValue(); code |= Integer.valueOf( params[1].trim().split("\\(")[1].replace( ")", "").replace("$", "")) .intValue() << 21; code |= 0x2B << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; // J-Type case "j": code = Integer.valueOf(params[0].trim()).intValue() << 2; code |= 2 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jal": code = Integer.valueOf(params[0].trim()).intValue() << 2; code |= 3 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "nop": code = 0; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); default: if (!(instruction.startsWith("#"))) { System.out.println("Error reading instruction"); } } } catch (Exception e) { e.printStackTrace(); System.out.println("Syntax Error Line " + lineNum); } } // Finish the files pw.print("END;\r\n"); mempw.print("END;\r\n"); // close the writers pw.close(); mempw.close(); try { memfw.close(); fw.close(); } catch (IOException e) { System.out.println("Could not Close FileWriter"); } } catch (IOException e) { System.out.println("Could not open FileWriter"); fw = null; } } catch (IOException e) { System.out.println("File couldn't be created"); } }
diff --git a/src/presentation/MainWindow.java b/src/presentation/MainWindow.java index 5f017f8..8fde856 100644 --- a/src/presentation/MainWindow.java +++ b/src/presentation/MainWindow.java @@ -1,65 +1,65 @@ package presentation; import java.awt.BorderLayout; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.*; /** * Presentation class for the main window. Contains the tabs that contains the panels. * @author Kristoffer Karlsson * */ public class MainWindow extends JFrame { private JPanel contentPane; /** * Method "createInnerPanel" creates the panel that is inside the tab * @param text is a placeholder, will be replaced by the other panels */ public JPanel createInnerPanel(String text) { JPanel thePanel = new JPanel(); JLabel theLabel = new JLabel(text); theLabel.setHorizontalAlignment(JLabel.CENTER); thePanel.setLayout(new GridLayout(1,1)); thePanel.add(theLabel); return thePanel; } public static void main(String[] args) { MainWindow mw = new MainWindow(); mw.setVisible(true); } public MainWindow() { setTitle("Bokhandeln"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 520); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JTabbedPane thePanes = new JTabbedPane(); ImageIcon bookIcon = new ImageIcon("dasbook.gif"); - JPanel start = createInnerPanel("Detta �r startsidan"); - thePanes.addTab("Startsida", bookIcon, start, "Tab1"); + JPanel start = createInnerPanel("BrowsePanel goes here"); + thePanes.addTab("Startsida", bookIcon, start, "Startsida, hitta information om b�cker"); thePanes.setSelectedIndex(0); - JPanel addStuff = createInnerPanel("H�r l�gger man till/tar bort b�cker"); - thePanes.addTab("L�gg till", bookIcon, addStuff); + JPanel addStuff = createInnerPanel("AddBooksPanel goes here"); + thePanes.addTab("L�gg till", bookIcon, addStuff, "L�gg till, ta bort, eller redigera b�cker"); - JPanel statistic = createInnerPanel("H�r ser man statistik"); - thePanes.addTab("Statistik", bookIcon, statistic); + JPanel statistic = createInnerPanel("StatisticPanel goes here"); + thePanes.addTab("Statistik", bookIcon, statistic, "Visa f�rs�ljningsstatistik"); setLayout(new GridLayout(1,1)); add(thePanes); } }
false
true
public MainWindow() { setTitle("Bokhandeln"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 520); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JTabbedPane thePanes = new JTabbedPane(); ImageIcon bookIcon = new ImageIcon("dasbook.gif"); JPanel start = createInnerPanel("Detta �r startsidan"); thePanes.addTab("Startsida", bookIcon, start, "Tab1"); thePanes.setSelectedIndex(0); JPanel addStuff = createInnerPanel("H�r l�gger man till/tar bort b�cker"); thePanes.addTab("L�gg till", bookIcon, addStuff); JPanel statistic = createInnerPanel("H�r ser man statistik"); thePanes.addTab("Statistik", bookIcon, statistic); setLayout(new GridLayout(1,1)); add(thePanes); }
public MainWindow() { setTitle("Bokhandeln"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 520); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JTabbedPane thePanes = new JTabbedPane(); ImageIcon bookIcon = new ImageIcon("dasbook.gif"); JPanel start = createInnerPanel("BrowsePanel goes here"); thePanes.addTab("Startsida", bookIcon, start, "Startsida, hitta information om b�cker"); thePanes.setSelectedIndex(0); JPanel addStuff = createInnerPanel("AddBooksPanel goes here"); thePanes.addTab("L�gg till", bookIcon, addStuff, "L�gg till, ta bort, eller redigera b�cker"); JPanel statistic = createInnerPanel("StatisticPanel goes here"); thePanes.addTab("Statistik", bookIcon, statistic, "Visa f�rs�ljningsstatistik"); setLayout(new GridLayout(1,1)); add(thePanes); }
diff --git a/src/main/java/net/robbytu/banjoserver/pvpcage/Main.java b/src/main/java/net/robbytu/banjoserver/pvpcage/Main.java index 1725c10..139e974 100644 --- a/src/main/java/net/robbytu/banjoserver/pvpcage/Main.java +++ b/src/main/java/net/robbytu/banjoserver/pvpcage/Main.java @@ -1,253 +1,253 @@ package net.robbytu.banjoserver.pvpcage; import com.sk89q.worldedit.bukkit.selections.Selection; import net.milkbowl.vault.permission.Permission; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.MemorySection; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import java.util.ArrayList; import java.util.List; import java.util.Set; public class Main extends JavaPlugin implements Listener { static WorldEditPlugin WE; static Permission permission = null; @Override public void onEnable() { WE = this.getWorldEdit(); if(WE == null) { getLogger().warning("You must have WorldEdit installed for this plugin to work."); getPluginLoader().disablePlugin(this); } if(!this.setupPermissions()) { getLogger().warning("You must have Vault and some Permissions plugin installed for this plugin to work."); getPluginLoader().disablePlugin(this); } getServer().getPluginManager().registerEvents(this, this); } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(!(sender instanceof Player)) { sender.sendMessage("Console may not interact with bs-pvpcage!"); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("create")) { if(!permission.has(sender, "pvpcage.create")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify a name for the new cage."); Selection sel = WE.getSelection((Player)sender); if(sel == null) return this.failCommand(sender, cmd, "Error: You must select a region using WorldEdit before creating a cage."); if(getConfig().contains("cage." + sel.getWorld().getName() + "." + args[1])) return this.failCommand(sender, cmd, "Invalid argument: This name is already in use by another cage."); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".min.x", sel.getMinimumPoint().getX()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".min.y", sel.getMinimumPoint().getY()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".min.z", sel.getMinimumPoint().getZ()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".max.x", sel.getMaximumPoint().getX()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".max.y", sel.getMaximumPoint().getY()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".max.z", sel.getMaximumPoint().getZ()); this.saveConfig(); sender.sendMessage(ChatColor.GREEN + "Succesfully created cage."); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("remove")) { if(!permission.has(sender, "pvpcage.remove")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify the name of the cage to be removed."); if(!getConfig().contains("cage." + ((Player)sender).getWorld().getName() + "." + args[1])) return this.failCommand(sender, cmd, "Invalid argument: No such cage found."); this.getConfig().set("cage." + ((Player)sender).getWorld().getName() + "." + args[1], null); this.saveConfig(); sender.sendMessage(ChatColor.GREEN + "Succesfully removed cage."); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("require")) { if(!permission.has(sender, "pvpcage.require")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify wether to <add> or <remove> a requirement."); if(args.length == 2) return this.failCommand(sender, cmd, "Missing argument: You must specify the name of the cage to apply new settings to."); if(args.length == 3) return this.failCommand(sender, cmd, "Missing argument: You must specify an item to apply."); if(!args[1].equalsIgnoreCase("add") && !args[1].equalsIgnoreCase("remove")) return this.failCommand(sender, cmd, "Invalid argument: You must specify wether to <add> or <remove> a requirement."); if(!getConfig().contains("cage." + ((Player)sender).getWorld().getName() + "." + args[2])) return this.failCommand(sender, cmd, "Invalid argument: No such cage found."); Material mat; - if(this.isInteger(args[3])) mat = Material.getMaterial(Integer.getInteger(args[3])); + if(this.isInteger(args[3])) mat = Material.getMaterial(Integer.parseInt(args[3])); else mat = Material.getMaterial(args[3]); if(mat == null) return this.failCommand(sender, cmd, "Invalid argument: No such Material found (" + args[3] + ")."); List<Integer> requirements = this.getConfig().getIntegerList("cage." + ((Player)sender).getWorld().getName() + "." + args[2] + ".requirements"); if(requirements == null) requirements = new ArrayList<Integer>(); if(args[1].equalsIgnoreCase("add")) if(!requirements.contains(mat.getId())) requirements.add(mat.getId()); if(args[1].equalsIgnoreCase("remove")) if(requirements.contains(mat.getId())) requirements.remove(mat.getId()); this.getConfig().set("cage." + ((Player)sender).getWorld().getName() + "." + args[2] + ".requirements", requirements); this.saveConfig(); sender.sendMessage(ChatColor.GREEN + "Succesfully " + args[1] + "ed requirement."); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("prohibit")) { if(!permission.has(sender, "pvpcage.prohibit")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify wether to <add> or <remove> a prohibitation."); if(args.length == 2) return this.failCommand(sender, cmd, "Missing argument: You must specify the name of the cage to apply new settings to."); if(args.length == 3) return this.failCommand(sender, cmd, "Missing argument: You must specify an item to apply."); if(!args[1].equalsIgnoreCase("add") && !args[1].equalsIgnoreCase("remove")) return this.failCommand(sender, cmd, "Invalid argument: You must specify wether to <add> or <remove> a prohibitation."); if(!getConfig().contains("cage." + ((Player)sender).getWorld().getName() + "." + args[2])) return this.failCommand(sender, cmd, "Invalid argument: No such cage found."); Material mat; - if(this.isInteger(args[3])) mat = Material.getMaterial(Integer.getInteger(args[3])); + if(this.isInteger(args[3])) mat = Material.getMaterial(Integer.parseInt(args[3])); else mat = Material.getMaterial(args[3]); if(mat == null) return this.failCommand(sender, cmd, "Invalid argument: No such Material found (" + args[3] + ")."); List<Integer> prohibitations = this.getConfig().getIntegerList("cage." + ((Player)sender).getWorld().getName() + "." + args[2] + ".prohibited"); if(prohibitations == null) prohibitations = new ArrayList<Integer>(); if(args[1].equalsIgnoreCase("add")) if(!prohibitations.contains(mat.getId())) prohibitations.add(mat.getId()); if(args[1].equalsIgnoreCase("remove")) if(prohibitations.contains(mat.getId())) prohibitations.remove(mat.getId()); this.getConfig().set("cage." + ((Player)sender).getWorld().getName() + "." + args[2] + ".prohibited", prohibitations); this.saveConfig(); sender.sendMessage(ChatColor.GREEN + "Succesfully " + args[1] + "ed prohibitation."); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("info")) { if(!permission.has(sender, "pvpcage.info")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify the name of the cage to fetch info from."); if(!getConfig().contains("cage." + ((Player)sender).getWorld().getName() + "." + args[1])) return this.failCommand(sender, cmd, "Invalid argument: No such cage found."); List<Integer> requirements = this.getConfig().getIntegerList("cage." + ((Player)sender).getWorld().getName() + "." + args[1] + ".requirements"); if(requirements != null) { sender.sendMessage(ChatColor.AQUA + "Required items for " + args[1] + ":"); for(int i : requirements) sender.sendMessage(ChatColor.AQUA + " - " + ChatColor.GRAY + Material.getMaterial(i).name()); sender.sendMessage(" "); } List<Integer> prohibitations = this.getConfig().getIntegerList("cage." + ((Player)sender).getWorld().getName() + "." + args[1] + ".prohibited"); if(prohibitations != null) { sender.sendMessage(ChatColor.AQUA + "Prohibited items for " + args[1] + ":"); for(int i : prohibitations) sender.sendMessage(ChatColor.AQUA + " - " + ChatColor.GRAY + Material.getMaterial(i).name()); sender.sendMessage(" "); } if(requirements == null && prohibitations == null) sender.sendMessage(ChatColor.GRAY + "No required nor prohibited items configured for " + args[1]); return true; } return this.failCommand(sender, cmd, "No such method or missing arguments."); } @EventHandler public void onPlayerMoveEvent(PlayerMoveEvent event) { if(!permission.has(event.getPlayer(), "pvpcage.bypass")) { try { String world = event.getPlayer().getWorld().getName(); Location player_loc = event.getPlayer().getLocation(); Set<String> regions = ((MemorySection)getConfig().get("cage." + world)).getKeys(false); for(String region : regions) { double max_x = getConfig().getDouble("cage." + world + "." + region + ".max.x"); double max_y = getConfig().getDouble("cage." + world + "." + region + ".max.y"); double max_z = getConfig().getDouble("cage." + world + "." + region + ".max.z"); double min_x = getConfig().getDouble("cage." + world + "." + region + ".min.x"); double min_y = getConfig().getDouble("cage." + world + "." + region + ".min.y"); double min_z = getConfig().getDouble("cage." + world + "." + region + ".min.z"); if(player_loc.getX() >= min_x && player_loc.getX() < max_x && player_loc.getY() >= min_y && player_loc.getY() < max_y && player_loc.getZ() >= min_z && player_loc.getZ() < max_z) { List<Integer> prohibitations = this.getConfig().getIntegerList("cage." + world + "." + region + ".prohibited"); List<Integer> requirements = this.getConfig().getIntegerList("cage." + world + "." + region + ".requirements"); for(int i : prohibitations) { Material mat = Material.getMaterial(i); if(event.getPlayer().getInventory().contains(mat)) { event.setCancelled(true); event.getPlayer().sendMessage(ChatColor.RED + "Je hebt geen toegang tot dit gebied omdat je dit item in je inventory hebt: " + mat.name()); return; } } for(int i : requirements) { Material mat = Material.getMaterial(i); if(!event.getPlayer().getInventory().contains(mat)) { event.setCancelled(true); event.getPlayer().sendMessage(ChatColor.RED + "Om dit gebied binnen te gaan ben je dit item in je inventory nodig: " + mat.name()); return; } } } } } catch(Exception ignored) {} } } private boolean failCommand(CommandSender sender, Command cmd, String error) { sender.sendMessage(ChatColor.RED + error); sender.sendMessage(ChatColor.GRAY + "Usage: " + ChatColor.ITALIC + cmd.getUsage()); return true; } private WorldEditPlugin getWorldEdit() { if(this.getServer().getPluginManager().getPlugin("WorldEdit") != null) return (WorldEditPlugin) this.getServer().getPluginManager().getPlugin("WorldEdit"); return null; } private boolean setupPermissions() { RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); if (permissionProvider != null) permission = permissionProvider.getProvider(); return (permission != null); } private boolean isInteger(String s) { try { Integer.parseInt(s); } catch(NumberFormatException e) { return false; } return true; } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(!(sender instanceof Player)) { sender.sendMessage("Console may not interact with bs-pvpcage!"); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("create")) { if(!permission.has(sender, "pvpcage.create")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify a name for the new cage."); Selection sel = WE.getSelection((Player)sender); if(sel == null) return this.failCommand(sender, cmd, "Error: You must select a region using WorldEdit before creating a cage."); if(getConfig().contains("cage." + sel.getWorld().getName() + "." + args[1])) return this.failCommand(sender, cmd, "Invalid argument: This name is already in use by another cage."); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".min.x", sel.getMinimumPoint().getX()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".min.y", sel.getMinimumPoint().getY()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".min.z", sel.getMinimumPoint().getZ()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".max.x", sel.getMaximumPoint().getX()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".max.y", sel.getMaximumPoint().getY()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".max.z", sel.getMaximumPoint().getZ()); this.saveConfig(); sender.sendMessage(ChatColor.GREEN + "Succesfully created cage."); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("remove")) { if(!permission.has(sender, "pvpcage.remove")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify the name of the cage to be removed."); if(!getConfig().contains("cage." + ((Player)sender).getWorld().getName() + "." + args[1])) return this.failCommand(sender, cmd, "Invalid argument: No such cage found."); this.getConfig().set("cage." + ((Player)sender).getWorld().getName() + "." + args[1], null); this.saveConfig(); sender.sendMessage(ChatColor.GREEN + "Succesfully removed cage."); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("require")) { if(!permission.has(sender, "pvpcage.require")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify wether to <add> or <remove> a requirement."); if(args.length == 2) return this.failCommand(sender, cmd, "Missing argument: You must specify the name of the cage to apply new settings to."); if(args.length == 3) return this.failCommand(sender, cmd, "Missing argument: You must specify an item to apply."); if(!args[1].equalsIgnoreCase("add") && !args[1].equalsIgnoreCase("remove")) return this.failCommand(sender, cmd, "Invalid argument: You must specify wether to <add> or <remove> a requirement."); if(!getConfig().contains("cage." + ((Player)sender).getWorld().getName() + "." + args[2])) return this.failCommand(sender, cmd, "Invalid argument: No such cage found."); Material mat; if(this.isInteger(args[3])) mat = Material.getMaterial(Integer.getInteger(args[3])); else mat = Material.getMaterial(args[3]); if(mat == null) return this.failCommand(sender, cmd, "Invalid argument: No such Material found (" + args[3] + ")."); List<Integer> requirements = this.getConfig().getIntegerList("cage." + ((Player)sender).getWorld().getName() + "." + args[2] + ".requirements"); if(requirements == null) requirements = new ArrayList<Integer>(); if(args[1].equalsIgnoreCase("add")) if(!requirements.contains(mat.getId())) requirements.add(mat.getId()); if(args[1].equalsIgnoreCase("remove")) if(requirements.contains(mat.getId())) requirements.remove(mat.getId()); this.getConfig().set("cage." + ((Player)sender).getWorld().getName() + "." + args[2] + ".requirements", requirements); this.saveConfig(); sender.sendMessage(ChatColor.GREEN + "Succesfully " + args[1] + "ed requirement."); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("prohibit")) { if(!permission.has(sender, "pvpcage.prohibit")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify wether to <add> or <remove> a prohibitation."); if(args.length == 2) return this.failCommand(sender, cmd, "Missing argument: You must specify the name of the cage to apply new settings to."); if(args.length == 3) return this.failCommand(sender, cmd, "Missing argument: You must specify an item to apply."); if(!args[1].equalsIgnoreCase("add") && !args[1].equalsIgnoreCase("remove")) return this.failCommand(sender, cmd, "Invalid argument: You must specify wether to <add> or <remove> a prohibitation."); if(!getConfig().contains("cage." + ((Player)sender).getWorld().getName() + "." + args[2])) return this.failCommand(sender, cmd, "Invalid argument: No such cage found."); Material mat; if(this.isInteger(args[3])) mat = Material.getMaterial(Integer.getInteger(args[3])); else mat = Material.getMaterial(args[3]); if(mat == null) return this.failCommand(sender, cmd, "Invalid argument: No such Material found (" + args[3] + ")."); List<Integer> prohibitations = this.getConfig().getIntegerList("cage." + ((Player)sender).getWorld().getName() + "." + args[2] + ".prohibited"); if(prohibitations == null) prohibitations = new ArrayList<Integer>(); if(args[1].equalsIgnoreCase("add")) if(!prohibitations.contains(mat.getId())) prohibitations.add(mat.getId()); if(args[1].equalsIgnoreCase("remove")) if(prohibitations.contains(mat.getId())) prohibitations.remove(mat.getId()); this.getConfig().set("cage." + ((Player)sender).getWorld().getName() + "." + args[2] + ".prohibited", prohibitations); this.saveConfig(); sender.sendMessage(ChatColor.GREEN + "Succesfully " + args[1] + "ed prohibitation."); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("info")) { if(!permission.has(sender, "pvpcage.info")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify the name of the cage to fetch info from."); if(!getConfig().contains("cage." + ((Player)sender).getWorld().getName() + "." + args[1])) return this.failCommand(sender, cmd, "Invalid argument: No such cage found."); List<Integer> requirements = this.getConfig().getIntegerList("cage." + ((Player)sender).getWorld().getName() + "." + args[1] + ".requirements"); if(requirements != null) { sender.sendMessage(ChatColor.AQUA + "Required items for " + args[1] + ":"); for(int i : requirements) sender.sendMessage(ChatColor.AQUA + " - " + ChatColor.GRAY + Material.getMaterial(i).name()); sender.sendMessage(" "); } List<Integer> prohibitations = this.getConfig().getIntegerList("cage." + ((Player)sender).getWorld().getName() + "." + args[1] + ".prohibited"); if(prohibitations != null) { sender.sendMessage(ChatColor.AQUA + "Prohibited items for " + args[1] + ":"); for(int i : prohibitations) sender.sendMessage(ChatColor.AQUA + " - " + ChatColor.GRAY + Material.getMaterial(i).name()); sender.sendMessage(" "); } if(requirements == null && prohibitations == null) sender.sendMessage(ChatColor.GRAY + "No required nor prohibited items configured for " + args[1]); return true; } return this.failCommand(sender, cmd, "No such method or missing arguments."); }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(!(sender instanceof Player)) { sender.sendMessage("Console may not interact with bs-pvpcage!"); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("create")) { if(!permission.has(sender, "pvpcage.create")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify a name for the new cage."); Selection sel = WE.getSelection((Player)sender); if(sel == null) return this.failCommand(sender, cmd, "Error: You must select a region using WorldEdit before creating a cage."); if(getConfig().contains("cage." + sel.getWorld().getName() + "." + args[1])) return this.failCommand(sender, cmd, "Invalid argument: This name is already in use by another cage."); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".min.x", sel.getMinimumPoint().getX()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".min.y", sel.getMinimumPoint().getY()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".min.z", sel.getMinimumPoint().getZ()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".max.x", sel.getMaximumPoint().getX()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".max.y", sel.getMaximumPoint().getY()); this.getConfig().set("cage." + sel.getWorld().getName() + "." + args[1] + ".max.z", sel.getMaximumPoint().getZ()); this.saveConfig(); sender.sendMessage(ChatColor.GREEN + "Succesfully created cage."); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("remove")) { if(!permission.has(sender, "pvpcage.remove")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify the name of the cage to be removed."); if(!getConfig().contains("cage." + ((Player)sender).getWorld().getName() + "." + args[1])) return this.failCommand(sender, cmd, "Invalid argument: No such cage found."); this.getConfig().set("cage." + ((Player)sender).getWorld().getName() + "." + args[1], null); this.saveConfig(); sender.sendMessage(ChatColor.GREEN + "Succesfully removed cage."); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("require")) { if(!permission.has(sender, "pvpcage.require")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify wether to <add> or <remove> a requirement."); if(args.length == 2) return this.failCommand(sender, cmd, "Missing argument: You must specify the name of the cage to apply new settings to."); if(args.length == 3) return this.failCommand(sender, cmd, "Missing argument: You must specify an item to apply."); if(!args[1].equalsIgnoreCase("add") && !args[1].equalsIgnoreCase("remove")) return this.failCommand(sender, cmd, "Invalid argument: You must specify wether to <add> or <remove> a requirement."); if(!getConfig().contains("cage." + ((Player)sender).getWorld().getName() + "." + args[2])) return this.failCommand(sender, cmd, "Invalid argument: No such cage found."); Material mat; if(this.isInteger(args[3])) mat = Material.getMaterial(Integer.parseInt(args[3])); else mat = Material.getMaterial(args[3]); if(mat == null) return this.failCommand(sender, cmd, "Invalid argument: No such Material found (" + args[3] + ")."); List<Integer> requirements = this.getConfig().getIntegerList("cage." + ((Player)sender).getWorld().getName() + "." + args[2] + ".requirements"); if(requirements == null) requirements = new ArrayList<Integer>(); if(args[1].equalsIgnoreCase("add")) if(!requirements.contains(mat.getId())) requirements.add(mat.getId()); if(args[1].equalsIgnoreCase("remove")) if(requirements.contains(mat.getId())) requirements.remove(mat.getId()); this.getConfig().set("cage." + ((Player)sender).getWorld().getName() + "." + args[2] + ".requirements", requirements); this.saveConfig(); sender.sendMessage(ChatColor.GREEN + "Succesfully " + args[1] + "ed requirement."); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("prohibit")) { if(!permission.has(sender, "pvpcage.prohibit")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify wether to <add> or <remove> a prohibitation."); if(args.length == 2) return this.failCommand(sender, cmd, "Missing argument: You must specify the name of the cage to apply new settings to."); if(args.length == 3) return this.failCommand(sender, cmd, "Missing argument: You must specify an item to apply."); if(!args[1].equalsIgnoreCase("add") && !args[1].equalsIgnoreCase("remove")) return this.failCommand(sender, cmd, "Invalid argument: You must specify wether to <add> or <remove> a prohibitation."); if(!getConfig().contains("cage." + ((Player)sender).getWorld().getName() + "." + args[2])) return this.failCommand(sender, cmd, "Invalid argument: No such cage found."); Material mat; if(this.isInteger(args[3])) mat = Material.getMaterial(Integer.parseInt(args[3])); else mat = Material.getMaterial(args[3]); if(mat == null) return this.failCommand(sender, cmd, "Invalid argument: No such Material found (" + args[3] + ")."); List<Integer> prohibitations = this.getConfig().getIntegerList("cage." + ((Player)sender).getWorld().getName() + "." + args[2] + ".prohibited"); if(prohibitations == null) prohibitations = new ArrayList<Integer>(); if(args[1].equalsIgnoreCase("add")) if(!prohibitations.contains(mat.getId())) prohibitations.add(mat.getId()); if(args[1].equalsIgnoreCase("remove")) if(prohibitations.contains(mat.getId())) prohibitations.remove(mat.getId()); this.getConfig().set("cage." + ((Player)sender).getWorld().getName() + "." + args[2] + ".prohibited", prohibitations); this.saveConfig(); sender.sendMessage(ChatColor.GREEN + "Succesfully " + args[1] + "ed prohibitation."); return true; } if(args.length > 0 && args[0].equalsIgnoreCase("info")) { if(!permission.has(sender, "pvpcage.info")) return this.failCommand(sender, cmd, "Insufficient permissions."); if(args.length == 1) return this.failCommand(sender, cmd, "Missing argument: You must specify the name of the cage to fetch info from."); if(!getConfig().contains("cage." + ((Player)sender).getWorld().getName() + "." + args[1])) return this.failCommand(sender, cmd, "Invalid argument: No such cage found."); List<Integer> requirements = this.getConfig().getIntegerList("cage." + ((Player)sender).getWorld().getName() + "." + args[1] + ".requirements"); if(requirements != null) { sender.sendMessage(ChatColor.AQUA + "Required items for " + args[1] + ":"); for(int i : requirements) sender.sendMessage(ChatColor.AQUA + " - " + ChatColor.GRAY + Material.getMaterial(i).name()); sender.sendMessage(" "); } List<Integer> prohibitations = this.getConfig().getIntegerList("cage." + ((Player)sender).getWorld().getName() + "." + args[1] + ".prohibited"); if(prohibitations != null) { sender.sendMessage(ChatColor.AQUA + "Prohibited items for " + args[1] + ":"); for(int i : prohibitations) sender.sendMessage(ChatColor.AQUA + " - " + ChatColor.GRAY + Material.getMaterial(i).name()); sender.sendMessage(" "); } if(requirements == null && prohibitations == null) sender.sendMessage(ChatColor.GRAY + "No required nor prohibited items configured for " + args[1]); return true; } return this.failCommand(sender, cmd, "No such method or missing arguments."); }
diff --git a/src/Export/Exporter.java b/src/Export/Exporter.java index 51ff042..697603c 100644 --- a/src/Export/Exporter.java +++ b/src/Export/Exporter.java @@ -1,112 +1,112 @@ /** * This file is part of libRibbonIO library (check README). * Copyright (C) 2012-2013 Stanislav Nepochatov * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ package Export; import Utils.IOControl; /** * Export single operation thread class. * @author Stanislav Nepochatov <[email protected]> */ public abstract class Exporter extends Thread { /** * Current export scheme. */ protected Schema currSchema; /** * Release switch for index updating. */ protected ReleaseSwitch currSwitch; /** * Dir which call this export task. */ protected String calledDir; /** * Exported message itself. You should use * this variable instead of <code>CONTENT</code> * field in message. */ protected String exportedContent; /** * Current exporting message. */ protected MessageClasses.Message exportedMessage; /** * Charset for export. */ protected String exportedCharset = "UTF-8"; /** * Default constructor. * @param givenMessage message to export; * @param givenSchema export scheme reference; * @param givenSwitch message index updater switch; * @param givenDir dir which message came from; */ public Exporter(MessageClasses.Message givenMessage, Schema givenSchema, ReleaseSwitch givenSwitch, String givenDir) { currSchema = givenSchema; currSwitch = givenSwitch; exportedMessage = givenMessage; calledDir = givenDir; if (currSchema.currFormater !=null) { exportedContent = currSchema.currFormater.format(exportedMessage, calledDir); } else { exportedContent = exportedMessage.CONTENT; } if (currSchema.currConfig.getProperty("opt_charset") != null) { exportedCharset = currSchema.currConfig.getProperty("opt_charset"); } } @Override public void run() { try { doExport(); if ("1".equals(this.currSchema.currConfig.getProperty("opt_log"))) { IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + this.currSchema.name, 3, "прозведено експорт повідомлення " + this.exportedMessage.INDEX); } - exportedMessage.PROPERTIES.add(new MessageClasses.MessageProperty(this.currSchema.currConfig.getProperty("export_type"), "root", this.currSchema.currConfig.getProperty("export_print"), IOControl.serverWrapper.getDate())); + exportedMessage.PROPERTIES.add(new MessageClasses.MessageProperty("EXPORT_" + this.currSchema.currConfig.getProperty("export_type"), "root", this.currSchema.currConfig.getProperty("export_print"), IOControl.serverWrapper.getDate())); } catch (Exception ex) { IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + this.currSchema.name, 1, "експорт повідомлення '" + this.exportedMessage.HEADER + "' завершився помилкою."); IOControl.serverWrapper.enableDirtyState(this.currSchema.type, this.currSchema.name, this.currSchema.currConfig.getProperty("export_print")); IOControl.serverWrapper.postException("Помилка експорту: схема " + this.currSchema.name + " тип " + this.currSchema.type + "\nПовідомлення " + this.exportedMessage.HEADER + " за індексом " + this.exportedMessage.INDEX, ex); } this.currSwitch.markSchema(this.currSchema.name); } /** * Body of export method. */ protected abstract void doExport() throws Exception; /** * Try to recover current export task. * @return result of recovery operation; */ public abstract Boolean tryRecovery(); }
true
true
public void run() { try { doExport(); if ("1".equals(this.currSchema.currConfig.getProperty("opt_log"))) { IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + this.currSchema.name, 3, "прозведено експорт повідомлення " + this.exportedMessage.INDEX); } exportedMessage.PROPERTIES.add(new MessageClasses.MessageProperty(this.currSchema.currConfig.getProperty("export_type"), "root", this.currSchema.currConfig.getProperty("export_print"), IOControl.serverWrapper.getDate())); } catch (Exception ex) { IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + this.currSchema.name, 1, "експорт повідомлення '" + this.exportedMessage.HEADER + "' завершився помилкою."); IOControl.serverWrapper.enableDirtyState(this.currSchema.type, this.currSchema.name, this.currSchema.currConfig.getProperty("export_print")); IOControl.serverWrapper.postException("Помилка експорту: схема " + this.currSchema.name + " тип " + this.currSchema.type + "\nПовідомлення " + this.exportedMessage.HEADER + " за індексом " + this.exportedMessage.INDEX, ex); } this.currSwitch.markSchema(this.currSchema.name); }
public void run() { try { doExport(); if ("1".equals(this.currSchema.currConfig.getProperty("opt_log"))) { IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + this.currSchema.name, 3, "прозведено експорт повідомлення " + this.exportedMessage.INDEX); } exportedMessage.PROPERTIES.add(new MessageClasses.MessageProperty("EXPORT_" + this.currSchema.currConfig.getProperty("export_type"), "root", this.currSchema.currConfig.getProperty("export_print"), IOControl.serverWrapper.getDate())); } catch (Exception ex) { IOControl.serverWrapper.log(IOControl.EXPORT_LOGID + ":" + this.currSchema.name, 1, "експорт повідомлення '" + this.exportedMessage.HEADER + "' завершився помилкою."); IOControl.serverWrapper.enableDirtyState(this.currSchema.type, this.currSchema.name, this.currSchema.currConfig.getProperty("export_print")); IOControl.serverWrapper.postException("Помилка експорту: схема " + this.currSchema.name + " тип " + this.currSchema.type + "\nПовідомлення " + this.exportedMessage.HEADER + " за індексом " + this.exportedMessage.INDEX, ex); } this.currSwitch.markSchema(this.currSchema.name); }
diff --git a/src/org/pitaya/io/Streams.java b/src/org/pitaya/io/Streams.java index 202f782..6be32d4 100644 --- a/src/org/pitaya/io/Streams.java +++ b/src/org/pitaya/io/Streams.java @@ -1,106 +1,106 @@ /*----------------------------------------------------------------------------* * This file is part of Pitaya. * * Copyright (C) 2012 Osman KOCAK <[email protected]> * * * * This program is free software: you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation, either version 3 of the License, or (at your * * option) any later version. * * This program is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * * License for more details. * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * *----------------------------------------------------------------------------*/ package org.pitaya.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Utiliy methods to deal with {@link InputStream}s and {@link OutputStream}s. * * @author Osman KOCAK */ public final class Streams { /** * Forwards the content of the given {@link InputStream} into the given * {@link OutputStream}. * * @param in the stream to read. * @param out the stream to write on. * * @throws NullPointerException if one of the arguments is {@code null}. * @throws IOException if an I/O error occurs during the process. */ public static void pipe(InputStream in, OutputStream out) throws IOException { byte[] buf = new byte[4096]; int len = in.read(buf); while (len >= 0) { out.write(buf, 0, len); - in.read(buf); + len = in.read(buf); } out.flush(); } /** * Silently closes the given {@link InputStream}. * * @param in the stream to close, may be {@code null}. */ public static void close(InputStream in) { if (in != null) { try { in.close(); } catch (IOException ex) { /* Ignored... */ } } } /** * Silently closes the given {@link OutputStream}. * * @param out the stream to close, may be {@code null}. */ public static void close(OutputStream out) { if (out != null) { try { out.flush(); out.close(); } catch (IOException ex) { /* Ignored... */ } } } /** * Reads the content of the given {@link InputStream}. * * @param in the stream to read. * * @return the stream's content. * * @throws IOException if the data cannot be read. */ public static byte[] read(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); pipe(in, out); return out.toByteArray(); } private Streams() { /* ... */ } }
true
true
public static void pipe(InputStream in, OutputStream out) throws IOException { byte[] buf = new byte[4096]; int len = in.read(buf); while (len >= 0) { out.write(buf, 0, len); in.read(buf); } out.flush(); }
public static void pipe(InputStream in, OutputStream out) throws IOException { byte[] buf = new byte[4096]; int len = in.read(buf); while (len >= 0) { out.write(buf, 0, len); len = in.read(buf); } out.flush(); }
diff --git a/signserver/modules/SignServer-ejb/src/java/org/signserver/server/DummyAuthorizer.java b/signserver/modules/SignServer-ejb/src/java/org/signserver/server/DummyAuthorizer.java index efa4a9e14..652b27899 100644 --- a/signserver/modules/SignServer-ejb/src/java/org/signserver/server/DummyAuthorizer.java +++ b/signserver/modules/SignServer-ejb/src/java/org/signserver/server/DummyAuthorizer.java @@ -1,73 +1,73 @@ /************************************************************************* * * * SignServer: The OpenSource Automated Signing Server * * * * This software 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 any later version. * * * * See terms of license at gnu.org. * * * *************************************************************************/ package org.signserver.server; import java.security.cert.X509Certificate; import javax.persistence.EntityManager; import org.ejbca.util.CertTools; import org.signserver.common.GenericSignRequest; import org.signserver.common.ProcessRequest; import org.signserver.common.IllegalRequestException; import org.signserver.common.RequestContext; import org.signserver.common.SignServerException; import org.signserver.common.WorkerConfig; /** * Dummy authorizer used for testing and demonstration purposes * * * @author Philip Vendil 24 nov 2007 * * @version $Id$ */ public class DummyAuthorizer implements IAuthorizer { /** * @see org.signserver.server.IAuthorizer#init(int, org.signserver.common.WorkerConfig, javax.persistence.EntityManager) */ public void init(int workerId, WorkerConfig config, EntityManager em) throws SignServerException { if(config.getProperties().getProperty("TESTAUTHPROP") == null){ throw new SignServerException("Error initializing DummyAuthorizer, TESTAUTHPROP must be set"); } } /** * @see org.signserver.server.IAuthorizer#isAuthorized(ProcessRequest, RequestContext) */ public void isAuthorized(ProcessRequest request,RequestContext requestContext) throws SignServerException, IllegalRequestException { String clientIP = (String) requestContext.get(RequestContext.REMOTE_IP); X509Certificate clientCert = (X509Certificate) requestContext.get(RequestContext.CLIENT_CERTIFICATE); if(clientIP != null && !clientIP.equals("1.2.3.4")){ throw new IllegalRequestException("Not authorized"); } - if(clientCert != null && (CertTools.stringToBCDNString(clientCert.getSubjectDN().toString()).equals("CN=timestamptest,O=PrimeKey Solution AB")) - || clientCert.getSerialNumber().toString(16).equalsIgnoreCase("58ece0453711fe20")) { + if(clientCert != null && (CertTools.stringToBCDNString(clientCert.getSubjectDN().toString()).equals("CN=timestamptest,O=PrimeKey Solution AB") + || clientCert.getSerialNumber().toString(16).equalsIgnoreCase("58ece0453711fe20"))) { throw new IllegalRequestException("Not authorized"); } if(request instanceof GenericSignRequest && ((GenericSignRequest) request).getRequestID() != 1){ throw new IllegalRequestException("Not authorized"); } } }
true
true
public void isAuthorized(ProcessRequest request,RequestContext requestContext) throws SignServerException, IllegalRequestException { String clientIP = (String) requestContext.get(RequestContext.REMOTE_IP); X509Certificate clientCert = (X509Certificate) requestContext.get(RequestContext.CLIENT_CERTIFICATE); if(clientIP != null && !clientIP.equals("1.2.3.4")){ throw new IllegalRequestException("Not authorized"); } if(clientCert != null && (CertTools.stringToBCDNString(clientCert.getSubjectDN().toString()).equals("CN=timestamptest,O=PrimeKey Solution AB")) || clientCert.getSerialNumber().toString(16).equalsIgnoreCase("58ece0453711fe20")) { throw new IllegalRequestException("Not authorized"); } if(request instanceof GenericSignRequest && ((GenericSignRequest) request).getRequestID() != 1){ throw new IllegalRequestException("Not authorized"); } }
public void isAuthorized(ProcessRequest request,RequestContext requestContext) throws SignServerException, IllegalRequestException { String clientIP = (String) requestContext.get(RequestContext.REMOTE_IP); X509Certificate clientCert = (X509Certificate) requestContext.get(RequestContext.CLIENT_CERTIFICATE); if(clientIP != null && !clientIP.equals("1.2.3.4")){ throw new IllegalRequestException("Not authorized"); } if(clientCert != null && (CertTools.stringToBCDNString(clientCert.getSubjectDN().toString()).equals("CN=timestamptest,O=PrimeKey Solution AB") || clientCert.getSerialNumber().toString(16).equalsIgnoreCase("58ece0453711fe20"))) { throw new IllegalRequestException("Not authorized"); } if(request instanceof GenericSignRequest && ((GenericSignRequest) request).getRequestID() != 1){ throw new IllegalRequestException("Not authorized"); } }
diff --git a/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java b/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java index b8ba59861..99918daa1 100644 --- a/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java +++ b/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java @@ -1,602 +1,597 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings.inputmethod; import com.android.settings.R; import com.android.settings.Settings.KeyboardLayoutPickerActivity; import com.android.settings.Settings.SpellCheckersSettingsActivity; import com.android.settings.SettingsPreferenceFragment; import com.android.settings.Utils; import com.android.settings.VoiceInputOutputSettings; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.content.res.Resources; import android.database.ContentObserver; import android.hardware.input.InputManager; import android.hardware.input.KeyboardLayout; import android.os.Bundle; import android.os.Handler; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceCategory; import android.preference.PreferenceScreen; import android.provider.Settings; import android.provider.Settings.System; import android.text.TextUtils; import android.view.InputDevice; import android.view.inputmethod.InputMethodInfo; import android.view.inputmethod.InputMethodManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.TreeSet; public class InputMethodAndLanguageSettings extends SettingsPreferenceFragment implements Preference.OnPreferenceChangeListener, InputManager.InputDeviceListener, KeyboardLayoutDialogFragment.OnSetupKeyboardLayoutsListener { private static final String KEY_PHONE_LANGUAGE = "phone_language"; private static final String KEY_CURRENT_INPUT_METHOD = "current_input_method"; private static final String KEY_INPUT_METHOD_SELECTOR = "input_method_selector"; private static final String KEY_USER_DICTIONARY_SETTINGS = "key_user_dictionary_settings"; private static final String KEY_IME_SWITCHER = "status_bar_ime_switcher"; private static final String KEY_STYLUS_ICON_ENABLED = "stylus_icon_enabled"; private static final String VOLUME_KEY_CURSOR_CONTROL = "volume_key_cursor_control"; // false: on ICS or later private static final boolean SHOW_INPUT_METHOD_SWITCHER_SETTINGS = false; private static final String[] sSystemSettingNames = { System.TEXT_AUTO_REPLACE, System.TEXT_AUTO_CAPS, System.TEXT_AUTO_PUNCTUATE, }; private static final String[] sHardKeyboardKeys = { "auto_replace", "auto_caps", "auto_punctuate", }; private CheckBoxPreference mStylusIconEnabled; private CheckBoxPreference mStatusBarImeSwitcher; private int mDefaultInputMethodSelectorVisibility = 0; private ListPreference mShowInputMethodSelectorPref; private PreferenceCategory mKeyboardSettingsCategory; private PreferenceCategory mHardKeyboardCategory; private PreferenceCategory mGameControllerCategory; private Preference mLanguagePref; private final ArrayList<InputMethodPreference> mInputMethodPreferenceList = new ArrayList<InputMethodPreference>(); private final ArrayList<PreferenceScreen> mHardKeyboardPreferenceList = new ArrayList<PreferenceScreen>(); private InputManager mIm; private InputMethodManager mImm; private List<InputMethodInfo> mImis; private boolean mIsOnlyImeSettings; private Handler mHandler; @SuppressWarnings("unused") private SettingsObserver mSettingsObserver; private Intent mIntentWaitingForResult; private ListPreference mVolumeKeyCursorControl; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.language_settings); try { mDefaultInputMethodSelectorVisibility = Integer.valueOf( getString(R.string.input_method_selector_visibility_default_value)); } catch (NumberFormatException e) { } if (getActivity().getAssets().getLocales().length == 1) { // No "Select language" pref if there's only one system locale available. getPreferenceScreen().removePreference(findPreference(KEY_PHONE_LANGUAGE)); } else { mLanguagePref = findPreference(KEY_PHONE_LANGUAGE); } if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) { mShowInputMethodSelectorPref = (ListPreference)findPreference( KEY_INPUT_METHOD_SELECTOR); mShowInputMethodSelectorPref.setOnPreferenceChangeListener(this); // TODO: Update current input method name on summary updateInputMethodSelectorSummary(loadInputMethodSelectorVisibility()); } new VoiceInputOutputSettings(this).onCreate(); // Get references to dynamically constructed categories. mHardKeyboardCategory = (PreferenceCategory)findPreference("hard_keyboard"); mKeyboardSettingsCategory = (PreferenceCategory)findPreference( "keyboard_settings_category"); mGameControllerCategory = (PreferenceCategory)findPreference( "game_controller_settings_category"); // Filter out irrelevant features if invoked from IME settings button. mIsOnlyImeSettings = Settings.ACTION_INPUT_METHOD_SETTINGS.equals( getActivity().getIntent().getAction()); getActivity().getIntent().setAction(null); if (mIsOnlyImeSettings) { getPreferenceScreen().removeAll(); getPreferenceScreen().addPreference(mHardKeyboardCategory); if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) { getPreferenceScreen().addPreference(mShowInputMethodSelectorPref); } getPreferenceScreen().addPreference(mKeyboardSettingsCategory); } // Build IME preference category. mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); mImis = mImm.getInputMethodList(); mKeyboardSettingsCategory.removeAll(); if (!mIsOnlyImeSettings) { final PreferenceScreen currentIme = new PreferenceScreen(getActivity(), null); currentIme.setKey(KEY_CURRENT_INPUT_METHOD); currentIme.setTitle(getResources().getString(R.string.current_input_method)); mKeyboardSettingsCategory.addPreference(currentIme); } mInputMethodPreferenceList.clear(); final int N = (mImis == null ? 0 : mImis.size()); for (int i = 0; i < N; ++i) { final InputMethodInfo imi = mImis.get(i); final InputMethodPreference pref = getInputMethodPreference(imi, N); mInputMethodPreferenceList.add(pref); } if (!mInputMethodPreferenceList.isEmpty()) { Collections.sort(mInputMethodPreferenceList); for (int i = 0; i < N; ++i) { mKeyboardSettingsCategory.addPreference(mInputMethodPreferenceList.get(i)); } } // Build hard keyboard and game controller preference categories. mIm = (InputManager)getActivity().getSystemService(Context.INPUT_SERVICE); updateInputDevices(); - // Enable or disable mStatusBarImeSwitcher based on boolean value: config_show_cmIMESwitcher - if (!getResources().getBoolean(com.android.internal.R.bool.config_show_cmIMESwitcher)) { - getPreferenceScreen().removePreference(findPreference(KEY_IME_SWITCHER)); - } else { - mStatusBarImeSwitcher = (CheckBoxPreference) findPreference(KEY_IME_SWITCHER); - } + mStatusBarImeSwitcher = (CheckBoxPreference) findPreference(KEY_IME_SWITCHER); mStylusIconEnabled = (CheckBoxPreference) findPreference(KEY_STYLUS_ICON_ENABLED); // Spell Checker final Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClass(getActivity(), SpellCheckersSettingsActivity.class); final SpellCheckersPreference scp = ((SpellCheckersPreference)findPreference( "spellcheckers_settings")); if (scp != null) { scp.setFragmentIntent(this, intent); } mVolumeKeyCursorControl = (ListPreference) findPreference(VOLUME_KEY_CURSOR_CONTROL); if(mVolumeKeyCursorControl != null) { mVolumeKeyCursorControl.setOnPreferenceChangeListener(this); mVolumeKeyCursorControl.setValue(Integer.toString(Settings.System.getInt(getActivity() .getContentResolver(), Settings.System.VOLUME_KEY_CURSOR_CONTROL, 0))); mVolumeKeyCursorControl.setSummary(mVolumeKeyCursorControl.getEntry()); } mHandler = new Handler(); mSettingsObserver = new SettingsObserver(mHandler, getActivity()); } private void updateInputMethodSelectorSummary(int value) { String[] inputMethodSelectorTitles = getResources().getStringArray( R.array.input_method_selector_titles); if (inputMethodSelectorTitles.length > value) { mShowInputMethodSelectorPref.setSummary(inputMethodSelectorTitles[value]); mShowInputMethodSelectorPref.setValue(String.valueOf(value)); } } private void updateUserDictionaryPreference(Preference userDictionaryPreference) { final Activity activity = getActivity(); final TreeSet<String> localeList = UserDictionaryList.getUserDictionaryLocalesSet(activity); if (null == localeList) { // The locale list is null if and only if the user dictionary service is // not present or disabled. In this case we need to remove the preference. getPreferenceScreen().removePreference(userDictionaryPreference); } else if (localeList.size() <= 1) { final Intent intent = new Intent(UserDictionaryList.USER_DICTIONARY_SETTINGS_INTENT_ACTION); userDictionaryPreference.setTitle(R.string.user_dict_single_settings_title); userDictionaryPreference.setIntent(intent); userDictionaryPreference.setFragment( com.android.settings.UserDictionarySettings.class.getName()); // If the size of localeList is 0, we don't set the locale parameter in the // extras. This will be interpreted by the UserDictionarySettings class as // meaning "the current locale". // Note that with the current code for UserDictionaryList#getUserDictionaryLocalesSet() // the locale list always has at least one element, since it always includes the current // locale explicitly. @see UserDictionaryList.getUserDictionaryLocalesSet(). if (localeList.size() == 1) { final String locale = (String)localeList.toArray()[0]; userDictionaryPreference.getExtras().putString("locale", locale); } } else { userDictionaryPreference.setTitle(R.string.user_dict_multiple_settings_title); userDictionaryPreference.setFragment(UserDictionaryList.class.getName()); } } @Override public void onResume() { super.onResume(); mIm.registerInputDeviceListener(this, null); if (!mIsOnlyImeSettings) { if (mLanguagePref != null) { Configuration conf = getResources().getConfiguration(); String language = conf.locale.getLanguage(); String localeString; // TODO: This is not an accurate way to display the locale, as it is // just working around the fact that we support limited dialects // and want to pretend that the language is valid for all locales. // We need a way to support languages that aren't tied to a particular // locale instead of hiding the locale qualifier. if (hasOnlyOneLanguageInstance(language, Resources.getSystem().getAssets().getLocales())) { localeString = conf.locale.getDisplayLanguage(conf.locale); } else { localeString = conf.locale.getDisplayName(conf.locale); } if (localeString.length() > 1) { localeString = Character.toUpperCase(localeString.charAt(0)) + localeString.substring(1); mLanguagePref.setSummary(localeString); } } updateUserDictionaryPreference(findPreference(KEY_USER_DICTIONARY_SETTINGS)); if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) { mShowInputMethodSelectorPref.setOnPreferenceChangeListener(this); } } if (mStatusBarImeSwitcher != null) { mStatusBarImeSwitcher.setChecked(Settings.System.getInt(getActivity().getContentResolver(), Settings.System.STATUS_BAR_IME_SWITCHER, 1) != 0); } if (mStylusIconEnabled != null) { mStylusIconEnabled.setChecked(Settings.System.getInt(getActivity().getContentResolver(), Settings.System.STYLUS_ICON_ENABLED, 0) == 1); } // Hard keyboard if (!mHardKeyboardPreferenceList.isEmpty()) { for (int i = 0; i < sHardKeyboardKeys.length; ++i) { CheckBoxPreference chkPref = (CheckBoxPreference) mHardKeyboardCategory.findPreference(sHardKeyboardKeys[i]); chkPref.setChecked( System.getInt(getContentResolver(), sSystemSettingNames[i], 1) > 0); } } updateInputDevices(); // IME InputMethodAndSubtypeUtil.loadInputMethodSubtypeList( this, getContentResolver(), mImis, null); updateActiveInputMethodsSummary(); } @Override public void onPause() { super.onPause(); mIm.unregisterInputDeviceListener(this); if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) { mShowInputMethodSelectorPref.setOnPreferenceChangeListener(null); } InputMethodAndSubtypeUtil.saveInputMethodSubtypeList( this, getContentResolver(), mImis, !mHardKeyboardPreferenceList.isEmpty()); } @Override public void onInputDeviceAdded(int deviceId) { updateInputDevices(); } @Override public void onInputDeviceChanged(int deviceId) { updateInputDevices(); } @Override public void onInputDeviceRemoved(int deviceId) { updateInputDevices(); } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { // Input Method stuff if (Utils.isMonkeyRunning()) { return false; } if (preference == mStatusBarImeSwitcher) { Settings.System.putInt(getActivity().getContentResolver(), Settings.System.STATUS_BAR_IME_SWITCHER, mStatusBarImeSwitcher.isChecked() ? 1 : 0); return true; } else if (preference == mStylusIconEnabled) { Settings.System.putInt(getActivity().getContentResolver(), Settings.System.STYLUS_ICON_ENABLED, mStylusIconEnabled.isChecked() ? 1 : 0); } else if (preference instanceof PreferenceScreen) { if (preference.getFragment() != null) { // Fragment will be handled correctly by the super class. } else if (KEY_CURRENT_INPUT_METHOD.equals(preference.getKey())) { final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showInputMethodPicker(); } } else if (preference instanceof CheckBoxPreference) { final CheckBoxPreference chkPref = (CheckBoxPreference) preference; if (!mHardKeyboardPreferenceList.isEmpty()) { for (int i = 0; i < sHardKeyboardKeys.length; ++i) { if (chkPref == mHardKeyboardCategory.findPreference(sHardKeyboardKeys[i])) { System.putInt(getContentResolver(), sSystemSettingNames[i], chkPref.isChecked() ? 1 : 0); return true; } } } if (chkPref == mGameControllerCategory.findPreference("vibrate_input_devices")) { System.putInt(getContentResolver(), Settings.System.VIBRATE_INPUT_DEVICES, chkPref.isChecked() ? 1 : 0); return true; } } return super.onPreferenceTreeClick(preferenceScreen, preference); } private boolean hasOnlyOneLanguageInstance(String languageCode, String[] locales) { int count = 0; for (String localeCode : locales) { if (localeCode.length() > 2 && localeCode.startsWith(languageCode)) { count++; if (count > 1) { return false; } } } return count == 1; } private void saveInputMethodSelectorVisibility(String value) { try { int intValue = Integer.valueOf(value); Settings.Secure.putInt(getContentResolver(), Settings.Secure.INPUT_METHOD_SELECTOR_VISIBILITY, intValue); updateInputMethodSelectorSummary(intValue); } catch(NumberFormatException e) { } } private int loadInputMethodSelectorVisibility() { return Settings.Secure.getInt(getContentResolver(), Settings.Secure.INPUT_METHOD_SELECTOR_VISIBILITY, mDefaultInputMethodSelectorVisibility); } @Override public boolean onPreferenceChange(Preference preference, Object value) { if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) { if (preference == mShowInputMethodSelectorPref) { if (value instanceof String) { saveInputMethodSelectorVisibility((String)value); } } } if (preference == mVolumeKeyCursorControl) { String volumeKeyCursorControl = (String) value; int val = Integer.parseInt(volumeKeyCursorControl); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.VOLUME_KEY_CURSOR_CONTROL, val); int index = mVolumeKeyCursorControl.findIndexOfValue(volumeKeyCursorControl); mVolumeKeyCursorControl.setSummary(mVolumeKeyCursorControl.getEntries()[index]); return true; } return false; } private void updateActiveInputMethodsSummary() { for (Preference pref : mInputMethodPreferenceList) { if (pref instanceof InputMethodPreference) { ((InputMethodPreference)pref).updateSummary(); } } updateCurrentImeName(); } private void updateCurrentImeName() { final Context context = getActivity(); if (context == null || mImm == null) return; final Preference curPref = getPreferenceScreen().findPreference(KEY_CURRENT_INPUT_METHOD); if (curPref != null) { final CharSequence curIme = InputMethodAndSubtypeUtil.getCurrentInputMethodName( context, getContentResolver(), mImm, mImis, getPackageManager()); if (!TextUtils.isEmpty(curIme)) { synchronized(this) { curPref.setSummary(curIme); } } } } private InputMethodPreference getInputMethodPreference(InputMethodInfo imi, int imiSize) { final PackageManager pm = getPackageManager(); final CharSequence label = imi.loadLabel(pm); // IME settings final Intent intent; final String settingsActivity = imi.getSettingsActivity(); if (!TextUtils.isEmpty(settingsActivity)) { intent = new Intent(Intent.ACTION_MAIN); intent.setClassName(imi.getPackageName(), settingsActivity); } else { intent = null; } // Add a check box for enabling/disabling IME InputMethodPreference pref = new InputMethodPreference(this, intent, mImm, imi, imiSize); pref.setKey(imi.getId()); pref.setTitle(label); return pref; } private void updateInputDevices() { updateHardKeyboards(); updateGameControllers(); } private void updateHardKeyboards() { mHardKeyboardPreferenceList.clear(); if (getResources().getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY) { final int[] devices = InputDevice.getDeviceIds(); for (int i = 0; i < devices.length; i++) { InputDevice device = InputDevice.getDevice(devices[i]); if (device != null && !device.isVirtual() && device.isFullKeyboard()) { final String inputDeviceDescriptor = device.getDescriptor(); final String keyboardLayoutDescriptor = mIm.getCurrentKeyboardLayoutForInputDevice(inputDeviceDescriptor); final KeyboardLayout keyboardLayout = keyboardLayoutDescriptor != null ? mIm.getKeyboardLayout(keyboardLayoutDescriptor) : null; final PreferenceScreen pref = new PreferenceScreen(getActivity(), null); pref.setTitle(device.getName()); if (keyboardLayout != null) { pref.setSummary(keyboardLayout.toString()); } else { pref.setSummary(R.string.keyboard_layout_default_label); } pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { showKeyboardLayoutDialog(inputDeviceDescriptor); return true; } }); mHardKeyboardPreferenceList.add(pref); } } } if (!mHardKeyboardPreferenceList.isEmpty()) { for (int i = mHardKeyboardCategory.getPreferenceCount(); i-- > 0; ) { final Preference pref = mHardKeyboardCategory.getPreference(i); if (pref.getOrder() < 1000) { mHardKeyboardCategory.removePreference(pref); } } Collections.sort(mHardKeyboardPreferenceList); final int count = mHardKeyboardPreferenceList.size(); for (int i = 0; i < count; i++) { final Preference pref = mHardKeyboardPreferenceList.get(i); pref.setOrder(i); mHardKeyboardCategory.addPreference(pref); } getPreferenceScreen().addPreference(mHardKeyboardCategory); } else { getPreferenceScreen().removePreference(mHardKeyboardCategory); } } private void showKeyboardLayoutDialog(String inputDeviceDescriptor) { KeyboardLayoutDialogFragment fragment = new KeyboardLayoutDialogFragment(inputDeviceDescriptor); fragment.setTargetFragment(this, 0); fragment.show(getActivity().getFragmentManager(), "keyboardLayout"); } @Override public void onSetupKeyboardLayouts(String inputDeviceDescriptor) { final Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClass(getActivity(), KeyboardLayoutPickerActivity.class); intent.putExtra(KeyboardLayoutPickerFragment.EXTRA_INPUT_DEVICE_DESCRIPTOR, inputDeviceDescriptor); mIntentWaitingForResult = intent; startActivityForResult(intent, 0); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (mIntentWaitingForResult != null) { String inputDeviceDescriptor = mIntentWaitingForResult.getStringExtra( KeyboardLayoutPickerFragment.EXTRA_INPUT_DEVICE_DESCRIPTOR); mIntentWaitingForResult = null; showKeyboardLayoutDialog(inputDeviceDescriptor); } } private void updateGameControllers() { if (haveInputDeviceWithVibrator()) { getPreferenceScreen().addPreference(mGameControllerCategory); CheckBoxPreference chkPref = (CheckBoxPreference) mGameControllerCategory.findPreference("vibrate_input_devices"); chkPref.setChecked(System.getInt(getContentResolver(), Settings.System.VIBRATE_INPUT_DEVICES, 1) > 0); } else { getPreferenceScreen().removePreference(mGameControllerCategory); } } private boolean haveInputDeviceWithVibrator() { final int[] devices = InputDevice.getDeviceIds(); for (int i = 0; i < devices.length; i++) { InputDevice device = InputDevice.getDevice(devices[i]); if (device != null && !device.isVirtual() && device.getVibrator().hasVibrator()) { return true; } } return false; } private class SettingsObserver extends ContentObserver { public SettingsObserver(Handler handler, Context context) { super(handler); final ContentResolver cr = context.getContentResolver(); cr.registerContentObserver( Settings.Secure.getUriFor(Settings.Secure.DEFAULT_INPUT_METHOD), false, this); cr.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE), false, this); } @Override public void onChange(boolean selfChange) { updateCurrentImeName(); } } }
true
true
public void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.language_settings); try { mDefaultInputMethodSelectorVisibility = Integer.valueOf( getString(R.string.input_method_selector_visibility_default_value)); } catch (NumberFormatException e) { } if (getActivity().getAssets().getLocales().length == 1) { // No "Select language" pref if there's only one system locale available. getPreferenceScreen().removePreference(findPreference(KEY_PHONE_LANGUAGE)); } else { mLanguagePref = findPreference(KEY_PHONE_LANGUAGE); } if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) { mShowInputMethodSelectorPref = (ListPreference)findPreference( KEY_INPUT_METHOD_SELECTOR); mShowInputMethodSelectorPref.setOnPreferenceChangeListener(this); // TODO: Update current input method name on summary updateInputMethodSelectorSummary(loadInputMethodSelectorVisibility()); } new VoiceInputOutputSettings(this).onCreate(); // Get references to dynamically constructed categories. mHardKeyboardCategory = (PreferenceCategory)findPreference("hard_keyboard"); mKeyboardSettingsCategory = (PreferenceCategory)findPreference( "keyboard_settings_category"); mGameControllerCategory = (PreferenceCategory)findPreference( "game_controller_settings_category"); // Filter out irrelevant features if invoked from IME settings button. mIsOnlyImeSettings = Settings.ACTION_INPUT_METHOD_SETTINGS.equals( getActivity().getIntent().getAction()); getActivity().getIntent().setAction(null); if (mIsOnlyImeSettings) { getPreferenceScreen().removeAll(); getPreferenceScreen().addPreference(mHardKeyboardCategory); if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) { getPreferenceScreen().addPreference(mShowInputMethodSelectorPref); } getPreferenceScreen().addPreference(mKeyboardSettingsCategory); } // Build IME preference category. mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); mImis = mImm.getInputMethodList(); mKeyboardSettingsCategory.removeAll(); if (!mIsOnlyImeSettings) { final PreferenceScreen currentIme = new PreferenceScreen(getActivity(), null); currentIme.setKey(KEY_CURRENT_INPUT_METHOD); currentIme.setTitle(getResources().getString(R.string.current_input_method)); mKeyboardSettingsCategory.addPreference(currentIme); } mInputMethodPreferenceList.clear(); final int N = (mImis == null ? 0 : mImis.size()); for (int i = 0; i < N; ++i) { final InputMethodInfo imi = mImis.get(i); final InputMethodPreference pref = getInputMethodPreference(imi, N); mInputMethodPreferenceList.add(pref); } if (!mInputMethodPreferenceList.isEmpty()) { Collections.sort(mInputMethodPreferenceList); for (int i = 0; i < N; ++i) { mKeyboardSettingsCategory.addPreference(mInputMethodPreferenceList.get(i)); } } // Build hard keyboard and game controller preference categories. mIm = (InputManager)getActivity().getSystemService(Context.INPUT_SERVICE); updateInputDevices(); // Enable or disable mStatusBarImeSwitcher based on boolean value: config_show_cmIMESwitcher if (!getResources().getBoolean(com.android.internal.R.bool.config_show_cmIMESwitcher)) { getPreferenceScreen().removePreference(findPreference(KEY_IME_SWITCHER)); } else { mStatusBarImeSwitcher = (CheckBoxPreference) findPreference(KEY_IME_SWITCHER); } mStylusIconEnabled = (CheckBoxPreference) findPreference(KEY_STYLUS_ICON_ENABLED); // Spell Checker final Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClass(getActivity(), SpellCheckersSettingsActivity.class); final SpellCheckersPreference scp = ((SpellCheckersPreference)findPreference( "spellcheckers_settings")); if (scp != null) { scp.setFragmentIntent(this, intent); } mVolumeKeyCursorControl = (ListPreference) findPreference(VOLUME_KEY_CURSOR_CONTROL); if(mVolumeKeyCursorControl != null) { mVolumeKeyCursorControl.setOnPreferenceChangeListener(this); mVolumeKeyCursorControl.setValue(Integer.toString(Settings.System.getInt(getActivity() .getContentResolver(), Settings.System.VOLUME_KEY_CURSOR_CONTROL, 0))); mVolumeKeyCursorControl.setSummary(mVolumeKeyCursorControl.getEntry()); } mHandler = new Handler(); mSettingsObserver = new SettingsObserver(mHandler, getActivity()); }
public void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.language_settings); try { mDefaultInputMethodSelectorVisibility = Integer.valueOf( getString(R.string.input_method_selector_visibility_default_value)); } catch (NumberFormatException e) { } if (getActivity().getAssets().getLocales().length == 1) { // No "Select language" pref if there's only one system locale available. getPreferenceScreen().removePreference(findPreference(KEY_PHONE_LANGUAGE)); } else { mLanguagePref = findPreference(KEY_PHONE_LANGUAGE); } if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) { mShowInputMethodSelectorPref = (ListPreference)findPreference( KEY_INPUT_METHOD_SELECTOR); mShowInputMethodSelectorPref.setOnPreferenceChangeListener(this); // TODO: Update current input method name on summary updateInputMethodSelectorSummary(loadInputMethodSelectorVisibility()); } new VoiceInputOutputSettings(this).onCreate(); // Get references to dynamically constructed categories. mHardKeyboardCategory = (PreferenceCategory)findPreference("hard_keyboard"); mKeyboardSettingsCategory = (PreferenceCategory)findPreference( "keyboard_settings_category"); mGameControllerCategory = (PreferenceCategory)findPreference( "game_controller_settings_category"); // Filter out irrelevant features if invoked from IME settings button. mIsOnlyImeSettings = Settings.ACTION_INPUT_METHOD_SETTINGS.equals( getActivity().getIntent().getAction()); getActivity().getIntent().setAction(null); if (mIsOnlyImeSettings) { getPreferenceScreen().removeAll(); getPreferenceScreen().addPreference(mHardKeyboardCategory); if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) { getPreferenceScreen().addPreference(mShowInputMethodSelectorPref); } getPreferenceScreen().addPreference(mKeyboardSettingsCategory); } // Build IME preference category. mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); mImis = mImm.getInputMethodList(); mKeyboardSettingsCategory.removeAll(); if (!mIsOnlyImeSettings) { final PreferenceScreen currentIme = new PreferenceScreen(getActivity(), null); currentIme.setKey(KEY_CURRENT_INPUT_METHOD); currentIme.setTitle(getResources().getString(R.string.current_input_method)); mKeyboardSettingsCategory.addPreference(currentIme); } mInputMethodPreferenceList.clear(); final int N = (mImis == null ? 0 : mImis.size()); for (int i = 0; i < N; ++i) { final InputMethodInfo imi = mImis.get(i); final InputMethodPreference pref = getInputMethodPreference(imi, N); mInputMethodPreferenceList.add(pref); } if (!mInputMethodPreferenceList.isEmpty()) { Collections.sort(mInputMethodPreferenceList); for (int i = 0; i < N; ++i) { mKeyboardSettingsCategory.addPreference(mInputMethodPreferenceList.get(i)); } } // Build hard keyboard and game controller preference categories. mIm = (InputManager)getActivity().getSystemService(Context.INPUT_SERVICE); updateInputDevices(); mStatusBarImeSwitcher = (CheckBoxPreference) findPreference(KEY_IME_SWITCHER); mStylusIconEnabled = (CheckBoxPreference) findPreference(KEY_STYLUS_ICON_ENABLED); // Spell Checker final Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClass(getActivity(), SpellCheckersSettingsActivity.class); final SpellCheckersPreference scp = ((SpellCheckersPreference)findPreference( "spellcheckers_settings")); if (scp != null) { scp.setFragmentIntent(this, intent); } mVolumeKeyCursorControl = (ListPreference) findPreference(VOLUME_KEY_CURSOR_CONTROL); if(mVolumeKeyCursorControl != null) { mVolumeKeyCursorControl.setOnPreferenceChangeListener(this); mVolumeKeyCursorControl.setValue(Integer.toString(Settings.System.getInt(getActivity() .getContentResolver(), Settings.System.VOLUME_KEY_CURSOR_CONTROL, 0))); mVolumeKeyCursorControl.setSummary(mVolumeKeyCursorControl.getEntry()); } mHandler = new Handler(); mSettingsObserver = new SettingsObserver(mHandler, getActivity()); }
diff --git a/src/java/org/apache/cassandra/db/SystemTable.java b/src/java/org/apache/cassandra/db/SystemTable.java index 88825a758..eb6eecd70 100644 --- a/src/java/org/apache/cassandra/db/SystemTable.java +++ b/src/java/org/apache/cassandra/db/SystemTable.java @@ -1,647 +1,647 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.db; import java.net.InetAddress; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.util.*; import java.util.concurrent.ExecutionException; import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.config.KSMetaData; import org.apache.cassandra.config.Schema; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.cql3.QueryProcessor; import org.apache.cassandra.cql3.UntypedResultSet; import org.apache.cassandra.db.columniterator.IdentityQueryFilter; import org.apache.cassandra.db.filter.QueryFilter; import org.apache.cassandra.db.filter.QueryPath; import org.apache.cassandra.db.marshal.AsciiType; import org.apache.cassandra.db.marshal.BytesType; import org.apache.cassandra.db.marshal.UTF8Type; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.locator.IEndpointSnitch; import org.apache.cassandra.service.StorageService; import org.apache.cassandra.thrift.Constants; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.CounterId; import org.apache.cassandra.utils.FBUtilities; import static org.apache.cassandra.cql3.QueryProcessor.processInternal; public class SystemTable { private static final Logger logger = LoggerFactory.getLogger(SystemTable.class); // see CFMetaData for schema definitions public static final String PEERS_CF = "peers"; public static final String LOCAL_CF = "local"; public static final String INDEX_CF = "IndexInfo"; public static final String COUNTER_ID_CF = "NodeIdInfo"; public static final String HINTS_CF = "hints"; public static final String RANGE_XFERS_CF = "range_xfers"; public static final String BATCHLOG_CF = "batchlog"; // see layout description in the DefsTable class header public static final String SCHEMA_KEYSPACES_CF = "schema_keyspaces"; public static final String SCHEMA_COLUMNFAMILIES_CF = "schema_columnfamilies"; public static final String SCHEMA_COLUMNS_CF = "schema_columns"; @Deprecated public static final String OLD_STATUS_CF = "LocationInfo"; @Deprecated public static final String OLD_HINTS_CF = "HintsColumnFamily"; private static final String LOCAL_KEY = "local"; private static final ByteBuffer CURRENT_LOCAL_NODE_ID_KEY = ByteBufferUtil.bytes("CurrentLocal"); private static final ByteBuffer ALL_LOCAL_NODE_ID_KEY = ByteBufferUtil.bytes("Local"); public enum BootstrapState { NEEDS_BOOTSTRAP, COMPLETED, IN_PROGRESS } private static DecoratedKey decorate(ByteBuffer key) { return StorageService.getPartitioner().decorateKey(key); } public static void finishStartup() { DefsTable.fixSchemaNanoTimestamps(); setupVersion(); try { upgradeSystemData(); } catch (ExecutionException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } // add entries to system schema columnfamilies for the hardcoded system definitions for (String ksname : Schema.systemKeyspaceNames) { KSMetaData ksmd = Schema.instance.getKSMetaData(ksname); // delete old, possibly obsolete entries in schema columnfamilies for (String cfname : Arrays.asList(SystemTable.SCHEMA_KEYSPACES_CF, SystemTable.SCHEMA_COLUMNFAMILIES_CF, SystemTable.SCHEMA_COLUMNS_CF)) { String req = String.format("DELETE FROM system.%s WHERE keyspace_name = '%s'", cfname, ksmd.name); processInternal(req); } // (+1 to timestamp to make sure we don't get shadowed by the tombstones we just added) ksmd.toSchema(FBUtilities.timestampMicros() + 1).apply(); } } private static void setupVersion() { String req = "INSERT INTO system.%s (key, release_version, cql_version, thrift_version, data_center, rack) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')"; IEndpointSnitch snitch = DatabaseDescriptor.getEndpointSnitch(); processInternal(String.format(req, LOCAL_CF, LOCAL_KEY, FBUtilities.getReleaseVersionString(), QueryProcessor.CQL_VERSION.toString(), Constants.VERSION, snitch.getDatacenter(FBUtilities.getBroadcastAddress()), snitch.getRack(FBUtilities.getBroadcastAddress()))); } /** if system data becomes incompatible across versions of cassandra, that logic (and associated purging) is managed here */ private static void upgradeSystemData() throws ExecutionException, InterruptedException { Table table = Table.open(Table.SYSTEM_KS); ColumnFamilyStore oldStatusCfs = table.getColumnFamilyStore(OLD_STATUS_CF); if (oldStatusCfs.getSSTables().size() > 0) { SortedSet<ByteBuffer> cols = new TreeSet<ByteBuffer>(BytesType.instance); cols.add(ByteBufferUtil.bytes("ClusterName")); cols.add(ByteBufferUtil.bytes("Token")); QueryFilter filter = QueryFilter.getNamesFilter(decorate(ByteBufferUtil.bytes("L")), new QueryPath(OLD_STATUS_CF), cols); ColumnFamily oldCf = oldStatusCfs.getColumnFamily(filter); Iterator<IColumn> oldColumns = oldCf.columns.iterator(); String clusterName = null; try { clusterName = ByteBufferUtil.string(oldColumns.next().value()); } catch (CharacterCodingException e) { throw new RuntimeException(e); } // serialize the old token as a collection of (one )tokens. Token token = StorageService.getPartitioner().getTokenFactory().fromByteArray(oldColumns.next().value()); String tokenBytes = serializeTokens(Collections.singleton(token)); // (assume that any node getting upgraded was bootstrapped, since that was stored in a separate row for no particular reason) - String req = "INSERT INTO system.%s (key, cluster_name, tokens, bootstrapped) VALUES ('%s', '%s', '%s', '%s')"; + String req = "INSERT INTO system.%s (key, cluster_name, tokens, bootstrapped) VALUES ('%s', '%s', %s, '%s')"; processInternal(String.format(req, LOCAL_CF, LOCAL_KEY, clusterName, tokenBytes, BootstrapState.COMPLETED.name())); oldStatusCfs.truncate(); } ColumnFamilyStore oldHintsCfs = table.getColumnFamilyStore(OLD_HINTS_CF); if (oldHintsCfs.getSSTables().size() > 0) { logger.info("Possible old-format hints found. Truncating"); oldHintsCfs.truncate(); } } /** * Record tokens being used by another node */ public static synchronized void updateTokens(InetAddress ep, Collection<Token> tokens) { if (ep.equals(FBUtilities.getBroadcastAddress())) { removeTokens(tokens); return; } String req = "INSERT INTO system.%s (peer, tokens) VALUES ('%s', %s)"; processInternal(String.format(req, PEERS_CF, ep.getHostAddress(), serializeTokens(tokens))); forceBlockingFlush(PEERS_CF); } public static synchronized void updatePeerInfo(InetAddress ep, String columnName, String value) { if (ep.equals(FBUtilities.getBroadcastAddress())) return; String req = "INSERT INTO system.%s (peer, %s) VALUES ('%s', '%s')"; processInternal(String.format(req, PEERS_CF, columnName, ep.getHostAddress(), value)); } private static String serializeTokens(Collection<Token> tokens) { Token.TokenFactory factory = StorageService.getPartitioner().getTokenFactory(); StringBuilder sb = new StringBuilder(); sb.append("{"); Iterator<Token> iter = tokens.iterator(); while (iter.hasNext()) { sb.append("'").append(factory.toString(iter.next())).append("'"); if (iter.hasNext()) sb.append(","); } sb.append("}"); return sb.toString(); } private static Collection<Token> deserializeTokens(Collection<String> tokensStrings) { Token.TokenFactory factory = StorageService.getPartitioner().getTokenFactory(); List<Token> tokens = new ArrayList<Token>(tokensStrings.size()); for (String tk : tokensStrings) tokens.add(factory.fromString(tk)); return tokens; } /** * Remove stored tokens being used by another node */ public static synchronized void removeTokens(Collection<Token> tokens) { Set<Token> tokenSet = new HashSet<Token>(tokens); for (Map.Entry<InetAddress, Collection<Token>> entry : loadTokens().asMap().entrySet()) { Set<Token> toRemove = Sets.intersection(tokenSet, ((Set<Token>)entry.getValue())).immutableCopy(); if (toRemove.isEmpty()) continue; String req = "UPDATE system.%s SET tokens = tokens - %s WHERE peer = '%s'"; processInternal(String.format(req, PEERS_CF, serializeTokens(toRemove), entry.getKey().getHostAddress())); } forceBlockingFlush(PEERS_CF); } /** * This method is used to update the System Table with the new tokens for this node */ public static synchronized void updateTokens(Collection<Token> tokens) { String req = "INSERT INTO system.%s (key, tokens) VALUES ('%s', %s)"; processInternal(String.format(req, LOCAL_CF, LOCAL_KEY, serializeTokens(tokens))); forceBlockingFlush(LOCAL_CF); } /** * Convenience method to update the list of tokens in the local system table. * * @param addTokens tokens to add * @param rmTokens tokens to remove * @return the collection of persisted tokens */ public static synchronized Collection<Token> updateLocalTokens(Collection<Token> addTokens, Collection<Token> rmTokens) { Collection<Token> tokens = getSavedTokens(); tokens.removeAll(rmTokens); tokens.addAll(addTokens); updateTokens(tokens); return tokens; } private static void forceBlockingFlush(String cfname) { try { Table.open(Table.SYSTEM_KS).getColumnFamilyStore(cfname).forceBlockingFlush(); } catch (ExecutionException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new AssertionError(e); } } /** * Return a map of stored tokens to IP addresses * */ public static SetMultimap<InetAddress, Token> loadTokens() { SetMultimap<InetAddress, Token> tokenMap = HashMultimap.create(); for (UntypedResultSet.Row row : processInternal("SELECT peer, tokens FROM system." + PEERS_CF)) { InetAddress peer = row.getInetAddress("peer"); if (row.has("tokens")) tokenMap.putAll(peer, deserializeTokens(row.getSet("tokens", UTF8Type.instance))); } return tokenMap; } /** * One of three things will happen if you try to read the system table: * 1. files are present and you can read them: great * 2. no files are there: great (new node is assumed) * 3. files are present but you can't read them: bad * @throws ConfigurationException */ public static void checkHealth() throws ConfigurationException { Table table; try { table = Table.open(Table.SYSTEM_KS); } catch (AssertionError err) { // this happens when a user switches from OPP to RP. ConfigurationException ex = new ConfigurationException("Could not read system table!"); ex.initCause(err); throw ex; } ColumnFamilyStore cfs = table.getColumnFamilyStore(LOCAL_CF); String req = "SELECT cluster_name FROM system.%s WHERE key='%s'"; UntypedResultSet result = processInternal(String.format(req, LOCAL_CF, LOCAL_KEY)); if (result.isEmpty() || !result.one().has("cluster_name")) { // this is a brand new node if (!cfs.getSSTables().isEmpty()) throw new ConfigurationException("Found system table files, but they couldn't be loaded!"); // no system files. this is a new node. req = "INSERT INTO system.%s (key, cluster_name) VALUES ('%s', '%s')"; processInternal(String.format(req, LOCAL_CF, LOCAL_KEY, DatabaseDescriptor.getClusterName())); return; } String savedClusterName = result.one().getString("cluster_name"); if (!DatabaseDescriptor.getClusterName().equals(savedClusterName)) throw new ConfigurationException("Saved cluster name " + savedClusterName + " != configured name " + DatabaseDescriptor.getClusterName()); } public static Collection<Token> getSavedTokens() { String req = "SELECT tokens FROM system.%s WHERE key='%s'"; UntypedResultSet result = processInternal(String.format(req, LOCAL_CF, LOCAL_KEY)); return result.isEmpty() || !result.one().has("tokens") ? Collections.<Token>emptyList() : deserializeTokens(result.one().<String>getSet("tokens", UTF8Type.instance)); } public static int incrementAndGetGeneration() { String req = "SELECT gossip_generation FROM system.%s WHERE key='%s'"; UntypedResultSet result = processInternal(String.format(req, LOCAL_CF, LOCAL_KEY)); int generation; if (result.isEmpty() || !result.one().has("gossip_generation")) { // seconds-since-epoch isn't a foolproof new generation // (where foolproof is "guaranteed to be larger than the last one seen at this ip address"), // but it's as close as sanely possible generation = (int) (System.currentTimeMillis() / 1000); } else { // Other nodes will ignore gossip messages about a node that have a lower generation than previously seen. final int storedGeneration = result.one().getInt("gossip_generation") + 1; final int now = (int) (System.currentTimeMillis() / 1000); if (storedGeneration >= now) { logger.warn("Using stored Gossip Generation {} as it is greater than current system time {}. See CASSANDRA-3654 if you experience problems", storedGeneration, now); generation = storedGeneration; } else { generation = now; } } req = "INSERT INTO system.%s (key, gossip_generation) VALUES ('%s', %d)"; processInternal(String.format(req, LOCAL_CF, LOCAL_KEY, generation)); forceBlockingFlush(LOCAL_CF); return generation; } public static BootstrapState getBootstrapState() { String req = "SELECT bootstrapped FROM system.%s WHERE key='%s'"; UntypedResultSet result = processInternal(String.format(req, LOCAL_CF, LOCAL_KEY)); if (result.isEmpty() || !result.one().has("bootstrapped")) return BootstrapState.NEEDS_BOOTSTRAP; return BootstrapState.valueOf(result.one().getString("bootstrapped")); } public static boolean bootstrapComplete() { return getBootstrapState() == BootstrapState.COMPLETED; } public static boolean bootstrapInProgress() { return getBootstrapState() == BootstrapState.IN_PROGRESS; } public static void setBootstrapState(BootstrapState state) { String req = "INSERT INTO system.%s (key, bootstrapped) VALUES ('%s', '%s')"; processInternal(String.format(req, LOCAL_CF, LOCAL_KEY, state.name())); forceBlockingFlush(LOCAL_CF); } public static boolean isIndexBuilt(String table, String indexName) { ColumnFamilyStore cfs = Table.open(Table.SYSTEM_KS).getColumnFamilyStore(INDEX_CF); QueryFilter filter = QueryFilter.getNamesFilter(decorate(ByteBufferUtil.bytes(table)), new QueryPath(INDEX_CF), ByteBufferUtil.bytes(indexName)); return ColumnFamilyStore.removeDeleted(cfs.getColumnFamily(filter), Integer.MAX_VALUE) != null; } public static void setIndexBuilt(String table, String indexName) { ColumnFamily cf = ColumnFamily.create(Table.SYSTEM_KS, INDEX_CF); cf.addColumn(new Column(ByteBufferUtil.bytes(indexName), ByteBufferUtil.EMPTY_BYTE_BUFFER, FBUtilities.timestampMicros())); RowMutation rm = new RowMutation(Table.SYSTEM_KS, ByteBufferUtil.bytes(table)); rm.add(cf); rm.apply(); forceBlockingFlush(INDEX_CF); } public static void setIndexRemoved(String table, String indexName) { RowMutation rm = new RowMutation(Table.SYSTEM_KS, ByteBufferUtil.bytes(table)); rm.delete(new QueryPath(INDEX_CF, null, ByteBufferUtil.bytes(indexName)), FBUtilities.timestampMicros()); rm.apply(); forceBlockingFlush(INDEX_CF); } /** * Read the host ID from the system table, creating (and storing) one if * none exists. */ public static UUID getLocalHostId() { UUID hostId = null; String req = "SELECT ring_id FROM system.%s WHERE key='%s'"; UntypedResultSet result = processInternal(String.format(req, LOCAL_CF, LOCAL_KEY)); // Look up the Host UUID (return it if found) if (!result.isEmpty() && result.one().has("ring_id")) { return result.one().getUUID("ring_id"); } // ID not found, generate a new one, persist, and then return it. hostId = UUID.randomUUID(); logger.warn("No host ID found, created {} (Note: This should happen exactly once per node).", hostId); req = "INSERT INTO system.%s (key, ring_id) VALUES ('%s', '%s')"; processInternal(String.format(req, LOCAL_CF, LOCAL_KEY, hostId)); return hostId; } /** * Read the current local node id from the system table or null if no * such node id is recorded. */ public static CounterId getCurrentLocalCounterId() { Table table = Table.open(Table.SYSTEM_KS); // Get the last CounterId (since CounterId are timeuuid is thus ordered from the older to the newer one) QueryFilter filter = QueryFilter.getSliceFilter(decorate(ALL_LOCAL_NODE_ID_KEY), new QueryPath(COUNTER_ID_CF), ByteBufferUtil.EMPTY_BYTE_BUFFER, ByteBufferUtil.EMPTY_BYTE_BUFFER, true, 1); ColumnFamily cf = table.getColumnFamilyStore(COUNTER_ID_CF).getColumnFamily(filter); if (cf != null && cf.getColumnCount() != 0) return CounterId.wrap(cf.iterator().next().name()); else return null; } /** * Write a new current local node id to the system table. * * @param oldCounterId the previous local node id (that {@code newCounterId} * replace) or null if no such node id exists (new node or removed system * table) * @param newCounterId the new current local node id to record * @param now microsecond time stamp. */ public static void writeCurrentLocalCounterId(CounterId oldCounterId, CounterId newCounterId, long now) { ByteBuffer ip = ByteBuffer.wrap(FBUtilities.getBroadcastAddress().getAddress()); ColumnFamily cf = ColumnFamily.create(Table.SYSTEM_KS, COUNTER_ID_CF); cf.addColumn(new Column(newCounterId.bytes(), ip, now)); RowMutation rm = new RowMutation(Table.SYSTEM_KS, ALL_LOCAL_NODE_ID_KEY); rm.add(cf); rm.apply(); forceBlockingFlush(COUNTER_ID_CF); } public static List<CounterId.CounterIdRecord> getOldLocalCounterIds() { List<CounterId.CounterIdRecord> l = new ArrayList<CounterId.CounterIdRecord>(); Table table = Table.open(Table.SYSTEM_KS); QueryFilter filter = QueryFilter.getIdentityFilter(decorate(ALL_LOCAL_NODE_ID_KEY), new QueryPath(COUNTER_ID_CF)); ColumnFamily cf = table.getColumnFamilyStore(COUNTER_ID_CF).getColumnFamily(filter); CounterId previous = null; for (IColumn c : cf) { if (previous != null) l.add(new CounterId.CounterIdRecord(previous, c.timestamp())); // this will ignore the last column on purpose since it is the // current local node id previous = CounterId.wrap(c.name()); } return l; } /** * @param cfName The name of the ColumnFamily responsible for part of the schema (keyspace, ColumnFamily, columns) * @return CFS responsible to hold low-level serialized schema */ public static ColumnFamilyStore schemaCFS(String cfName) { return Table.open(Table.SYSTEM_KS).getColumnFamilyStore(cfName); } public static List<Row> serializedSchema() { List<Row> schema = new ArrayList<Row>(3); schema.addAll(serializedSchema(SCHEMA_KEYSPACES_CF)); schema.addAll(serializedSchema(SCHEMA_COLUMNFAMILIES_CF)); schema.addAll(serializedSchema(SCHEMA_COLUMNS_CF)); return schema; } /** * @param schemaCfName The name of the ColumnFamily responsible for part of the schema (keyspace, ColumnFamily, columns) * @return low-level schema representation (each row represents individual Keyspace or ColumnFamily) */ public static List<Row> serializedSchema(String schemaCfName) { Token minToken = StorageService.getPartitioner().getMinimumToken(); return schemaCFS(schemaCfName).getRangeSlice(null, new Range<RowPosition>(minToken.minKeyBound(), minToken.maxKeyBound()), Integer.MAX_VALUE, new IdentityQueryFilter(), null); } public static Collection<RowMutation> serializeSchema() { Map<DecoratedKey, RowMutation> mutationMap = new HashMap<DecoratedKey, RowMutation>(); serializeSchema(mutationMap, SCHEMA_KEYSPACES_CF); serializeSchema(mutationMap, SCHEMA_COLUMNFAMILIES_CF); serializeSchema(mutationMap, SCHEMA_COLUMNS_CF); return mutationMap.values(); } private static void serializeSchema(Map<DecoratedKey, RowMutation> mutationMap, String schemaCfName) { for (Row schemaRow : serializedSchema(schemaCfName)) { if (Schema.ignoredSchemaRow(schemaRow)) continue; RowMutation mutation = mutationMap.get(schemaRow.key); if (mutation == null) { mutationMap.put(schemaRow.key, new RowMutation(Table.SYSTEM_KS, schemaRow)); continue; } mutation.add(schemaRow.cf); } } public static Map<DecoratedKey, ColumnFamily> getSchema(String cfName) { Map<DecoratedKey, ColumnFamily> schema = new HashMap<DecoratedKey, ColumnFamily>(); for (Row schemaEntity : SystemTable.serializedSchema(cfName)) schema.put(schemaEntity.key, schemaEntity.cf); return schema; } public static ByteBuffer getSchemaKSKey(String ksName) { return AsciiType.instance.fromString(ksName); } public static Row readSchemaRow(String ksName) { DecoratedKey key = StorageService.getPartitioner().decorateKey(getSchemaKSKey(ksName)); ColumnFamilyStore schemaCFS = SystemTable.schemaCFS(SCHEMA_KEYSPACES_CF); ColumnFamily result = schemaCFS.getColumnFamily(QueryFilter.getIdentityFilter(key, new QueryPath(SCHEMA_KEYSPACES_CF))); return new Row(key, result); } public static Row readSchemaRow(String ksName, String cfName) { DecoratedKey key = StorageService.getPartitioner().decorateKey(getSchemaKSKey(ksName)); ColumnFamilyStore schemaCFS = SystemTable.schemaCFS(SCHEMA_COLUMNFAMILIES_CF); ColumnFamily result = schemaCFS.getColumnFamily(key, new QueryPath(SCHEMA_COLUMNFAMILIES_CF), DefsTable.searchComposite(cfName, true), DefsTable.searchComposite(cfName, false), false, Integer.MAX_VALUE); return new Row(key, result); } }
true
true
private static void upgradeSystemData() throws ExecutionException, InterruptedException { Table table = Table.open(Table.SYSTEM_KS); ColumnFamilyStore oldStatusCfs = table.getColumnFamilyStore(OLD_STATUS_CF); if (oldStatusCfs.getSSTables().size() > 0) { SortedSet<ByteBuffer> cols = new TreeSet<ByteBuffer>(BytesType.instance); cols.add(ByteBufferUtil.bytes("ClusterName")); cols.add(ByteBufferUtil.bytes("Token")); QueryFilter filter = QueryFilter.getNamesFilter(decorate(ByteBufferUtil.bytes("L")), new QueryPath(OLD_STATUS_CF), cols); ColumnFamily oldCf = oldStatusCfs.getColumnFamily(filter); Iterator<IColumn> oldColumns = oldCf.columns.iterator(); String clusterName = null; try { clusterName = ByteBufferUtil.string(oldColumns.next().value()); } catch (CharacterCodingException e) { throw new RuntimeException(e); } // serialize the old token as a collection of (one )tokens. Token token = StorageService.getPartitioner().getTokenFactory().fromByteArray(oldColumns.next().value()); String tokenBytes = serializeTokens(Collections.singleton(token)); // (assume that any node getting upgraded was bootstrapped, since that was stored in a separate row for no particular reason) String req = "INSERT INTO system.%s (key, cluster_name, tokens, bootstrapped) VALUES ('%s', '%s', '%s', '%s')"; processInternal(String.format(req, LOCAL_CF, LOCAL_KEY, clusterName, tokenBytes, BootstrapState.COMPLETED.name())); oldStatusCfs.truncate(); } ColumnFamilyStore oldHintsCfs = table.getColumnFamilyStore(OLD_HINTS_CF); if (oldHintsCfs.getSSTables().size() > 0) { logger.info("Possible old-format hints found. Truncating"); oldHintsCfs.truncate(); } }
private static void upgradeSystemData() throws ExecutionException, InterruptedException { Table table = Table.open(Table.SYSTEM_KS); ColumnFamilyStore oldStatusCfs = table.getColumnFamilyStore(OLD_STATUS_CF); if (oldStatusCfs.getSSTables().size() > 0) { SortedSet<ByteBuffer> cols = new TreeSet<ByteBuffer>(BytesType.instance); cols.add(ByteBufferUtil.bytes("ClusterName")); cols.add(ByteBufferUtil.bytes("Token")); QueryFilter filter = QueryFilter.getNamesFilter(decorate(ByteBufferUtil.bytes("L")), new QueryPath(OLD_STATUS_CF), cols); ColumnFamily oldCf = oldStatusCfs.getColumnFamily(filter); Iterator<IColumn> oldColumns = oldCf.columns.iterator(); String clusterName = null; try { clusterName = ByteBufferUtil.string(oldColumns.next().value()); } catch (CharacterCodingException e) { throw new RuntimeException(e); } // serialize the old token as a collection of (one )tokens. Token token = StorageService.getPartitioner().getTokenFactory().fromByteArray(oldColumns.next().value()); String tokenBytes = serializeTokens(Collections.singleton(token)); // (assume that any node getting upgraded was bootstrapped, since that was stored in a separate row for no particular reason) String req = "INSERT INTO system.%s (key, cluster_name, tokens, bootstrapped) VALUES ('%s', '%s', %s, '%s')"; processInternal(String.format(req, LOCAL_CF, LOCAL_KEY, clusterName, tokenBytes, BootstrapState.COMPLETED.name())); oldStatusCfs.truncate(); } ColumnFamilyStore oldHintsCfs = table.getColumnFamilyStore(OLD_HINTS_CF); if (oldHintsCfs.getSSTables().size() > 0) { logger.info("Possible old-format hints found. Truncating"); oldHintsCfs.truncate(); } }
diff --git a/cruisecontrol/main/src/net/sourceforge/cruisecontrol/builders/Maven2Script.java b/cruisecontrol/main/src/net/sourceforge/cruisecontrol/builders/Maven2Script.java index 6246c374..db613430 100644 --- a/cruisecontrol/main/src/net/sourceforge/cruisecontrol/builders/Maven2Script.java +++ b/cruisecontrol/main/src/net/sourceforge/cruisecontrol/builders/Maven2Script.java @@ -1,295 +1,298 @@ package net.sourceforge.cruisecontrol.builders; import java.io.File; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.apache.log4j.Logger; import org.jdom.CDATA; import org.jdom.Element; import net.sourceforge.cruisecontrol.CruiseControlException; import net.sourceforge.cruisecontrol.util.Commandline; import net.sourceforge.cruisecontrol.util.StreamConsumer; /** * Maven2 script class based on the Maven builder class from * <a href="mailto:[email protected]">Eric Pugh</a>. * <br /> * Contains all the details related to running a Maven based build. * @author Steria Benelux Sa/Nv - Provided without any warranty */ public class Maven2Script implements Script, StreamConsumer { private static final String ERROR = "error"; private static final String SUCCESS = "success"; private static final Logger LOG = Logger.getLogger(Maven2Script.class); private String goalset; private String mvn; private String pomFile; private String settingsFile; private String flags; private final Element buildLogElement; //Log to store result of the execution for CC private Map buildProperties; private String activateProfiles; private List properties; private int exitCode; private Element currentElement; /** * @param buildLogElement Log to store result of the execution for CC * @param mvn path to the mvn script * @param pomFile path to the pom file * @param goals the goalset to execute * @param settingsFile path to the settings file (not required) * @param activateProfiles comma-delimited list of profiles to activate. (not required) * @param flags extra parameter to pass to mvn e.g.: -U (not required) */ public Maven2Script(Element buildLogElement, String mvn, String pomFile, String goals, String settingsFile, String activateProfiles, String flags) { this.buildLogElement = buildLogElement; this.mvn = mvn; this.pomFile = pomFile; this.goalset = goals; this.settingsFile = settingsFile; this.flags = flags; this.activateProfiles = activateProfiles; } /** * Construct the command that we're going to execute. * @return Commandline holding command to be executed * @throws CruiseControlException */ public Commandline buildCommandline() throws CruiseControlException { //usage: maven [options] [<goal(s)>] [<phase(s)>] Commandline cmdLine = new Commandline(); cmdLine.setExecutable(mvn); //Run in non-interactive mode. cmdLine.createArgument("-B"); //If log is enabled for CC, enable it for mvn if (LOG.isDebugEnabled()) { cmdLine.createArgument("-X"); } //Alternate path for the user settings file if (settingsFile != null) { cmdLine.createArguments("-s", settingsFile); } if (pomFile != null) { cmdLine.createArguments("-f", new File(pomFile).getName()); } //activate specified profiles if (activateProfiles != null) { cmdLine.createArguments("-P", activateProfiles); } if (flags != null) { - cmdLine.createArgument(flags); + StringTokenizer stok = new StringTokenizer(flags, " \t\r\n"); + while (stok.hasMoreTokens()) { + cmdLine.createArgument(stok.nextToken()); + } } if (goalset != null) { StringTokenizer stok = new StringTokenizer(goalset, " \t\r\n"); while (stok.hasMoreTokens()) { cmdLine.createArgument(stok.nextToken()); } } Iterator propertiesIterator = buildProperties.keySet().iterator(); while (propertiesIterator.hasNext()) { final String key = (String) propertiesIterator.next(); final String value = (String) buildProperties.get(key); if (value.indexOf(' ') == -1) { cmdLine.createArgument("-D" + key + "=" + value); } else { // @todo Find better way to handle when property values contains spaces. // Just using Commandline results in entire prop being quoted: // "-Dcvstimestamp=2006-11-29 03:41:04 GMT" // and using Commandline.quoteArgument() results in this when used on value only: // '-Dcvstimestamp="2006-11-29 03:41:04 GMT"' // all these (includeing no manipulation) cause errors in maven's parsing of the command line. // For now, we just replace spaces with underscores so at least some form of the prop is available final String spacelessValue = value.replace(' ', '_'); LOG.warn("Maven2Script altering build property with space. Key:" + key + "; Orig Value:" + value + "; New Value: " + spacelessValue); cmdLine.createArgument("-D" + key + "=" + spacelessValue); } } for (Iterator propsIterator = properties.iterator(); propsIterator.hasNext(); ) { Property property = (Property) propsIterator.next(); cmdLine.createArgument("-D" + property.getName() + "=" + property.getValue()); } //If log is enabled, log the command line if (LOG.isDebugEnabled()) { StringBuffer sb = new StringBuffer(); sb.append("Executing Command: "); String[] args = cmdLine.getCommandline(); for (int i = 0; i < args.length; i++) { String arg = args[i]; sb.append(arg); sb.append(" "); } LOG.debug(sb.toString()); } return cmdLine; } /** * Analyze the output of the mvn command. This is used to detect errors * or successful build. */ public void consumeLine(String line) { final String level; final String infoLine; if (line == null || line.length() == 0 || buildLogElement == null) { return; } synchronized (buildLogElement) { //To detect errors, we will parse the output of the mvn command. //Don't forget that this can stop working if changes are made in mvn. if (line.startsWith("[ERROR]")) { level = "error"; infoLine = line.substring(line.indexOf(']') + 1).trim(); } else if (line.startsWith("[INFO]") || line.startsWith("[DEBUG]")) { level = "info"; infoLine = line.substring(line.indexOf(']') + 1).trim(); } else { level = "info"; infoLine = line; } if (infoLine.startsWith("BUILD SUCCESSFUL")) { buildLogElement.setAttribute(SUCCESS, "BUILD SUCCESSFUL detected"); } else if (infoLine.startsWith("BUILD FAILURE")) { buildLogElement.setAttribute(ERROR, "BUILD FAILURE detected"); } else if (infoLine.startsWith("BUILD ERROR")) { buildLogElement.setAttribute(ERROR, "BUILD ERROR detected"); } else if (infoLine.startsWith("FATAL ERROR")) { buildLogElement.setAttribute(ERROR, "FATAL ERROR detected"); /*} else if (line.startsWith("org.apache.maven.MavenException")) { buildLogElement.setAttribute("error", "You have encountered an unknown error running Maven: " + line); } else if (line.startsWith("The build cannot continue")) { buildLogElement.setAttribute("error", "The build cannot continue: Unsatisfied Dependency");*/ } else if (infoLine.startsWith("[") && infoLine.endsWith("]") && infoLine.indexOf(":") > -1) { // heuristically this is a goal marker, makeNewCurrentElement(infoLine.substring(1, infoLine.length() - 1)); return; // Do not log the goal itself } Element msg = new Element("message"); msg.addContent(new CDATA(line)); // Initially call it "info" level. // If "the going gets tough" we'll switch this to "error" msg.setAttribute("priority", level); if (currentElement == null) { buildLogElement.addContent(msg); } else { currentElement.addContent(msg); } } } private Element makeNewCurrentElement(String cTask) { if (buildLogElement == null) { return null; } synchronized (buildLogElement) { flushCurrentElement(); currentElement = new Element("mavengoal"); currentElement.setAttribute("name", cTask); return currentElement; } } protected void flushCurrentElement() { if (buildLogElement == null) { return; } synchronized (buildLogElement) { if (currentElement != null) { if (buildLogElement.getAttribute(SUCCESS) != null && buildLogElement.getAttribute(ERROR) == null) { LOG.debug("Ok : BUILD SUCCESSFUL"); // Ok build successfull } else if (buildLogElement.getAttribute(ERROR) != null) { // All the messages of the last (failed) goal should be // switched to priority error List lst = currentElement.getChildren("message"); if (lst != null) { Iterator it = lst.iterator(); while (it.hasNext()) { Element msg = (Element) it.next(); msg.setAttribute("priority", ERROR); } } } buildLogElement.addContent(currentElement); currentElement = null; } } } /** * @param buildProperties The buildProperties to set. */ public void setBuildProperties(Map buildProperties) { this.buildProperties = buildProperties; } /** * @param goalset The goalset to set. */ public void setGoalset(String goalset) { this.goalset = goalset; } /** * @param mvnScript The mavenScript to set. */ public void setMvnScript(String mvnScript) { this.mvn = mvnScript; } /** * @param pomFile The projectFile to set. */ public void setPomFile(String pomFile) { this.pomFile = pomFile; } /** * @param properties The properties to set. */ public void setProperties(List properties) { this.properties = properties; } /** * @return the exitCode. */ public int getExitCode() { return exitCode; } /** * @param exitCode The exitCode to set. */ public void setExitCode(int exitCode) { this.exitCode = exitCode; } }
true
true
public Commandline buildCommandline() throws CruiseControlException { //usage: maven [options] [<goal(s)>] [<phase(s)>] Commandline cmdLine = new Commandline(); cmdLine.setExecutable(mvn); //Run in non-interactive mode. cmdLine.createArgument("-B"); //If log is enabled for CC, enable it for mvn if (LOG.isDebugEnabled()) { cmdLine.createArgument("-X"); } //Alternate path for the user settings file if (settingsFile != null) { cmdLine.createArguments("-s", settingsFile); } if (pomFile != null) { cmdLine.createArguments("-f", new File(pomFile).getName()); } //activate specified profiles if (activateProfiles != null) { cmdLine.createArguments("-P", activateProfiles); } if (flags != null) { cmdLine.createArgument(flags); } if (goalset != null) { StringTokenizer stok = new StringTokenizer(goalset, " \t\r\n"); while (stok.hasMoreTokens()) { cmdLine.createArgument(stok.nextToken()); } } Iterator propertiesIterator = buildProperties.keySet().iterator(); while (propertiesIterator.hasNext()) { final String key = (String) propertiesIterator.next(); final String value = (String) buildProperties.get(key); if (value.indexOf(' ') == -1) { cmdLine.createArgument("-D" + key + "=" + value); } else { // @todo Find better way to handle when property values contains spaces. // Just using Commandline results in entire prop being quoted: // "-Dcvstimestamp=2006-11-29 03:41:04 GMT" // and using Commandline.quoteArgument() results in this when used on value only: // '-Dcvstimestamp="2006-11-29 03:41:04 GMT"' // all these (includeing no manipulation) cause errors in maven's parsing of the command line. // For now, we just replace spaces with underscores so at least some form of the prop is available final String spacelessValue = value.replace(' ', '_'); LOG.warn("Maven2Script altering build property with space. Key:" + key + "; Orig Value:" + value + "; New Value: " + spacelessValue); cmdLine.createArgument("-D" + key + "=" + spacelessValue); } } for (Iterator propsIterator = properties.iterator(); propsIterator.hasNext(); ) { Property property = (Property) propsIterator.next(); cmdLine.createArgument("-D" + property.getName() + "=" + property.getValue()); } //If log is enabled, log the command line if (LOG.isDebugEnabled()) { StringBuffer sb = new StringBuffer(); sb.append("Executing Command: "); String[] args = cmdLine.getCommandline(); for (int i = 0; i < args.length; i++) { String arg = args[i]; sb.append(arg); sb.append(" "); } LOG.debug(sb.toString()); } return cmdLine; }
public Commandline buildCommandline() throws CruiseControlException { //usage: maven [options] [<goal(s)>] [<phase(s)>] Commandline cmdLine = new Commandline(); cmdLine.setExecutable(mvn); //Run in non-interactive mode. cmdLine.createArgument("-B"); //If log is enabled for CC, enable it for mvn if (LOG.isDebugEnabled()) { cmdLine.createArgument("-X"); } //Alternate path for the user settings file if (settingsFile != null) { cmdLine.createArguments("-s", settingsFile); } if (pomFile != null) { cmdLine.createArguments("-f", new File(pomFile).getName()); } //activate specified profiles if (activateProfiles != null) { cmdLine.createArguments("-P", activateProfiles); } if (flags != null) { StringTokenizer stok = new StringTokenizer(flags, " \t\r\n"); while (stok.hasMoreTokens()) { cmdLine.createArgument(stok.nextToken()); } } if (goalset != null) { StringTokenizer stok = new StringTokenizer(goalset, " \t\r\n"); while (stok.hasMoreTokens()) { cmdLine.createArgument(stok.nextToken()); } } Iterator propertiesIterator = buildProperties.keySet().iterator(); while (propertiesIterator.hasNext()) { final String key = (String) propertiesIterator.next(); final String value = (String) buildProperties.get(key); if (value.indexOf(' ') == -1) { cmdLine.createArgument("-D" + key + "=" + value); } else { // @todo Find better way to handle when property values contains spaces. // Just using Commandline results in entire prop being quoted: // "-Dcvstimestamp=2006-11-29 03:41:04 GMT" // and using Commandline.quoteArgument() results in this when used on value only: // '-Dcvstimestamp="2006-11-29 03:41:04 GMT"' // all these (includeing no manipulation) cause errors in maven's parsing of the command line. // For now, we just replace spaces with underscores so at least some form of the prop is available final String spacelessValue = value.replace(' ', '_'); LOG.warn("Maven2Script altering build property with space. Key:" + key + "; Orig Value:" + value + "; New Value: " + spacelessValue); cmdLine.createArgument("-D" + key + "=" + spacelessValue); } } for (Iterator propsIterator = properties.iterator(); propsIterator.hasNext(); ) { Property property = (Property) propsIterator.next(); cmdLine.createArgument("-D" + property.getName() + "=" + property.getValue()); } //If log is enabled, log the command line if (LOG.isDebugEnabled()) { StringBuffer sb = new StringBuffer(); sb.append("Executing Command: "); String[] args = cmdLine.getCommandline(); for (int i = 0; i < args.length; i++) { String arg = args[i]; sb.append(arg); sb.append(" "); } LOG.debug(sb.toString()); } return cmdLine; }
diff --git a/src/com/dalthed/tucan/ui/MainMenu.java b/src/com/dalthed/tucan/ui/MainMenu.java index 2aede10..50de6ec 100644 --- a/src/com/dalthed/tucan/ui/MainMenu.java +++ b/src/com/dalthed/tucan/ui/MainMenu.java @@ -1,290 +1,290 @@ package com.dalthed.tucan.ui; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import org.acra.ErrorReporter; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.bugsense.trace.BugSense; import com.bugsense.trace.BugSenseHandler; import com.dalthed.tucan.R; import com.dalthed.tucan.TuCanMobileActivity; import com.dalthed.tucan.TucanMobile; import com.dalthed.tucan.Connection.AnswerObject; import com.dalthed.tucan.Connection.CookieManager; import com.dalthed.tucan.Connection.RequestObject; import com.dalthed.tucan.Connection.SimpleSecureBrowser; import com.google.android.apps.analytics.GoogleAnalyticsTracker; public class MainMenu extends SimpleWebActivity { CookieManager localCookieManager; private static final String LOG_TAG = "TuCanMobile"; private String menu_link_vv = ""; private String menu_link_ex = ""; private String menu_link_msg = ""; private String menu_link_export = ""; private String menu_link_month = ""; private String UserName = ""; String SessionArgument=""; private boolean noeventstoday=false; private String[] today_event_links; public GoogleAnalyticsTracker mAnalyticsTracker; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_menu); mAnalyticsTracker = GoogleAnalyticsTracker.getInstance(); mAnalyticsTracker.startNewSession("UA-2729322-5", this); BugSenseHandler.setup(this,"ed5c1682"); // Webhandling Start String CookieHTTPString = getIntent().getExtras().getString("Cookie"); String lastCalledURLString = getIntent().getExtras().getString("URL"); URL lastCalledURL; try { lastCalledURL = new URL(lastCalledURLString); localCookieManager = new CookieManager(); localCookieManager.generateManagerfromHTTPString( lastCalledURL.getHost(), CookieHTTPString); callResultBrowser = new SimpleSecureBrowser( this); RequestObject thisRequest = new RequestObject(lastCalledURLString, localCookieManager, RequestObject.METHOD_GET, ""); callResultBrowser.execute(thisRequest); } catch (MalformedURLException e) { Log.e(LOG_TAG, e.getMessage()); } // Webhandling End ListView MenuList = (ListView) findViewById(R.id.mm_menuList); MenuList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getResources() .getStringArray(R.array.mainmenu_options))); MenuList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView arg0, View arg1, int position, long arg3) { switch (position) { case 0: Intent StartVVIntent = new Intent(MainMenu.this, VV.class); StartVVIntent.putExtra("URL", menu_link_vv); StartVVIntent.putExtra("Cookie", localCookieManager .getCookieHTTPString(TucanMobile.TUCAN_HOST)); StartVVIntent.putExtra("UserName", UserName); startActivity(StartVVIntent); // Vorlesungsverzeichnis break; case 1: Intent StartScheduleIntent = new Intent(MainMenu.this, Schedule.class); StartScheduleIntent.putExtra("URL", menu_link_month); StartScheduleIntent.putExtra("Cookie", localCookieManager .getCookieHTTPString(TucanMobile.TUCAN_HOST)); StartScheduleIntent.putExtra("Session", SessionArgument); startActivity(StartScheduleIntent); // Stundenplan break; case 2: Intent StartEventIntent = new Intent(MainMenu.this, Events.class); StartEventIntent.putExtra("URL", menu_link_ex); StartEventIntent.putExtra("Cookie", localCookieManager .getCookieHTTPString(TucanMobile.TUCAN_HOST)); StartEventIntent.putExtra("UserName", UserName); startActivity(StartEventIntent); // Veranstaltungen break; case 3: Intent StartExamIntent = new Intent(MainMenu.this, Exams.class); StartExamIntent.putExtra("URL", menu_link_ex); StartExamIntent.putExtra("Cookie", localCookieManager .getCookieHTTPString(TucanMobile.TUCAN_HOST)); StartExamIntent.putExtra("UserName", UserName); startActivity(StartExamIntent); // Pr�fungen break; case 4: Intent StartMessageIntent = new Intent(MainMenu.this, Messages.class); StartMessageIntent.putExtra("URL", menu_link_msg); StartMessageIntent.putExtra("Cookie", localCookieManager .getCookieHTTPString(TucanMobile.TUCAN_HOST)); StartMessageIntent.putExtra("UserName", UserName); startActivity(StartMessageIntent); break; } } }); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setContentView(R.layout.main_menu); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { localCookieManager = new CookieManager(); Toast.makeText(this, "Abgemeldet", Toast.LENGTH_SHORT).show(); } return super.onKeyDown(keyCode, event); } class EventAdapter extends ArrayAdapter<String> { String[] startClock; EventAdapter(String[] Events, String[] Times) { super(MainMenu.this, R.layout.row, R.id.label, Events); this.startClock = Times; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = super.getView(position, convertView, parent); TextView clockText = (TextView) row.findViewById(R.id.row_time); clockText.setText(startClock[position]); return row; } } @Override public void onPostExecute(AnswerObject result) { // HTML auslesen sendHTMLatBug(result.getHTML()); Document doc = Jsoup.parse(result.getHTML()); if(doc.select("span.notLoggedText").text().length()>0){ Intent BackToLoginIntent = new Intent(this,TuCanMobileActivity.class); startActivity(BackToLoginIntent); } else { String lcURLString=result.getLastCalledURL(); try { URL lcURL = new URL (lcURLString); SessionArgument = lcURL.getQuery().split("ARGUMENTS=")[1].split(",")[0]; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Tabelle mit den Terminen finden und Durchlaufen Element EventTable = doc.select("table.nb").first(); String[] Events; String[] Times; if(EventTable==null){ Events = new String[1]; Times = new String[1]; Events[0] = "Keine Heutigen Veranstaltungen"; Times[0] = ""; } else { if (EventTable.select("tr.tbdata").first().select("td").size()==5) { Events = new String[1]; Times = new String[1]; Events[0] = "Keine Heutigen Veranstaltungen"; Times[0] = ""; noeventstoday = true; } else { Elements EventRows = EventTable.select("tr.tbdata"); Iterator<Element> RowIt = EventRows.iterator(); Events = new String[EventRows.size()]; Times = new String[EventRows.size()]; today_event_links = new String[EventRows.size()]; int i = 0; while (RowIt.hasNext()) { Element currentElement = (Element) RowIt.next(); String EventString = currentElement.select("td[headers=Name]") .select("a").first().text(); today_event_links[i]=currentElement.select("td[headers=Name]") .select("a").first().attr("href"); String EventTimeString = currentElement - .select("td[headers=von]").select("a").first().text(); + .select("td").get(2).select("a").first().text(); String EventTimeEndString = currentElement - .select("td[headers=bis]").select("a").first().text(); + .select("td").get(3).select("a").first().text(); Times[i] = EventTimeString + "-" + EventTimeEndString; Events[i] = EventString; i++; } } } UserName = doc.select("span#loginDataName").text().split(":")[1]; TextView usertextview = (TextView) findViewById(R.id.mm_username); URL lcURL = null; try { lcURL = new URL(result.getLastCalledURL()); } catch (MalformedURLException e) { Log.e(LOG_TAG, "Malformed URL"); } Elements LinkstoOuterWorld = doc.select("div.tb"); Element ArchivLink=LinkstoOuterWorld.get(1).select("a").first(); menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li[title=VV]").select("a").attr("href"); menu_link_ex = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li[title=Pr�fungen]").select("a").attr("href"); menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); menu_link_export = lcURL.getProtocol() + "://" + lcURL.getHost() +doc.select("li#link000272").select("a").attr("href"); menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() +doc.select("li#link000271").select("a").attr("href"); Log.i(LOG_TAG, menu_link_export); usertextview.setText(UserName); ListView EventList = (ListView) findViewById(R.id.mm_eventList); EventList.setAdapter(new EventAdapter(Events, Times)); EventList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(noeventstoday==false){ Intent StartSingleEventIntent = new Intent(MainMenu.this, SingleEvent.class); StartSingleEventIntent.putExtra("URL", TucanMobile.TUCAN_PROT+TucanMobile.TUCAN_HOST+today_event_links[position]); StartSingleEventIntent.putExtra("Cookie", localCookieManager .getCookieHTTPString(TucanMobile.TUCAN_HOST)); //StartSingleEventIntent.putExtra("UserName", UserName); startActivity(StartSingleEventIntent); } } }); } } }
false
true
public void onPostExecute(AnswerObject result) { // HTML auslesen sendHTMLatBug(result.getHTML()); Document doc = Jsoup.parse(result.getHTML()); if(doc.select("span.notLoggedText").text().length()>0){ Intent BackToLoginIntent = new Intent(this,TuCanMobileActivity.class); startActivity(BackToLoginIntent); } else { String lcURLString=result.getLastCalledURL(); try { URL lcURL = new URL (lcURLString); SessionArgument = lcURL.getQuery().split("ARGUMENTS=")[1].split(",")[0]; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Tabelle mit den Terminen finden und Durchlaufen Element EventTable = doc.select("table.nb").first(); String[] Events; String[] Times; if(EventTable==null){ Events = new String[1]; Times = new String[1]; Events[0] = "Keine Heutigen Veranstaltungen"; Times[0] = ""; } else { if (EventTable.select("tr.tbdata").first().select("td").size()==5) { Events = new String[1]; Times = new String[1]; Events[0] = "Keine Heutigen Veranstaltungen"; Times[0] = ""; noeventstoday = true; } else { Elements EventRows = EventTable.select("tr.tbdata"); Iterator<Element> RowIt = EventRows.iterator(); Events = new String[EventRows.size()]; Times = new String[EventRows.size()]; today_event_links = new String[EventRows.size()]; int i = 0; while (RowIt.hasNext()) { Element currentElement = (Element) RowIt.next(); String EventString = currentElement.select("td[headers=Name]") .select("a").first().text(); today_event_links[i]=currentElement.select("td[headers=Name]") .select("a").first().attr("href"); String EventTimeString = currentElement .select("td[headers=von]").select("a").first().text(); String EventTimeEndString = currentElement .select("td[headers=bis]").select("a").first().text(); Times[i] = EventTimeString + "-" + EventTimeEndString; Events[i] = EventString; i++; } } } UserName = doc.select("span#loginDataName").text().split(":")[1]; TextView usertextview = (TextView) findViewById(R.id.mm_username); URL lcURL = null; try { lcURL = new URL(result.getLastCalledURL()); } catch (MalformedURLException e) { Log.e(LOG_TAG, "Malformed URL"); } Elements LinkstoOuterWorld = doc.select("div.tb"); Element ArchivLink=LinkstoOuterWorld.get(1).select("a").first(); menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li[title=VV]").select("a").attr("href"); menu_link_ex = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li[title=Pr�fungen]").select("a").attr("href"); menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); menu_link_export = lcURL.getProtocol() + "://" + lcURL.getHost() +doc.select("li#link000272").select("a").attr("href"); menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() +doc.select("li#link000271").select("a").attr("href"); Log.i(LOG_TAG, menu_link_export); usertextview.setText(UserName); ListView EventList = (ListView) findViewById(R.id.mm_eventList); EventList.setAdapter(new EventAdapter(Events, Times)); EventList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(noeventstoday==false){ Intent StartSingleEventIntent = new Intent(MainMenu.this, SingleEvent.class); StartSingleEventIntent.putExtra("URL", TucanMobile.TUCAN_PROT+TucanMobile.TUCAN_HOST+today_event_links[position]); StartSingleEventIntent.putExtra("Cookie", localCookieManager .getCookieHTTPString(TucanMobile.TUCAN_HOST)); //StartSingleEventIntent.putExtra("UserName", UserName); startActivity(StartSingleEventIntent); } } }); } }
public void onPostExecute(AnswerObject result) { // HTML auslesen sendHTMLatBug(result.getHTML()); Document doc = Jsoup.parse(result.getHTML()); if(doc.select("span.notLoggedText").text().length()>0){ Intent BackToLoginIntent = new Intent(this,TuCanMobileActivity.class); startActivity(BackToLoginIntent); } else { String lcURLString=result.getLastCalledURL(); try { URL lcURL = new URL (lcURLString); SessionArgument = lcURL.getQuery().split("ARGUMENTS=")[1].split(",")[0]; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Tabelle mit den Terminen finden und Durchlaufen Element EventTable = doc.select("table.nb").first(); String[] Events; String[] Times; if(EventTable==null){ Events = new String[1]; Times = new String[1]; Events[0] = "Keine Heutigen Veranstaltungen"; Times[0] = ""; } else { if (EventTable.select("tr.tbdata").first().select("td").size()==5) { Events = new String[1]; Times = new String[1]; Events[0] = "Keine Heutigen Veranstaltungen"; Times[0] = ""; noeventstoday = true; } else { Elements EventRows = EventTable.select("tr.tbdata"); Iterator<Element> RowIt = EventRows.iterator(); Events = new String[EventRows.size()]; Times = new String[EventRows.size()]; today_event_links = new String[EventRows.size()]; int i = 0; while (RowIt.hasNext()) { Element currentElement = (Element) RowIt.next(); String EventString = currentElement.select("td[headers=Name]") .select("a").first().text(); today_event_links[i]=currentElement.select("td[headers=Name]") .select("a").first().attr("href"); String EventTimeString = currentElement .select("td").get(2).select("a").first().text(); String EventTimeEndString = currentElement .select("td").get(3).select("a").first().text(); Times[i] = EventTimeString + "-" + EventTimeEndString; Events[i] = EventString; i++; } } } UserName = doc.select("span#loginDataName").text().split(":")[1]; TextView usertextview = (TextView) findViewById(R.id.mm_username); URL lcURL = null; try { lcURL = new URL(result.getLastCalledURL()); } catch (MalformedURLException e) { Log.e(LOG_TAG, "Malformed URL"); } Elements LinkstoOuterWorld = doc.select("div.tb"); Element ArchivLink=LinkstoOuterWorld.get(1).select("a").first(); menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li[title=VV]").select("a").attr("href"); menu_link_ex = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li[title=Pr�fungen]").select("a").attr("href"); menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); menu_link_export = lcURL.getProtocol() + "://" + lcURL.getHost() +doc.select("li#link000272").select("a").attr("href"); menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() +doc.select("li#link000271").select("a").attr("href"); Log.i(LOG_TAG, menu_link_export); usertextview.setText(UserName); ListView EventList = (ListView) findViewById(R.id.mm_eventList); EventList.setAdapter(new EventAdapter(Events, Times)); EventList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(noeventstoday==false){ Intent StartSingleEventIntent = new Intent(MainMenu.this, SingleEvent.class); StartSingleEventIntent.putExtra("URL", TucanMobile.TUCAN_PROT+TucanMobile.TUCAN_HOST+today_event_links[position]); StartSingleEventIntent.putExtra("Cookie", localCookieManager .getCookieHTTPString(TucanMobile.TUCAN_HOST)); //StartSingleEventIntent.putExtra("UserName", UserName); startActivity(StartSingleEventIntent); } } }); } }
diff --git a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Coordinator.java b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Coordinator.java index 80c37b44..0cfebab6 100644 --- a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Coordinator.java +++ b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Coordinator.java @@ -1,1463 +1,1470 @@ /******************************************************************************* * Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management * Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. ******************************************************************************/ package de.tuilmenau.ics.fog.routing.hierarchical.management; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import de.tuilmenau.ics.fog.IEvent; import de.tuilmenau.ics.fog.packets.hierarchical.SignalingMessageHrm; import de.tuilmenau.ics.fog.packets.hierarchical.topology.AnnounceCoordinator; import de.tuilmenau.ics.fog.packets.hierarchical.topology.InvalidCoordinator; import de.tuilmenau.ics.fog.packets.hierarchical.topology.RouteReport; import de.tuilmenau.ics.fog.packets.hierarchical.topology.RouteShare; import de.tuilmenau.ics.fog.routing.hierarchical.*; import de.tuilmenau.ics.fog.routing.hierarchical.election.BullyPriority; import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID; import de.tuilmenau.ics.fog.ui.Logging; /** * This class is used for a coordinator instance and can be used on all hierarchy levels. * A cluster's elector instance is responsible for creating instances of this class. */ public class Coordinator extends ControlEntity implements Localization, IEvent { /** * Stores the simulation timestamp of the last "share phase" */ private double mTimeOfLastSharePhase = 0; /** * Stores the routes which should be shared with cluster members. */ private LinkedList<RoutingEntry> mSharedRoutes = new LinkedList<RoutingEntry>(); /** * Stores whether the data of the "shared phase" has changed or not. */ private boolean mSharedRoutesHaveChanged = false; /** * Stores the parent cluster, which is managed by this coordinator instance. */ private Cluster mParentCluster = null; /** * This is the coordinator counter, which allows for globally (related to a physical simulation machine) unique coordinator IDs. */ private static int sNextFreeCoordinatorID = 1; /** * Stores the cluster memberships of this coordinator */ private LinkedList<CoordinatorAsClusterMember> mClusterMemberships = new LinkedList<CoordinatorAsClusterMember>(); /** * Stores the communication channel to the superior coordinator. * For a base hierarchy level cluster, this is a level 0 coordinator. * For a level n coordinator, this is a level n+1 coordinator. */ private ComChannel mSuperiorCoordinatorComChannel = null; /** * Stores how many announces were already sent */ private int mSentAnnounces = 0; /** * Stores the last received routing table from the superior coordinator */ private RoutingTable mReceivedSharedRoutingTable = new RoutingTable(); /** * Stores if the GUI user has selected to deactivate announcements. * This function is not part of the concept. It is only used for debugging purposes and measurement speedup. */ public static boolean GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS = true; private static final long serialVersionUID = 6824959379284820010L; /** * The constructor for a cluster object. Usually, it is called by a cluster's elector instance * * @param pCluster the parent cluster instance */ public Coordinator(Cluster pCluster) { // use the HRMController reference and the hierarchy level from the cluster super(pCluster.mHRMController, pCluster.getHierarchyLevel()); mParentCluster = pCluster; // create an ID for the cluster setCoordinatorID(createCoordinatorID()); // update the cluster ID setClusterID(mParentCluster.getClusterID()); // register itself as coordinator for the managed cluster mParentCluster.eventNewLocalCoordinator(this); // register at HRMController's internal database mHRMController.registerCoordinator(this); Logging.log(this, "\n\n\n################ CREATED COORDINATOR at hierarchy level: " + getHierarchyLevel().getValue()); // trigger periodic Cluster announcements if(HRMConfig.Hierarchy.COORDINATOR_ANNOUNCEMENTS){ if(HRMConfig.Hierarchy.PERIODIC_COORDINATOR_ANNOUNCEMENTS){ Logging.log(this, "Activating periodic coordinator announcements"); // register next trigger for mHRMController.getAS().getTimeBase().scheduleIn(HRMConfig.Hierarchy.COORDINATOR_ANNOUNCEMENTS_INTERVAL * 2, this); } } } /** * Generates a new ClusterID * * @return the ClusterID */ static private synchronized long createCoordinatorID() { // get the current unique ID counter long tResult = sNextFreeCoordinatorID * idMachineMultiplier(); // make sure the next ID isn't equal sNextFreeCoordinatorID++; if(tResult < 1){ throw new RuntimeException("Created an invalid coordinator ID " + tResult); } return tResult; } /** * Sets the communication channel to the superior coordinator. * For a base hierarchy level cluster, this is a level 0 coordinator. * For a level n coordinator, this is a level n+1 coordinator. * * @param pComChannel the new communication channel */ protected void setSuperiorCoordinatorComChannel(ComChannel pComChannel) { Logging.log(this, "Setting superior comm. channel: " + pComChannel); mSuperiorCoordinatorComChannel = pComChannel; } /** * Returns a reference to the communication channel towards the superior coordinator. * * @return the communication channel */ public ComChannel superiorCoordinatorComChannel() { return mSuperiorCoordinatorComChannel; } /** * Sends a packet to the superior coordinator * * @param pPacket the packet */ public void sendSuperiorCoordinator(SignalingMessageHrm pPacket) { if(HRMConfig.DebugOutput.SHOW_REPORT_PHASE){ Logging.log(this, "Sending to superior coordinator: " + pPacket); } if(superiorCoordinatorComChannel() != null){ // plausibility check if we actually use a link from a CoordinatorAsClusterMember if(superiorCoordinatorComChannel().getParent() instanceof CoordinatorAsClusterMember){ CoordinatorAsClusterMember tCoordinatorAsClusterMember = (CoordinatorAsClusterMember)superiorCoordinatorComChannel().getParent(); if(tCoordinatorAsClusterMember.isThisEntityValid()){ if(tCoordinatorAsClusterMember.getComChannelToClusterHead() != null){ // plausibility check if we actually use an active link if(tCoordinatorAsClusterMember.getComChannelToClusterHead().isLinkActive()){ superiorCoordinatorComChannel().sendPacket(pPacket); }else{ Logging.err(this, "sendSuperiorCoordinator() expected an active link, link is: " + superiorCoordinatorComChannel()); } }else{ Logging.warn(this, "sendSuperiorCoordinator() aborted because the comm. channel to the cluster head is invalid for: " + tCoordinatorAsClusterMember); } }else{ Logging.warn(this, "sendSuperiorCoordinator() aborted because of an invalidated CoordinatorAsClusterMember: " + tCoordinatorAsClusterMember); } }else{ Logging.err(this, "sendSuperiorCoordinator() expected a CoordinatorAsClusterMember as parent of: " + superiorCoordinatorComChannel()); } }else{ Logging.err(this, "sendSuperiorCoordinator() aborted because the comm. channel to the superior coordinator is invalid"); int i = 0; for(CoordinatorAsClusterMember tMembership : mClusterMemberships){ Logging.err(this, " ..possible comm. channel [" + i + "] " + (tMembership.isActiveCluster() ? "(A)" : "") + ":" + tMembership.getComChannelToClusterHead()); i++; } } } /** * Checks if the "share phase" should be started or not * * @return true if the "share phase" should be started, otherwise false */ private boolean sharePhaseHasTimeout() { // determine the time between two "share phases" double tDesiredTimePeriod = mHRMController.getPeriodSharePhase(getHierarchyLevel().getValue()); // determine the time when a "share phase" has to be started double tTimeNextSharePhase = mTimeOfLastSharePhase + tDesiredTimePeriod; // determine the current simulation time from the HRMCotnroller instance double tCurrentSimulationTime = mHRMController.getSimulationTime(); if (HRMConfig.DebugOutput.GUI_SHOW_TIMING_ROUTE_DISTRIBUTION){ Logging.log(this, "Checking for timeout of \"share phase\": desired time period is " + tDesiredTimePeriod + ", " + tCurrentSimulationTime + " > " + tTimeNextSharePhase + "? -> " + (tCurrentSimulationTime >= tTimeNextSharePhase)); } return (tCurrentSimulationTime >= tTimeNextSharePhase); } /** * Determines if new "share phase" data is available * * @return true if new data is available, otherwise false */ private boolean hasNewSharePhaseData() { boolean tResult = false; synchronized (mSharedRoutes){ tResult = mSharedRoutesHaveChanged; } return tResult; } /** * This function implements the "share phase". * It distributes locally stored sharable routing data among the known cluster members */ private int mCallsSharePhase = 0; @SuppressWarnings("unused") public void sharePhase() { boolean DEBUG_SHARE_PHASE_DETAILS = false; // should we start the "share phase"? if (sharePhaseHasTimeout()){ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, "SHARE PHASE with cluster members on level " + getHierarchyLevel().getValue() + "/" + (HRMConfig.Hierarchy.HEIGHT - 1)); } // store the time of this "share phase" mTimeOfLastSharePhase = mHRMController.getSimulationTime(); if ((!HRMConfig.Routing.PERIODIC_SHARE_PHASES) && (!hasNewSharePhaseData())){ //TODO if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, "SHARE PHASE aborted because routing data hasn't changed since last signaling round"); } return; } mCallsSharePhase++; // get all comm. channels to inferior cluster members LinkedList<ComChannel> tComChannels = mParentCluster.getComChannels(); /******************************************************************* * Iterate over all comm. channels and share routing data *******************************************************************/ for (ComChannel tComChannel : tComChannels){ /** * Only proceed if the link is actually active */ if(tComChannel.isLinkActive()){ RoutingTable tSharedRoutingTable = new RoutingTable(); HRMID tPeerHRMID = tComChannel.getPeerHRMID(); if((tPeerHRMID != null) && (!tPeerHRMID.isZero())){ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, " ..sharing routes with: " + tPeerHRMID); } if(getHierarchyLevel().isBaseLevel()){ HRMID tThisNodeHRMID = getCluster().getL0HRMID(); /********************************************************************* * SHARE 1: received routes from superior coordinator *********************************************************************/ // copy the received routing table RoutingTable tReceivedSharedRoutingTable = null; synchronized (mReceivedSharedRoutingTable) { tReceivedSharedRoutingTable = (RoutingTable) mReceivedSharedRoutingTable.clone(); } int j = -1; - for(RoutingEntry tEntry : tReceivedSharedRoutingTable){ + for(RoutingEntry tReceivedSharedRoutingEntry : tReceivedSharedRoutingTable){ j++; /** * does the received route start at the peer? * => share: [original route from sup. coordinator] */ - if(tEntry.getSource().isCluster(tPeerHRMID)){ - RoutingEntry tNewEntry = tEntry.clone(); + if(tReceivedSharedRoutingEntry.getSource().isCluster(tPeerHRMID)){ + RoutingEntry tNewEntry = tReceivedSharedRoutingEntry.clone(); + // reset L2Address for next hop + tNewEntry.setNextHopL2Address(null); tNewEntry.extendCause(this + "::sharePhase()_ReceivedRouteShare_1(" + mCallsSharePhase + ")(" + j + ") as " + tNewEntry); // share the received entry with the peer tSharedRoutingTable.addEntry(tNewEntry); continue; } /** * does the received route start at this node and the next node isn't the peer? * => share: [route from peer to this node] ==> [original route from sup. coordinator] */ - if((tEntry.getSource().equals(tThisNodeHRMID)) && (!tEntry.getNextHop().equals(tPeerHRMID))){ + if((tReceivedSharedRoutingEntry.getSource().equals(tThisNodeHRMID)) && (!tReceivedSharedRoutingEntry.getNextHop().equals(tPeerHRMID))){ RoutingEntry tRoutingEntryWithPeer = mHRMController.getRoutingEntryHRG(tPeerHRMID, tThisNodeHRMID); if(tRoutingEntryWithPeer != null){ - tRoutingEntryWithPeer.chain(tEntry); - tRoutingEntryWithPeer.extendCause(this + "::sharePhase()_ReceivedRouteShare_2(" + mCallsSharePhase + ")(" + j + ") as " + tRoutingEntryWithPeer); + RoutingEntry tNewEntry = tRoutingEntryWithPeer.clone(); + // reset L2Address for next hop + tNewEntry.setNextHopL2Address(null); + tNewEntry.chain(tReceivedSharedRoutingEntry); + tNewEntry.extendCause(this + "::sharePhase()_ReceivedRouteShare_2(" + mCallsSharePhase + ")(" + j + ") as combination of " + tRoutingEntryWithPeer + " and " + tReceivedSharedRoutingEntry); // share the received entry with the peer - tSharedRoutingTable.addEntry(tRoutingEntryWithPeer); + tSharedRoutingTable.addEntry(tNewEntry); } continue; } } }else{ // /********************************************************************* // * SHARE: routes to neighbors of ourself // *********************************************************************/ // // find all siblings of ourself // //HINT: the found siblings have the same hierarchy level like this coordinator // LinkedList<HRMID> tKnownSibblings = mHRMController.getDestinationsHRG(getHRMID()); // for(HRMID tPossibleDestination : tKnownSibblings){ // if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ // Logging.log(this, " ..possible higher destination: " + tPossibleDestination); // } // // // get the inter-cluster path to the possible destination // List<AbstractRoutingGraphLink> tPath = mHRMController.getRouteHRG(getHRMID(), tPossibleDestination); // if(tPath != null){ // // } // } /********************************************************************* * SHARE 2: routes to known siblings of the peer at the same hierarchy level *********************************************************************/ // find all siblings of the peer //HINT: the peer is one hierarchy level below this coordinator LinkedList<HRMID> tKnownPeerSiblings = mHRMController.getSiblingsHRG(tPeerHRMID); for(HRMID tPossibleDestination : tKnownPeerSiblings){ if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..possible peer destination: " + tPossibleDestination + " for: " + tPeerHRMID); Logging.log(this, " ..determining path from " + tPeerHRMID + " to " + tPossibleDestination); } int tStep = 0; // get the inter-cluster path to the possible destination List<AbstractRoutingGraphLink> tPath = mHRMController.getRouteHRG(tPeerHRMID, tPossibleDestination); if(tPath != null){ // the searched routing entry to the possible destination cluster RoutingEntry tFinalRoutingEntryToDestination = null; // the last cluster gateway HRMID tLastClusterGateway = null; HRMID tFirstForeignGateway = null; if(!tPath.isEmpty()){ if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..found inter cluster path:"); for(AbstractRoutingGraphLink tLink : tPath){ Logging.log(this, " ..step: " + tLink); } } for(AbstractRoutingGraphLink tLink : tPath){ RoutingEntry tInterClusterRoutingEntry = (RoutingEntry)tLink.getRoute().getFirst(); if(tFinalRoutingEntryToDestination != null){ if(tLastClusterGateway == null){ throw new RuntimeException(this + "::sharePhase() should never reach this point"); } /************************************************************************************************ * ROUTE PART: the intra-cluster route from the last gateway to the next one ***********************************************************************************************/ // the next cluster gateway HRMID tNextClusterGateway = tInterClusterRoutingEntry.getSource(); if(!tLastClusterGateway.equals(tNextClusterGateway)){ // the intra-cluster path List<AbstractRoutingGraphLink> tIntraClusterPath = mHRMController.getRouteHRG(tLastClusterGateway, tNextClusterGateway); if(tIntraClusterPath != null){ if(!tIntraClusterPath.isEmpty()){ RoutingEntry tLogicalIntraClusterRoutingEntry = null; /** * Determine the intra-cluster route part */ // check if we have only one hop in intra-cluster route if(tIntraClusterPath.size() == 1){ AbstractRoutingGraphLink tIntraClusterLogLink = tIntraClusterPath.get(0); // get the routing entry from the last gateway to the next one tLogicalIntraClusterRoutingEntry = (RoutingEntry) tIntraClusterLogLink.getRoute().getFirst(); }else{ tLogicalIntraClusterRoutingEntry = RoutingEntry.create(tIntraClusterPath); if(tLogicalIntraClusterRoutingEntry == null){ Logging.warn(this, "sharePhase() for " + tPeerHRMID + " found a complex intra-cluster path and wasn't able to derive an aggregated logical link from it.."); Logging.warn(this, " ..path: " + tIntraClusterPath); Logging.warn(this, " ..from: " + tLastClusterGateway); Logging.warn(this, " ..to: " + tNextClusterGateway); Logging.warn(this, " ..for a routing from " + tPeerHRMID + " to " + tPossibleDestination); // reset tFinalRoutingEntryToDestination = null; // abort break; } } /** * Add the intra-cluster route part */ if(tLogicalIntraClusterRoutingEntry != null){ // chain the routing entries if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..step [" + tStep + "] (intra-cluster): " + tLogicalIntraClusterRoutingEntry); } tFinalRoutingEntryToDestination.chain(tLogicalIntraClusterRoutingEntry); tStep++; /** * Determine the next hop for the resulting path */ if(tFirstForeignGateway == null){ if(tLogicalIntraClusterRoutingEntry.getHopCount() > 0){ tFirstForeignGateway = tLogicalIntraClusterRoutingEntry.getNextHop(); } } } }else{ Logging.warn(this, "sharePhase() for " + tPeerHRMID + " found an empty intra-cluster path.."); Logging.warn(this, " ..from: " + tLastClusterGateway); Logging.warn(this, " ..to: " + tNextClusterGateway); Logging.warn(this, " ..for a routing from " + tPeerHRMID + " to " + tPossibleDestination); } }else{ Logging.warn(this, "sharePhase() for " + tPeerHRMID + " couldn't find a route from " + tLastClusterGateway + " to " + tNextClusterGateway + " for a routing from " + tPeerHRMID + " to " + tPossibleDestination); // reset tFinalRoutingEntryToDestination = null; // abort break; //HINT: do not throw a RuntimeException here because such a situation could have a temporary cause } }else{ // tLastClusterGateway and tNextClusterGateway are equal => empty route for cluster traversal } /*********************************************************************************************** * ROUTE PART: the inter-cluster link ***********************************************************************************************/ // chain the routing entries if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..step [" + tStep + "] (cluster-2-cluster): " + tInterClusterRoutingEntry); } tFinalRoutingEntryToDestination.chain(tInterClusterRoutingEntry); }else{ /*********************************************************************************************** * ROUTE PART: first step of the resulting path ***********************************************************************************************/ if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..step [" + tStep + "] (cluster-2-cluster): " + tInterClusterRoutingEntry); } tFinalRoutingEntryToDestination = tInterClusterRoutingEntry; } tStep++; /** * Determine the next hop for the resulting path */ if(tFirstForeignGateway == null){ if(tInterClusterRoutingEntry.getHopCount() > 0){ tFirstForeignGateway = tInterClusterRoutingEntry.getNextHop(); } } //update last cluster gateway tLastClusterGateway = tInterClusterRoutingEntry.getNextHop(); } }else{ Logging.err(this, "sharePhase() for " + tPeerHRMID + " found an empty path from " + tPeerHRMID + " to " + tPossibleDestination); } if(tFinalRoutingEntryToDestination != null){ /** * Set the DESTINATION for the resulting routing entry */ tFinalRoutingEntryToDestination.setDest(tPeerHRMID.getForeignCluster(tPossibleDestination) /* aggregate the destination here */); /** * Set the NEXT HOP for the resulting routing entry */ if(tFirstForeignGateway != null){ tFinalRoutingEntryToDestination.setNextHop(tFirstForeignGateway); } /** * Add the found routing entry to the shared routing table */ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, " ..==> routing entry: " + tFinalRoutingEntryToDestination); } + // reset L2Address for next hop + tFinalRoutingEntryToDestination.setNextHopL2Address(null); tFinalRoutingEntryToDestination.extendCause(this + "::sharePhase()_HRG_based(" + mCallsSharePhase + ")"); tSharedRoutingTable.addEntry(tFinalRoutingEntryToDestination); } }else{ Logging.err(this, "sharePhase() for " + tPeerHRMID + " couldn't determine a route from " + tPeerHRMID + " to " + tPossibleDestination); } } } if(tSharedRoutingTable.size() > 0){ tComChannel.distributeRouteShare(tSharedRoutingTable); } } } } }else{ // share phase shouldn't be started, we have to wait until next trigger } } /** * This function implements the "report phase". * It sends locally stored sharable routing data to the superior coordinator */ public void reportPhase() { /** * Auto. delete deprecated routes */ if(getHierarchyLevel().isBaseLevel()){ mHRMController.autoRemoveObsoleteHRGLinks(); } /** * Create the report based on current topology data */ // the highest coordinator does not have any superior coordinator if (!getHierarchyLevel().isHighest()){ // do we have a valid channel to the superior coordinator? if(superiorCoordinatorComChannel() != null){ // HINT: we do not report topology data which is already locally known if(!mHRMController.getNodeL2Address().equals(superiorCoordinatorComChannel().getPeerL2Address())){ RoutingTable tReportRoutingTable = new RoutingTable(); /**************************************************************************************************************************** * Report 1: inter-cluster links to all neighbor clusters based on the local HRG * If we are "1.2.0", we report forward/backward route with "1.3.0" and with "1.1.0" (if both clusters are direct neighbors) ***************************************************************************************************************************/ RoutingTable tRoutesToNeighbors = mHRMController.getRoutesWithNeighborsHRG(getHRMID()); if (HRMConfig.DebugOutput.SHOW_REPORT_PHASE){ Logging.log(this, " ..got inter-cluster routing report: " + tRoutesToNeighbors); } // add the found routes to the report routing table tReportRoutingTable.addEntries(tRoutesToNeighbors); /**************************************************************************************************************************** * Report 2: intra-cluster routes between all possible combinations of gateway pairings ***************************************************************************************************************************/ if(getHierarchyLevel().isBaseLevel()){ //TODO: remove this limitation /*************************************************************** * (L0): routes to remote ClusterMember (physical neighbor nodes) based on node-to-node messages **************************************************************/ if (HRMConfig.DebugOutput.SHOW_REPORT_PHASE){ Logging.log(this, "REPORT PHASE at hierarchy level " + getHierarchyLevel().getValue() + "/" + (HRMConfig.Hierarchy.HEIGHT - 1)); } // get all comm. channels LinkedList<ComChannel> tComChannels = mParentCluster.getComChannels(); // iterate over all comm. channels and fetch the recorded route reports for(ComChannel tComChannel : tComChannels){ RoutingTable tComChannelTable = tComChannel.getReportedRoutingTable(); if (HRMConfig.DebugOutput.SHOW_REPORT_PHASE){ Logging.log(this, " ..got L0 intra-cluster routing report: " + tComChannelTable); } // add the found routes to the overall route report, which is later sent to the superior coordinator tReportRoutingTable.addEntries(tComChannelTable); } }else{ /************************************************************** * (L1+): routes between gateways **************************************************************/ /** * step 1: find gateways */ ArrayList<HRMID> tGateways = new ArrayList<HRMID>(); LinkedList<HRMID> tNeighbors = mHRMController.getNeighborsHRG(getHRMID()); if(!tNeighbors.isEmpty()){ for(HRMID tNeighbor : tNeighbors){ if (HRMConfig.DebugOutput.SHOW_REPORT_PHASE){ Logging.log(this, " ..found neighbor: " + tNeighbor); } // get the link to the neighbor RoutingEntry tRoutingEntryToNeighbor = mHRMController.getRoutingEntryHRG(getHRMID(), tNeighbor); if(tRoutingEntryToNeighbor != null){ HRMID tGateway = tRoutingEntryToNeighbor.getSource(); if(!tGateways.contains(tGateway)){ // get the cluster-internal source node for the inter-cluster link if (HRMConfig.DebugOutput.SHOW_REPORT_PHASE){ Logging.log(this, " ..found gateway: " + tGateway); } tGateways.add(tGateway); } } } } /** * step 2: combine all gateways to pairs and determine a route per combination */ if(!tGateways.isEmpty()){ // do we have at least one possible combination? if(tGateways.size() > 1){ /** * combine all gateways */ for(int tOuter = 0; tOuter < tGateways.size(); tOuter++){ for (int tInner = tOuter + 1; tInner < tGateways.size(); tInner++){ HRMID tSourceGateway = tGateways.get(tOuter); HRMID tDestinationGateway = tGateways.get(tInner); if (HRMConfig.DebugOutput.SHOW_REPORT_PHASE){ Logging.log(this, " ..need a route from " + tSourceGateway + " to " + tDestinationGateway); } List<AbstractRoutingGraphLink> tPath = mHRMController.getRouteHRG(tSourceGateway, tDestinationGateway); if(tPath != null){ if(!tPath.isEmpty()){ // the searched routing entry between the current two gateways RoutingEntry tFinalRoutingEntryBetweenGateways = null; /** * Determine a gateway-2-gateway route */ int tStep = 0; for(AbstractRoutingGraphLink tLink : tPath){ RoutingEntry tStepRoutingEntry = (RoutingEntry)tLink.getRoute().getFirst(); // chain the routing entries if (HRMConfig.DebugOutput.SHOW_REPORT_PHASE){ Logging.log(this, " ..step[ " + tStep + "]: " + tStepRoutingEntry); } tStep++; if(tFinalRoutingEntryBetweenGateways == null){ tFinalRoutingEntryBetweenGateways = tStepRoutingEntry; }else{ tFinalRoutingEntryBetweenGateways.chain(tStepRoutingEntry); } } /** * derive and add an entry to the routing report */ if(tFinalRoutingEntryBetweenGateways != null){ // enforce the destination gateway as next hop tFinalRoutingEntryBetweenGateways.setNextHop(tDestinationGateway); tFinalRoutingEntryBetweenGateways.setRouteForClusterTraversal(); if (HRMConfig.DebugOutput.SHOW_REPORT_PHASE){ Logging.log(this, " ..got L1+ intra-cluster routing report entry: " + tFinalRoutingEntryBetweenGateways); } // add the found gate-2-gateway route to the overall route report, which is later sent to the superior coordinator tReportRoutingTable.addEntry(tFinalRoutingEntryBetweenGateways); } } } } } } } } /** * Send the created report routing table to the superior coordinator */ if(tReportRoutingTable.size() > 0){ if (HRMConfig.DebugOutput.SHOW_REPORT_PHASE){ Logging.log(this, " ..reporting via " + superiorCoordinatorComChannel() + " the routing table:"); int i = 0; for(RoutingEntry tEntry : tReportRoutingTable){ Logging.log(this, " ..[" + i +"]: " + tEntry); i++; } } // create new RouteReport packet for the superior coordinator RouteReport tRouteReportPacket = new RouteReport(getHRMID(), superiorCoordinatorComChannel().getPeerHRMID(), tReportRoutingTable); // send the packet to the superior coordinator sendSuperiorCoordinator(tRouteReportPacket); }else{ if (HRMConfig.DebugOutput.SHOW_REPORT_PHASE){ Logging.log(this, "reportPhase() aborted because no report for " + superiorCoordinatorComChannel() + " available"); } } }else{ if (HRMConfig.DebugOutput.SHOW_REPORT_PHASE){ Logging.log(this, "reportPhase() aborted because no report in a loopback is allowed"); } } }else{ Logging.warn(this, "reportPhase() aborted because channel to superior coordinator is invalid"); } }else{ // nothing to be done here: we are the highest hierarchy level, no one to send topology reports to } } /** * EVENT: RouteShare * * @param pSourceComChannel the source comm. channel * @param pRouteSharePacket the packet */ public void eventReceivedRouteShare(ComChannel pSourceComChannel, RouteShare pRouteSharePacket) { if(HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.err(this, "EVENT: ReceivedRouteShare via: " + pSourceComChannel); } synchronized (mReceivedSharedRoutingTable) { mReceivedSharedRoutingTable = pRouteSharePacket.getRoutes(); mHRMController.addHRMRouteShare(mReceivedSharedRoutingTable, getHierarchyLevel(), pSourceComChannel.getPeerHRMID(), this + "::eventReceivedRouteShare()"); } } /** * EVENT: "eventCoordinatorRoleInvalid", triggered by the Elector, the reaction is: * 1.) create signaling packet "BullyLeave" * 2.) send the packet to the superior coordinator */ public synchronized void eventCoordinatorRoleInvalid() { Logging.log(this, "============ EVENT: Coordinator_Role_Invalid"); /** * Trigger: role invalid */ eventInvalidation(); /** * Trigger: invalid coordinator */ distributeCoordinatorInvalidation(); /** * Inform all superior clusters about the event and trigger the invalidation of this coordinator instance -> we leave all Bully elections because we are no longer a possible election winner */ if (!getHierarchyLevel().isHighest()){ eventAllClusterMembershipsInvalid(); }else{ Logging.log(this, "eventCoordinatorRoleInvalid() skips further signaling because hierarchy end is already reached at: " + getHierarchyLevel().getValue()); } /** * Revoke own HRMID */ if((getHRMID() != null) && (!getHRMID().isZero())){ eventRevokedHRMID(this, getHRMID()); } /** * Trigger: revoke all assigned HRMIDs from all cluster members */ mParentCluster.eventAllClusterAddressesInvalid(); /** * Unregister from local databases */ Logging.log(this, "============ Destroying this coordinator now..."); // unregister from HRMController's internal database mHRMController.unregisterCoordinator(this); /** * Inform the inferior cluster about our destruction */ mParentCluster.eventCoordinatorLost(); } /** * EVENT: all cluster membership invalid */ private void eventAllClusterMembershipsInvalid() { Logging.log(this, "EVENT: all cluster memberships invalid"); Logging.log(this, " ..invalidating these cluster memberships: " + mClusterMemberships); while(mClusterMemberships.size() > 0) { CoordinatorAsClusterMember tCoordinatorAsClusterMember = mClusterMemberships.getLast(); tCoordinatorAsClusterMember.eventClusterMembershipInvalid(); } } /** * SEND: distribute AnnounceCoordinator messages among the neighbors which are within the given max. radius (see HRMConfig) */ private synchronized void distributeCoordinatorAnnouncement() { if(isThisEntityValid()){ // trigger periodic Cluster announcements if(HRMConfig.Hierarchy.COORDINATOR_ANNOUNCEMENTS){ if (GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS){ LinkedList<Cluster> tL0Clusters = mHRMController.getAllClusters(0); AnnounceCoordinator tAnnounceCoordinatorPacket = new AnnounceCoordinator(mHRMController, mHRMController.getNodeName(), getCluster().createClusterName(), mHRMController.getNodeL2Address()); /** * Count the sent announces */ mSentAnnounces++; if(getHierarchyLevel().isBaseLevel()){ /** * Send cluster broadcasts in all other active L0 clusters if we are at level 0 */ for(Cluster tCluster : tL0Clusters){ tCluster.sendClusterBroadcast(tAnnounceCoordinatorPacket, true); } }else{ /** * Send cluster broadcast (to the bottom) in all active inferior clusters - either direct or indirect via the forwarding function of a higher cluster */ LinkedList<Cluster> tClusters = mHRMController.getAllClusters(getHierarchyLevel().getValue()); if(HRMConfig.DebugOutput.SHOW_DEBUG_COORDINATOR_ANNOUNCEMENT_PACKETS){ Logging.log(this, "########## Distributing Coordinator announcement (to the bottom): " + tAnnounceCoordinatorPacket); Logging.log(this, " ..distributing in clusters: " + tClusters); } for(Cluster tCluster : tClusters){ tCluster.sendClusterBroadcast(tAnnounceCoordinatorPacket, true); } /** * Send cluster broadcasts in all known inactive L0 clusters */ LinkedList<Cluster> tInactiveL0Clusters = new LinkedList<Cluster>(); for(Cluster tCluster : tL0Clusters){ if(!tCluster.isActiveCluster()){ tInactiveL0Clusters.add(tCluster); } } if(HRMConfig.DebugOutput.SHOW_DEBUG_COORDINATOR_ANNOUNCEMENT_PACKETS){ Logging.log(this, "########## Distributing Coordinator announcement (to the side): " + tAnnounceCoordinatorPacket); Logging.log(this, " ..distributing in inactive clusters: " + tClusters); } for(Cluster tCluster : tInactiveL0Clusters){ tCluster.sendClusterBroadcast(tAnnounceCoordinatorPacket, true); } } }else{ Logging.warn(this, "USER_CTRL_COORDINATOR_ANNOUNCEMENTS is set to false, this prevents the HRM system from creating a correct hierarchy"); } }else{ Logging.warn(this, "HRMConfig->COORDINATOR_ANNOUNCEMENTS is set to false, this prevents the HRM system from creating a correct hierarchy"); } }else{ if(HRMConfig.DebugOutput.SHOW_DEBUG_COORDINATOR_ANNOUNCEMENT_PACKETS){ Logging.warn(this, "distributeCoordinatorAnnouncement() aborted because coordinator role is already invalidated"); } } } /** * SEND: distribute InvalidCoordinator messages among the neighbors which are within the given max. radius (see HRMConfig) */ private synchronized void distributeCoordinatorInvalidation() { // trigger periodic Cluster announcements if((HRMConfig.Hierarchy.COORDINATOR_ANNOUNCEMENTS) && (GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS)){ InvalidCoordinator tInvalidCoordinatorPacket = new InvalidCoordinator(mHRMController, mHRMController.getNodeName(), getCluster().createClusterName(), mHRMController.getNodeL2Address()); /** * Send broadcasts in all locally known clusters at this hierarchy level */ LinkedList<Cluster> tClusters = mHRMController.getAllClusters(0); //HINT: we have to broadcast via level 0, otherwise, an inferior might already be destroyed and the invalidation message might get dropped if(HRMConfig.DebugOutput.SHOW_DEBUG_COORDINATOR_INVALIDATION_PACKETS){ Logging.log(this, "########## Distributing Coordinator invalidation (to the bottom): " + tInvalidCoordinatorPacket); Logging.log(this, " ..distributing in clusters: " + tClusters); } for(Cluster tCluster : tClusters){ tCluster.sendClusterBroadcast(tInvalidCoordinatorPacket, true); } } } /** * Returns how many announces were already sent * * @return the number of announces */ public int countAnnounces() { return mSentAnnounces; } /** * Implementation for IEvent::fire() */ @Override public void fire() { if(isThisEntityValid()){ if(HRMConfig.Hierarchy.COORDINATOR_ANNOUNCEMENTS){ if(GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS){ if(HRMConfig.DebugOutput.SHOW_DEBUG_COORDINATOR_ANNOUNCEMENT_PACKETS){ Logging.log(this, "###########################"); Logging.log(this, "###### FIRE FIRE FIRE #####"); Logging.log(this, "###########################"); } /** * Trigger: ClusterAnnounce distribution */ distributeCoordinatorAnnouncement(); } // register next trigger for mHRMController.getAS().getTimeBase().scheduleIn(HRMConfig.Hierarchy.COORDINATOR_ANNOUNCEMENTS_INTERVAL, this); } }else{ if(GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS){ //Logging.warn(this, "fire() aborted because coordinator role is already invalidated"); } } } /** * EVENT: "announced", triggered by Elector if the election was won and this coordinator was announced to all cluster members */ public synchronized void eventAnnouncedAsCoordinator() { Logging.log(this, "EVENT: announced as coordinator"); /** * Trigger: explicit cluster announcement to neighbors */ distributeCoordinatorAnnouncement(); /** * AUTO ADDRESS DISTRIBUTION */ if (HRMConfig.Addressing.ASSIGN_AUTOMATICALLY){ //Logging.log(this, "EVENT ANNOUNCED - triggering address assignment for " + mParentCluster.getComChannels().size() + " cluster members"); getCluster().distributeAddresses(); } /** * AUTO CLUSTERING */ if(!getHierarchyLevel().isHighest()) { if (HRMConfig.Hierarchy.CONTINUE_AUTOMATICALLY){ if(getHierarchyLevel().getValue() < HRMConfig.Hierarchy.CONTINUE_AUTOMATICALLY_HIERARCHY_LIMIT){ //Logging.log(this, "EVENT ANNOUNCED - triggering clustering of this cluster's coordinator and its neighbors"); // start the clustering at the hierarchy level mHRMController.cluster(this, new HierarchyLevel(this, getHierarchyLevel().getValue() + 1)); }else{ //Logging.log(this, "EVENT ANNOUNCED - stopping clustering because height limitation is reached at level: " + getHierarchyLevel().getValue()); } }else{ Logging.warn(this, "EVENT ANNOUNCED - stopping clustering because automatic continuation is deactivated"); } } } /** * EVENT: coordinator announcement, we react on this by: * 1.) store the topology information locally * 2.) forward the announcement downward the hierarchy to all locally known clusters (where this node is the head) ("to the bottom") * * @param pComChannel the source comm. channel * @param pAnnounceCoordinator the received announcement */ @Override public void eventCoordinatorAnnouncement(ComChannel pComChannel, AnnounceCoordinator pAnnounceCoordinator) { if(HRMConfig.DebugOutput.SHOW_DEBUG_COORDINATOR_ANNOUNCEMENT_PACKETS){ Logging.log(this, "EVENT: coordinator announcement (from above): " + pAnnounceCoordinator); } /** * Storing that the announced coordinator is a superior one of this node */ // is the packet still on its way from the top to the bottom AND does it not belong to an L0 coordinator? if((!pAnnounceCoordinator.enteredSidewardForwarding()) && (!pAnnounceCoordinator.getSenderClusterName().getHierarchyLevel().isBaseLevel())){ mHRMController.registerSuperiorCoordinator(pAnnounceCoordinator.getSenderClusterName()); } //HINT: we don't store the announced remote coordinator in the ARG here because we are waiting for the side-ward forwarding of the announcement // otherwise, we would store [] routes between this local coordinator and the announced remote one /** * Record the passed clusters */ pAnnounceCoordinator.addGUIPassedCluster(new Long(getGUIClusterID())); /** * Forward the coordinator announcement to all locally known clusters at this hierarchy level */ LinkedList<Cluster> tClusters = mHRMController.getAllClusters(getHierarchyLevel()); if(HRMConfig.DebugOutput.SHOW_DEBUG_COORDINATOR_ANNOUNCEMENT_PACKETS){ Logging.log(this, "\n\n########## Forwarding Coordinator announcement: " + pAnnounceCoordinator); Logging.log(this, " ..distributing in clusters: " + tClusters); } for(Cluster tCluster : tClusters){ tCluster.sendClusterBroadcast(pAnnounceCoordinator, true); } } /** * EVENT: coordinator invalidation, we react on this by: * 1.) remove the topology information locally * 2.) forward the invalidation downward the hierarchy to all locally known clusters (where this node is the head) ("to the bottom") * * @param pComChannel the source comm. channel * @param pInvalidCoordinator the received invalidation */ @Override public synchronized void eventCoordinatorInvalidation(ComChannel pComChannel, InvalidCoordinator pInvalidCoordinator) { if(HRMConfig.DebugOutput.SHOW_DEBUG_COORDINATOR_INVALIDATION_PACKETS){ Logging.log(this, "EVENT: coordinator invalidation (from above): " + pInvalidCoordinator); } /** * Store the announced remote coordinator in the ARG */ if(!pInvalidCoordinator.getSenderClusterName().equals(this)){ unregisterAnnouncedCoordinatorARG(this, pInvalidCoordinator); }else{ Logging.err(this, "eventCoordinatorInvalidation() was triggered for an invalidation of ourself, announcement: " + pInvalidCoordinator); } /** * Forward the coordinator invalidation to all locally known clusters at this hierarchy level */ LinkedList<Cluster> tClusters = mHRMController.getAllClusters(getHierarchyLevel()); if(HRMConfig.DebugOutput.SHOW_DEBUG_COORDINATOR_INVALIDATION_PACKETS){ Logging.log(this, "\n\n########## Forwarding Coordinator invalidation: " + pInvalidCoordinator); Logging.log(this, " ..distributing in clusters: " + tClusters); } for(Cluster tCluster : tClusters){ tCluster.sendClusterBroadcast(pInvalidCoordinator, true); } } /** * Creates a ClusterName object which describes this coordinator * * @return the new ClusterName object */ public ClusterName createCoordinatorName() { ClusterName tResult = null; tResult = new ClusterName(mHRMController, getHierarchyLevel(), getCluster().getClusterID(), getCoordinatorID()); return tResult; } /** * EVENT: new HRMID assigned * The function is called when an address update was received. * * @param pSourceComChannel the source comm. channel * @param pHRMID the new HRMID */ @Override public void eventAssignedHRMID(ComChannel pSourceComChannel, HRMID pHRMID) { if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){ Logging.log(this, "Handling AssignHRMID with assigned HRMID " + pHRMID.toString()); } if((pHRMID != null) && (!pHRMID.isZero())){ // setHRMID() super.eventAssignedHRMID(pSourceComChannel, pHRMID); /** * Automatic address distribution via the cluster */ // we should automatically continue the address distribution? if (HRMConfig.Addressing.ASSIGN_AUTOMATICALLY){ if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){ Logging.log(this, " ..continuing the address distribution process via this cluster"); } getCluster().distributeAddresses(); } } } /** * EVENT: cluster membership request, a cluster requests of a coordinator to acknowledge cluster membership, triggered by the comm. session * * @param pRemoteClusterName the description of the possible new cluster member * @param pSourceComSession the comm. session where the packet was received */ private int mClusterMembershipRequestNr = 0; public void eventClusterMembershipRequest(ClusterName pRemoteClusterName, ComSession pSourceComSession) { mClusterMembershipRequestNr++; Logging.log(this, "EVENT: got cluster membership request (" + mClusterMembershipRequestNr + ") from: " + pRemoteClusterName); if(isThisEntityValid()){ /** * Create new cluster (member) object */ if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){ Logging.log(this, " ..creating new local cluster membership for: " + pRemoteClusterName + ", remote node: " + pSourceComSession.getPeerL2Address()); } CoordinatorAsClusterMember tClusterMembership = CoordinatorAsClusterMember.create(mHRMController, this, pRemoteClusterName, pSourceComSession.getPeerL2Address()); /** * Create the communication channel for the described cluster member */ if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){ Logging.log(this, " ..creating communication channel"); } ComChannel tComChannel = new ComChannel(mHRMController, ComChannel.Direction.IN, tClusterMembership, pSourceComSession); /** * Set the remote ClusterName of the communication channel */ tComChannel.setRemoteClusterName(pRemoteClusterName); /** * SEND: acknowledgment -> will be answered by a BullyPriorityUpdate */ tComChannel.signalRequestClusterMembershipAck(createCoordinatorName()); /** * Trigger: comm. channel established */ tClusterMembership.eventComChannelEstablished(tComChannel); /** * Trigger: joined a remote cluster (sends a Bully priority update) */ tClusterMembership.eventJoinedRemoteCluster(tComChannel); }else{ Logging.warn(this, "eventClusterMembershipRequest() aborted because coordinator role is already invalidated"); /** * Inform the peer by the help of a InformClusterLeft packet */ pSourceComSession.denyClusterMembershipRequest(pRemoteClusterName, createCoordinatorName()); } } public void eventClusterMembershipToSuperiorCoordinator(CoordinatorAsClusterMember pMembership) { Logging.log(this, "EVENT: cluster membership to superior coordinator updated to: " + pMembership); /** * Deactivate the old membership */ if((superiorCoordinatorComChannel() != null) && (superiorCoordinatorComChannel().getParent() != null)){ if(superiorCoordinatorComChannel().getParent() instanceof CoordinatorAsClusterMember){ CoordinatorAsClusterMember tOldMembership = (CoordinatorAsClusterMember)superiorCoordinatorComChannel().getParent(); tOldMembership.setMembershipActivation(false); }else{ Logging.err(this, "Expected a CoordinatorAsClusterMember as parent of: " + superiorCoordinatorComChannel()); } } if(pMembership != null){ /** * Activate the new membership */ pMembership.setMembershipActivation(true); /** * Set the comm. channel to the superior coordinator */ if (superiorCoordinatorComChannel() != pMembership.getComChannelToClusterHead()){ Logging.log(this, "eventClusterMembershipToSuperiorCoordinator() updates comm. channel to superior coordinator: " + pMembership.getComChannelToClusterHead()); setSuperiorCoordinatorComChannel(pMembership.getComChannelToClusterHead()); } /** * Update info. about superior coordinator */ eventClusterCoordinatorAvailable(pMembership.superiorCoordinatorNodeName(), pMembership.getCoordinatorID(), pMembership.superiorCoordinatorHostL2Address(), pMembership.superiorCoordinatorDescription()); /** * Set the HRMID of the CoordinatorAsClusterMember instance */ if((getHRMID() == null) || (getHRMID().isZero()) || (!getHRMID().equals(pMembership.getHRMID()))){ Logging.log(this, "eventClusterMembershipToSuperiorCoordinator() updates HRMID to: " + pMembership.getHRMID()); eventAssignedHRMID(pMembership.getComChannelToClusterHead(), pMembership.getHRMID()); } }else{ /** * reset all data about superior coordinator */ setSuperiorCoordinatorComChannel(null); eventClusterCoordinatorAvailable(null, 0, null, ""); } } /** * EVENT: cluster membership activated * * @param pMembership the membership */ public void eventClusterMembershipActivated(CoordinatorAsClusterMember pMembership) { Logging.log(this, "EVENT: cluster membership activated: " + pMembership); } /** * EVENT: cluster membership deactivated * * @param pMembership the membership */ public void eventClusterMembershipDeactivated(CoordinatorAsClusterMember pMembership) { Logging.log(this, "EVENT: cluster membership deactivated: " + pMembership); /** * If we have lost the membership to the superior coordinator, we search for the next possible superior coordinator/cluster */ if (superiorCoordinatorComChannel() == pMembership.getComChannelToClusterHead()){ Logging.warn(this, "Lost the channel to the superior coordinator, remaining channels to superior clusters: " + getClusterMembershipComChannels()); } } /** * Registers a new cluster membership for this coordinator * * @param pMembership the new cluster membership */ public void registerClusterMembership(CoordinatorAsClusterMember pMembership) { synchronized (mClusterMemberships) { if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){ Logging.log(this, "Registering cluster membership for: " + pMembership); //HINT: a check for already existing cluster memberships has to be done based on equals AND a check of the peer ClusterName } // add this cluster membership mClusterMemberships.add(pMembership); } } /** * Unregisters a new cluster membership for this coordinator * * @param pMembership the cluster membership which should be removed */ public void unregisterClusterMembership(CoordinatorAsClusterMember pMembership) { synchronized (mClusterMemberships) { if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){ Logging.log(this, "Unregistering cluster membership for: " + pMembership); //HINT: a check for already existing cluster memberships has to be done based on equals AND a check of the peer ClusterName } // remove this cluster membership mClusterMemberships.remove(pMembership); } } /** * Returns all register communication channels * * @return the communication channels */ public LinkedList<ComChannel> getClusterMembershipComChannels() { LinkedList<ComChannel> tResult = new LinkedList<ComChannel>(); synchronized (mClusterMemberships) { for (ClusterMember tClusterMembership : mClusterMemberships){ tResult.addAll(tClusterMembership.getComChannels()); } } return tResult; } /** * Checks if a membership to a given cluster does already exist * * @param pCluster the ClusterName of a cluster for which the membership is searched */ private boolean hasMembership(ClusterName pCluster) { boolean tResult = false; //Logging.log(this, "Checking cluster membership for: " + pCluster); synchronized (mClusterMemberships) { for(CoordinatorAsClusterMember tClusterMembership : mClusterMemberships){ //Logging.log(this, " ..cluster membership: " + tClusterMembership); //Logging.log(this, " ..comm. channels: " + tClusterMembership.getComChannels()); if(tClusterMembership.hasComChannel(pCluster)){ tResult = true; break; } } } return tResult; } /** * Returns if the initial clustering has already finished * * @return true or false */ public boolean isClustered() { // search for an existing cluster at this hierarchy level Cluster tSuperiorCluster = mHRMController.getCluster(getHierarchyLevel().getValue() + 1); return ((getHierarchyLevel().isHighest()) || ((tSuperiorCluster != null) && (hasMembership(tSuperiorCluster)))); } /** * Returns the hierarchy Bully priority of the node * * @return the Bully priority */ @Override public BullyPriority getPriority() { return BullyPriority.create(this, mHRMController.getHierarchyNodePriority(getHierarchyLevel())); } /** * Sets a new Bully priority * * @param pPriority the new Bully priority */ @Override public void setPriority(BullyPriority pPriority) { if (!getPriority().equals(pPriority)){ Logging.err(this, "Updating Bully priority from " + getPriority() + " to " + pPriority); }else{ Logging.log(this, "Trying to set same Bully priority " + getPriority()); } // update the Bully priority of the parent cluster, which is managed by this coordinator mParentCluster.setPriority(pPriority); } /** * Assign new HRMID for being addressable. * HINT: We use the HRMID of the managed cluster. * * @param pCaller the caller who assigns the new HRMID * @param pHRMID the new HRMID */ @Override public void setHRMID(Object pCaller, HRMID pHRMID) { Logging.log(this, "Got new HRMID: " + pHRMID + ", caller=" + pCaller); // update the Bully priority of the parent cluster, which is managed by this coordinator mParentCluster.setHRMID(pCaller, pHRMID); } /** * Returns the HRMID under which this node is addressable for this cluster * HINT: We use the HRMID of the managed cluster. * * @return the HRMID */ @Override public HRMID getHRMID() { return mParentCluster.getHRMID(); } /** * Returns a reference to the cluster, which this coordinator manages. * * @return the managed cluster */ public Cluster getCluster() { return mParentCluster; } /** * Returns the unique ID of the parental cluster * * @return the unique cluster ID */ @Override public Long getClusterID() { return mParentCluster.getClusterID(); } /** * Generates a descriptive string about this object * * @return the descriptive string */ public String toString() { return toLocation() + "(" + idToString() + ")"; } /** * Returns a location description about this instance * * @return the location description */ @Override public String toLocation() { String tResult = getClass().getSimpleName() + getGUICoordinatorID() + "@" + mHRMController.getNodeGUIName() + "@" + getHierarchyLevel().getValue(); return tResult; } /** * Returns a string including the ClusterID, the coordinator ID, and the node priority * * @return the complex string */ private String idToString() { if ((getHRMID() == null) || (getHRMID().isRelativeAddress())){ return "Cluster" + getGUIClusterID(); }else{ return "Cluster" + getGUIClusterID() + ", HRMID=" + getHRMID().toString(); } } }
false
true
public void sharePhase() { boolean DEBUG_SHARE_PHASE_DETAILS = false; // should we start the "share phase"? if (sharePhaseHasTimeout()){ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, "SHARE PHASE with cluster members on level " + getHierarchyLevel().getValue() + "/" + (HRMConfig.Hierarchy.HEIGHT - 1)); } // store the time of this "share phase" mTimeOfLastSharePhase = mHRMController.getSimulationTime(); if ((!HRMConfig.Routing.PERIODIC_SHARE_PHASES) && (!hasNewSharePhaseData())){ //TODO if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, "SHARE PHASE aborted because routing data hasn't changed since last signaling round"); } return; } mCallsSharePhase++; // get all comm. channels to inferior cluster members LinkedList<ComChannel> tComChannels = mParentCluster.getComChannels(); /******************************************************************* * Iterate over all comm. channels and share routing data *******************************************************************/ for (ComChannel tComChannel : tComChannels){ /** * Only proceed if the link is actually active */ if(tComChannel.isLinkActive()){ RoutingTable tSharedRoutingTable = new RoutingTable(); HRMID tPeerHRMID = tComChannel.getPeerHRMID(); if((tPeerHRMID != null) && (!tPeerHRMID.isZero())){ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, " ..sharing routes with: " + tPeerHRMID); } if(getHierarchyLevel().isBaseLevel()){ HRMID tThisNodeHRMID = getCluster().getL0HRMID(); /********************************************************************* * SHARE 1: received routes from superior coordinator *********************************************************************/ // copy the received routing table RoutingTable tReceivedSharedRoutingTable = null; synchronized (mReceivedSharedRoutingTable) { tReceivedSharedRoutingTable = (RoutingTable) mReceivedSharedRoutingTable.clone(); } int j = -1; for(RoutingEntry tEntry : tReceivedSharedRoutingTable){ j++; /** * does the received route start at the peer? * => share: [original route from sup. coordinator] */ if(tEntry.getSource().isCluster(tPeerHRMID)){ RoutingEntry tNewEntry = tEntry.clone(); tNewEntry.extendCause(this + "::sharePhase()_ReceivedRouteShare_1(" + mCallsSharePhase + ")(" + j + ") as " + tNewEntry); // share the received entry with the peer tSharedRoutingTable.addEntry(tNewEntry); continue; } /** * does the received route start at this node and the next node isn't the peer? * => share: [route from peer to this node] ==> [original route from sup. coordinator] */ if((tEntry.getSource().equals(tThisNodeHRMID)) && (!tEntry.getNextHop().equals(tPeerHRMID))){ RoutingEntry tRoutingEntryWithPeer = mHRMController.getRoutingEntryHRG(tPeerHRMID, tThisNodeHRMID); if(tRoutingEntryWithPeer != null){ tRoutingEntryWithPeer.chain(tEntry); tRoutingEntryWithPeer.extendCause(this + "::sharePhase()_ReceivedRouteShare_2(" + mCallsSharePhase + ")(" + j + ") as " + tRoutingEntryWithPeer); // share the received entry with the peer tSharedRoutingTable.addEntry(tRoutingEntryWithPeer); } continue; } } }else{ // /********************************************************************* // * SHARE: routes to neighbors of ourself // *********************************************************************/ // // find all siblings of ourself // //HINT: the found siblings have the same hierarchy level like this coordinator // LinkedList<HRMID> tKnownSibblings = mHRMController.getDestinationsHRG(getHRMID()); // for(HRMID tPossibleDestination : tKnownSibblings){ // if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ // Logging.log(this, " ..possible higher destination: " + tPossibleDestination); // } // // // get the inter-cluster path to the possible destination // List<AbstractRoutingGraphLink> tPath = mHRMController.getRouteHRG(getHRMID(), tPossibleDestination); // if(tPath != null){ // // } // } /********************************************************************* * SHARE 2: routes to known siblings of the peer at the same hierarchy level *********************************************************************/ // find all siblings of the peer //HINT: the peer is one hierarchy level below this coordinator LinkedList<HRMID> tKnownPeerSiblings = mHRMController.getSiblingsHRG(tPeerHRMID); for(HRMID tPossibleDestination : tKnownPeerSiblings){ if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..possible peer destination: " + tPossibleDestination + " for: " + tPeerHRMID); Logging.log(this, " ..determining path from " + tPeerHRMID + " to " + tPossibleDestination); } int tStep = 0; // get the inter-cluster path to the possible destination List<AbstractRoutingGraphLink> tPath = mHRMController.getRouteHRG(tPeerHRMID, tPossibleDestination); if(tPath != null){ // the searched routing entry to the possible destination cluster RoutingEntry tFinalRoutingEntryToDestination = null; // the last cluster gateway HRMID tLastClusterGateway = null; HRMID tFirstForeignGateway = null; if(!tPath.isEmpty()){ if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..found inter cluster path:"); for(AbstractRoutingGraphLink tLink : tPath){ Logging.log(this, " ..step: " + tLink); } } for(AbstractRoutingGraphLink tLink : tPath){ RoutingEntry tInterClusterRoutingEntry = (RoutingEntry)tLink.getRoute().getFirst(); if(tFinalRoutingEntryToDestination != null){ if(tLastClusterGateway == null){ throw new RuntimeException(this + "::sharePhase() should never reach this point"); } /************************************************************************************************ * ROUTE PART: the intra-cluster route from the last gateway to the next one ***********************************************************************************************/ // the next cluster gateway HRMID tNextClusterGateway = tInterClusterRoutingEntry.getSource(); if(!tLastClusterGateway.equals(tNextClusterGateway)){ // the intra-cluster path List<AbstractRoutingGraphLink> tIntraClusterPath = mHRMController.getRouteHRG(tLastClusterGateway, tNextClusterGateway); if(tIntraClusterPath != null){ if(!tIntraClusterPath.isEmpty()){ RoutingEntry tLogicalIntraClusterRoutingEntry = null; /** * Determine the intra-cluster route part */ // check if we have only one hop in intra-cluster route if(tIntraClusterPath.size() == 1){ AbstractRoutingGraphLink tIntraClusterLogLink = tIntraClusterPath.get(0); // get the routing entry from the last gateway to the next one tLogicalIntraClusterRoutingEntry = (RoutingEntry) tIntraClusterLogLink.getRoute().getFirst(); }else{ tLogicalIntraClusterRoutingEntry = RoutingEntry.create(tIntraClusterPath); if(tLogicalIntraClusterRoutingEntry == null){ Logging.warn(this, "sharePhase() for " + tPeerHRMID + " found a complex intra-cluster path and wasn't able to derive an aggregated logical link from it.."); Logging.warn(this, " ..path: " + tIntraClusterPath); Logging.warn(this, " ..from: " + tLastClusterGateway); Logging.warn(this, " ..to: " + tNextClusterGateway); Logging.warn(this, " ..for a routing from " + tPeerHRMID + " to " + tPossibleDestination); // reset tFinalRoutingEntryToDestination = null; // abort break; } } /** * Add the intra-cluster route part */ if(tLogicalIntraClusterRoutingEntry != null){ // chain the routing entries if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..step [" + tStep + "] (intra-cluster): " + tLogicalIntraClusterRoutingEntry); } tFinalRoutingEntryToDestination.chain(tLogicalIntraClusterRoutingEntry); tStep++; /** * Determine the next hop for the resulting path */ if(tFirstForeignGateway == null){ if(tLogicalIntraClusterRoutingEntry.getHopCount() > 0){ tFirstForeignGateway = tLogicalIntraClusterRoutingEntry.getNextHop(); } } } }else{ Logging.warn(this, "sharePhase() for " + tPeerHRMID + " found an empty intra-cluster path.."); Logging.warn(this, " ..from: " + tLastClusterGateway); Logging.warn(this, " ..to: " + tNextClusterGateway); Logging.warn(this, " ..for a routing from " + tPeerHRMID + " to " + tPossibleDestination); } }else{ Logging.warn(this, "sharePhase() for " + tPeerHRMID + " couldn't find a route from " + tLastClusterGateway + " to " + tNextClusterGateway + " for a routing from " + tPeerHRMID + " to " + tPossibleDestination); // reset tFinalRoutingEntryToDestination = null; // abort break; //HINT: do not throw a RuntimeException here because such a situation could have a temporary cause } }else{ // tLastClusterGateway and tNextClusterGateway are equal => empty route for cluster traversal } /*********************************************************************************************** * ROUTE PART: the inter-cluster link ***********************************************************************************************/ // chain the routing entries if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..step [" + tStep + "] (cluster-2-cluster): " + tInterClusterRoutingEntry); } tFinalRoutingEntryToDestination.chain(tInterClusterRoutingEntry); }else{ /*********************************************************************************************** * ROUTE PART: first step of the resulting path ***********************************************************************************************/ if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..step [" + tStep + "] (cluster-2-cluster): " + tInterClusterRoutingEntry); } tFinalRoutingEntryToDestination = tInterClusterRoutingEntry; } tStep++; /** * Determine the next hop for the resulting path */ if(tFirstForeignGateway == null){ if(tInterClusterRoutingEntry.getHopCount() > 0){ tFirstForeignGateway = tInterClusterRoutingEntry.getNextHop(); } } //update last cluster gateway tLastClusterGateway = tInterClusterRoutingEntry.getNextHop(); } }else{ Logging.err(this, "sharePhase() for " + tPeerHRMID + " found an empty path from " + tPeerHRMID + " to " + tPossibleDestination); } if(tFinalRoutingEntryToDestination != null){ /** * Set the DESTINATION for the resulting routing entry */ tFinalRoutingEntryToDestination.setDest(tPeerHRMID.getForeignCluster(tPossibleDestination) /* aggregate the destination here */); /** * Set the NEXT HOP for the resulting routing entry */ if(tFirstForeignGateway != null){ tFinalRoutingEntryToDestination.setNextHop(tFirstForeignGateway); } /** * Add the found routing entry to the shared routing table */ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, " ..==> routing entry: " + tFinalRoutingEntryToDestination); } tFinalRoutingEntryToDestination.extendCause(this + "::sharePhase()_HRG_based(" + mCallsSharePhase + ")"); tSharedRoutingTable.addEntry(tFinalRoutingEntryToDestination); } }else{ Logging.err(this, "sharePhase() for " + tPeerHRMID + " couldn't determine a route from " + tPeerHRMID + " to " + tPossibleDestination); } } } if(tSharedRoutingTable.size() > 0){ tComChannel.distributeRouteShare(tSharedRoutingTable); } } } } }else{ // share phase shouldn't be started, we have to wait until next trigger } }
public void sharePhase() { boolean DEBUG_SHARE_PHASE_DETAILS = false; // should we start the "share phase"? if (sharePhaseHasTimeout()){ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, "SHARE PHASE with cluster members on level " + getHierarchyLevel().getValue() + "/" + (HRMConfig.Hierarchy.HEIGHT - 1)); } // store the time of this "share phase" mTimeOfLastSharePhase = mHRMController.getSimulationTime(); if ((!HRMConfig.Routing.PERIODIC_SHARE_PHASES) && (!hasNewSharePhaseData())){ //TODO if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, "SHARE PHASE aborted because routing data hasn't changed since last signaling round"); } return; } mCallsSharePhase++; // get all comm. channels to inferior cluster members LinkedList<ComChannel> tComChannels = mParentCluster.getComChannels(); /******************************************************************* * Iterate over all comm. channels and share routing data *******************************************************************/ for (ComChannel tComChannel : tComChannels){ /** * Only proceed if the link is actually active */ if(tComChannel.isLinkActive()){ RoutingTable tSharedRoutingTable = new RoutingTable(); HRMID tPeerHRMID = tComChannel.getPeerHRMID(); if((tPeerHRMID != null) && (!tPeerHRMID.isZero())){ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, " ..sharing routes with: " + tPeerHRMID); } if(getHierarchyLevel().isBaseLevel()){ HRMID tThisNodeHRMID = getCluster().getL0HRMID(); /********************************************************************* * SHARE 1: received routes from superior coordinator *********************************************************************/ // copy the received routing table RoutingTable tReceivedSharedRoutingTable = null; synchronized (mReceivedSharedRoutingTable) { tReceivedSharedRoutingTable = (RoutingTable) mReceivedSharedRoutingTable.clone(); } int j = -1; for(RoutingEntry tReceivedSharedRoutingEntry : tReceivedSharedRoutingTable){ j++; /** * does the received route start at the peer? * => share: [original route from sup. coordinator] */ if(tReceivedSharedRoutingEntry.getSource().isCluster(tPeerHRMID)){ RoutingEntry tNewEntry = tReceivedSharedRoutingEntry.clone(); // reset L2Address for next hop tNewEntry.setNextHopL2Address(null); tNewEntry.extendCause(this + "::sharePhase()_ReceivedRouteShare_1(" + mCallsSharePhase + ")(" + j + ") as " + tNewEntry); // share the received entry with the peer tSharedRoutingTable.addEntry(tNewEntry); continue; } /** * does the received route start at this node and the next node isn't the peer? * => share: [route from peer to this node] ==> [original route from sup. coordinator] */ if((tReceivedSharedRoutingEntry.getSource().equals(tThisNodeHRMID)) && (!tReceivedSharedRoutingEntry.getNextHop().equals(tPeerHRMID))){ RoutingEntry tRoutingEntryWithPeer = mHRMController.getRoutingEntryHRG(tPeerHRMID, tThisNodeHRMID); if(tRoutingEntryWithPeer != null){ RoutingEntry tNewEntry = tRoutingEntryWithPeer.clone(); // reset L2Address for next hop tNewEntry.setNextHopL2Address(null); tNewEntry.chain(tReceivedSharedRoutingEntry); tNewEntry.extendCause(this + "::sharePhase()_ReceivedRouteShare_2(" + mCallsSharePhase + ")(" + j + ") as combination of " + tRoutingEntryWithPeer + " and " + tReceivedSharedRoutingEntry); // share the received entry with the peer tSharedRoutingTable.addEntry(tNewEntry); } continue; } } }else{ // /********************************************************************* // * SHARE: routes to neighbors of ourself // *********************************************************************/ // // find all siblings of ourself // //HINT: the found siblings have the same hierarchy level like this coordinator // LinkedList<HRMID> tKnownSibblings = mHRMController.getDestinationsHRG(getHRMID()); // for(HRMID tPossibleDestination : tKnownSibblings){ // if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ // Logging.log(this, " ..possible higher destination: " + tPossibleDestination); // } // // // get the inter-cluster path to the possible destination // List<AbstractRoutingGraphLink> tPath = mHRMController.getRouteHRG(getHRMID(), tPossibleDestination); // if(tPath != null){ // // } // } /********************************************************************* * SHARE 2: routes to known siblings of the peer at the same hierarchy level *********************************************************************/ // find all siblings of the peer //HINT: the peer is one hierarchy level below this coordinator LinkedList<HRMID> tKnownPeerSiblings = mHRMController.getSiblingsHRG(tPeerHRMID); for(HRMID tPossibleDestination : tKnownPeerSiblings){ if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..possible peer destination: " + tPossibleDestination + " for: " + tPeerHRMID); Logging.log(this, " ..determining path from " + tPeerHRMID + " to " + tPossibleDestination); } int tStep = 0; // get the inter-cluster path to the possible destination List<AbstractRoutingGraphLink> tPath = mHRMController.getRouteHRG(tPeerHRMID, tPossibleDestination); if(tPath != null){ // the searched routing entry to the possible destination cluster RoutingEntry tFinalRoutingEntryToDestination = null; // the last cluster gateway HRMID tLastClusterGateway = null; HRMID tFirstForeignGateway = null; if(!tPath.isEmpty()){ if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..found inter cluster path:"); for(AbstractRoutingGraphLink tLink : tPath){ Logging.log(this, " ..step: " + tLink); } } for(AbstractRoutingGraphLink tLink : tPath){ RoutingEntry tInterClusterRoutingEntry = (RoutingEntry)tLink.getRoute().getFirst(); if(tFinalRoutingEntryToDestination != null){ if(tLastClusterGateway == null){ throw new RuntimeException(this + "::sharePhase() should never reach this point"); } /************************************************************************************************ * ROUTE PART: the intra-cluster route from the last gateway to the next one ***********************************************************************************************/ // the next cluster gateway HRMID tNextClusterGateway = tInterClusterRoutingEntry.getSource(); if(!tLastClusterGateway.equals(tNextClusterGateway)){ // the intra-cluster path List<AbstractRoutingGraphLink> tIntraClusterPath = mHRMController.getRouteHRG(tLastClusterGateway, tNextClusterGateway); if(tIntraClusterPath != null){ if(!tIntraClusterPath.isEmpty()){ RoutingEntry tLogicalIntraClusterRoutingEntry = null; /** * Determine the intra-cluster route part */ // check if we have only one hop in intra-cluster route if(tIntraClusterPath.size() == 1){ AbstractRoutingGraphLink tIntraClusterLogLink = tIntraClusterPath.get(0); // get the routing entry from the last gateway to the next one tLogicalIntraClusterRoutingEntry = (RoutingEntry) tIntraClusterLogLink.getRoute().getFirst(); }else{ tLogicalIntraClusterRoutingEntry = RoutingEntry.create(tIntraClusterPath); if(tLogicalIntraClusterRoutingEntry == null){ Logging.warn(this, "sharePhase() for " + tPeerHRMID + " found a complex intra-cluster path and wasn't able to derive an aggregated logical link from it.."); Logging.warn(this, " ..path: " + tIntraClusterPath); Logging.warn(this, " ..from: " + tLastClusterGateway); Logging.warn(this, " ..to: " + tNextClusterGateway); Logging.warn(this, " ..for a routing from " + tPeerHRMID + " to " + tPossibleDestination); // reset tFinalRoutingEntryToDestination = null; // abort break; } } /** * Add the intra-cluster route part */ if(tLogicalIntraClusterRoutingEntry != null){ // chain the routing entries if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..step [" + tStep + "] (intra-cluster): " + tLogicalIntraClusterRoutingEntry); } tFinalRoutingEntryToDestination.chain(tLogicalIntraClusterRoutingEntry); tStep++; /** * Determine the next hop for the resulting path */ if(tFirstForeignGateway == null){ if(tLogicalIntraClusterRoutingEntry.getHopCount() > 0){ tFirstForeignGateway = tLogicalIntraClusterRoutingEntry.getNextHop(); } } } }else{ Logging.warn(this, "sharePhase() for " + tPeerHRMID + " found an empty intra-cluster path.."); Logging.warn(this, " ..from: " + tLastClusterGateway); Logging.warn(this, " ..to: " + tNextClusterGateway); Logging.warn(this, " ..for a routing from " + tPeerHRMID + " to " + tPossibleDestination); } }else{ Logging.warn(this, "sharePhase() for " + tPeerHRMID + " couldn't find a route from " + tLastClusterGateway + " to " + tNextClusterGateway + " for a routing from " + tPeerHRMID + " to " + tPossibleDestination); // reset tFinalRoutingEntryToDestination = null; // abort break; //HINT: do not throw a RuntimeException here because such a situation could have a temporary cause } }else{ // tLastClusterGateway and tNextClusterGateway are equal => empty route for cluster traversal } /*********************************************************************************************** * ROUTE PART: the inter-cluster link ***********************************************************************************************/ // chain the routing entries if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..step [" + tStep + "] (cluster-2-cluster): " + tInterClusterRoutingEntry); } tFinalRoutingEntryToDestination.chain(tInterClusterRoutingEntry); }else{ /*********************************************************************************************** * ROUTE PART: first step of the resulting path ***********************************************************************************************/ if (DEBUG_SHARE_PHASE_DETAILS){ Logging.log(this, " ..step [" + tStep + "] (cluster-2-cluster): " + tInterClusterRoutingEntry); } tFinalRoutingEntryToDestination = tInterClusterRoutingEntry; } tStep++; /** * Determine the next hop for the resulting path */ if(tFirstForeignGateway == null){ if(tInterClusterRoutingEntry.getHopCount() > 0){ tFirstForeignGateway = tInterClusterRoutingEntry.getNextHop(); } } //update last cluster gateway tLastClusterGateway = tInterClusterRoutingEntry.getNextHop(); } }else{ Logging.err(this, "sharePhase() for " + tPeerHRMID + " found an empty path from " + tPeerHRMID + " to " + tPossibleDestination); } if(tFinalRoutingEntryToDestination != null){ /** * Set the DESTINATION for the resulting routing entry */ tFinalRoutingEntryToDestination.setDest(tPeerHRMID.getForeignCluster(tPossibleDestination) /* aggregate the destination here */); /** * Set the NEXT HOP for the resulting routing entry */ if(tFirstForeignGateway != null){ tFinalRoutingEntryToDestination.setNextHop(tFirstForeignGateway); } /** * Add the found routing entry to the shared routing table */ if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ Logging.log(this, " ..==> routing entry: " + tFinalRoutingEntryToDestination); } // reset L2Address for next hop tFinalRoutingEntryToDestination.setNextHopL2Address(null); tFinalRoutingEntryToDestination.extendCause(this + "::sharePhase()_HRG_based(" + mCallsSharePhase + ")"); tSharedRoutingTable.addEntry(tFinalRoutingEntryToDestination); } }else{ Logging.err(this, "sharePhase() for " + tPeerHRMID + " couldn't determine a route from " + tPeerHRMID + " to " + tPossibleDestination); } } } if(tSharedRoutingTable.size() > 0){ tComChannel.distributeRouteShare(tSharedRoutingTable); } } } } }else{ // share phase shouldn't be started, we have to wait until next trigger } }
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.tcf.core/src/org/eclipse/tcf/te/tcf/core/va/AbstractExternalValueAdd.java b/target_explorer/plugins/org.eclipse.tcf.te.tcf.core/src/org/eclipse/tcf/te/tcf/core/va/AbstractExternalValueAdd.java index e4860fe63..445035c17 100644 --- a/target_explorer/plugins/org.eclipse.tcf.te.tcf.core/src/org/eclipse/tcf/te/tcf/core/va/AbstractExternalValueAdd.java +++ b/target_explorer/plugins/org.eclipse.tcf.te.tcf.core/src/org/eclipse/tcf/te/tcf/core/va/AbstractExternalValueAdd.java @@ -1,363 +1,363 @@ /******************************************************************************* * Copyright (c) 2012 Wind River Systems, Inc. and others. All rights reserved. * This program and the accompanying materials are made available under the terms * of the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.tcf.te.tcf.core.va; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.osgi.util.NLS; import org.eclipse.tcf.protocol.IChannel; import org.eclipse.tcf.protocol.IPeer; import org.eclipse.tcf.protocol.JSON; import org.eclipse.tcf.protocol.Protocol; import org.eclipse.tcf.te.core.async.AsyncCallbackCollector; import org.eclipse.tcf.te.runtime.callback.Callback; import org.eclipse.tcf.te.runtime.interfaces.callback.ICallback; import org.eclipse.tcf.te.runtime.utils.net.IPAddressUtil; import org.eclipse.tcf.te.tcf.core.activator.CoreBundleActivator; import org.eclipse.tcf.te.tcf.core.async.CallbackInvocationDelegate; import org.eclipse.tcf.te.tcf.core.interfaces.tracing.ITraceIds; import org.eclipse.tcf.te.tcf.core.nls.Messages; import org.eclipse.tcf.te.tcf.core.peers.Peer; /** * Abstract external value add implementation. */ public abstract class AbstractExternalValueAdd extends AbstractValueAdd { // The per peer id value add entry map /* default */ final Map<String, ValueAddEntry> entries = new HashMap<String, ValueAddEntry>(); /** * Class representing a value add entry */ protected static class ValueAddEntry { public Process process; public IPeer peer; } /* (non-Javadoc) * @see org.eclipse.tcf.te.tcf.core.va.interfaces.IValueAdd#getPeer(java.lang.String) */ @Override public IPeer getPeer(String id) { Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$ Assert.isNotNull(id); IPeer peer = null; ValueAddEntry entry = entries.get(id); if (entry != null) { peer = entry.peer; } return peer; } /* (non-Javadoc) * @see org.eclipse.tcf.te.tcf.core.va.interfaces.IValueAdd#isAlive(java.lang.String, org.eclipse.tcf.te.runtime.interfaces.callback.ICallback) */ @Override public void isAlive(final String id, final ICallback done) { Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$ Assert.isNotNull(id); Assert.isNotNull(done); // Assume that the value-add is not alive done.setResult(Boolean.FALSE); // Query the associated entry ValueAddEntry entry = entries.get(id); // If no entry is available yet, but a debug peer id // is set, create a corresponding entry for it if (entry == null && getDebugPeerId() != null) { String[] attrs = getDebugPeerId().split(":"); //$NON-NLS-1$ if (attrs.length == 3) { Map<String, String> props = new HashMap<String, String>(); props.put(IPeer.ATTR_ID, getDebugPeerId()); props.put(IPeer.ATTR_TRANSPORT_NAME, attrs[0]); if (attrs[1].length() > 0) { props.put(IPeer.ATTR_IP_HOST, attrs[1]); } else { props.put(IPeer.ATTR_IP_HOST, IPAddressUtil.getInstance().getIPv4LoopbackAddress()); } props.put(IPeer.ATTR_IP_PORT, attrs[2]); entry = new ValueAddEntry(); entry.peer = new Peer(props); entries.put(id, entry); } } if (entry != null) { // Check if the process is still alive or has auto-exited already boolean exited = false; if (entry.process != null) { Assert.isNotNull(entry.peer); try { entry.process.exitValue(); exited = true; } catch (IllegalThreadStateException e) { /* ignored on purpose */ } } // If the process is still running, try to open a channel if (!exited) { final ValueAddEntry finEntry = entry; final IChannel channel = entry.peer.openChannel(); channel.addChannelListener(new IChannel.IChannelListener() { @Override public void onChannelOpened() { // Remove ourself as channel listener channel.removeChannelListener(this); // Close the channel, it is not longer needed channel.close(); // Invoke the callback done.setResult(Boolean.TRUE); done.done(AbstractExternalValueAdd.this, Status.OK_STATUS); } @Override public void onChannelClosed(Throwable error) { // Remove ourself as channel listener channel.removeChannelListener(this); // External value-add is not longer alive, clean up entries.remove(id); if (finEntry.process != null) { finEntry.process.destroy(); } // Invoke the callback done.done(AbstractExternalValueAdd.this, Status.OK_STATUS); } @Override public void congestionLevel(int level) { } }); } else { done.done(AbstractExternalValueAdd.this, Status.OK_STATUS); } } else { done.done(AbstractExternalValueAdd.this, Status.OK_STATUS); } } /* (non-Javadoc) * @see org.eclipse.tcf.te.tcf.core.va.interfaces.IValueAdd#launch(java.lang.String, org.eclipse.tcf.te.runtime.interfaces.callback.ICallback) */ @SuppressWarnings("unchecked") @Override public void launch(String id, ICallback done) { Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$ Assert.isNotNull(id); Assert.isNotNull(done); Throwable error = null; // Get the location of the executable image IPath path = getLocation(); if (path != null && path.toFile().canRead()) { ValueAddLauncher launcher = createLauncher(id, path); try { launcher.launch(); } catch (Throwable e) { error = e; } // Prepare the value-add entry ValueAddEntry entry = new ValueAddEntry(); if (error == null) { // Get the external process Process process = launcher.getProcess(); try { // Check if the process exited right after the launch int exitCode = process.exitValue(); // Died -> Fail the launch error = new IOException("Value-add process died with exit code " + exitCode); //$NON-NLS-1$ } catch (IllegalThreadStateException e) { // Still running -> Associate the process with the entry entry.process = process; } } String output = null; if (error == null) { // The agent is started with "-S" to write out the peer attributes in JSON format. int counter = 10; while (counter > 0 && output == null) { // Try to read in the output output = launcher.getOutputReader().getOutput(); - if ("".equals(output)) { //$NON-NLS-1$ + if ("".equals(output) || output.indexOf("Server-Properties:") == -1) { //$NON-NLS-1$ //$NON-NLS-2$ output = null; try { Thread.sleep(200); } catch (InterruptedException e) { /* ignored on purpose */ } } counter--; } if (output == null) { error = new IOException("Failed to read output from value-add."); //$NON-NLS-1$ } } Map<String, String> attrs = null; if (error == null) { if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) { CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.AbstractExternalValueAdd_output, output, id), 0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this); } // Find the "Server-Properties: ..." string within the output int start = output.indexOf("Server-Properties:"); //$NON-NLS-1$ if (start != -1 && start > 0) { output = output.substring(start); } // Strip away "Server-Properties:" output = output.replace("Server-Properties:", " "); //$NON-NLS-1$ //$NON-NLS-2$ output = output.trim(); // Read into an object Object object = null; try { object = JSON.parseOne(output.getBytes("UTF-8")); //$NON-NLS-1$ attrs = new HashMap<String, String>((Map<String, String>)object); } catch (IOException e) { error = e; } } if (error == null) { // Construct the peer id from peer attributes // The expected peer id is "<transport>:<canonical IP>:<port>" String transport = attrs.get(IPeer.ATTR_TRANSPORT_NAME); String port = attrs.get(IPeer.ATTR_IP_PORT); String ip = IPAddressUtil.getInstance().getIPv4LoopbackAddress(); if (transport != null && ip != null && port != null) { String peerId = transport + ":" + ip + ":" + port; //$NON-NLS-1$ //$NON-NLS-2$ attrs.put(IPeer.ATTR_ID, peerId); attrs.put(IPeer.ATTR_IP_HOST, ip); entry.peer = new Peer(attrs); } else { error = new IOException("Invalid or incomplete peer attributes reported by value-add."); //$NON-NLS-1$ } } if (error == null) { Assert.isNotNull(entry.process); Assert.isNotNull(entry.peer); entries.put(id, entry); } // Stop the output reader thread launcher.getOutputReader().interrupt(); } else { error = new FileNotFoundException(NLS.bind(Messages.AbstractExternalValueAdd_error_invalidLocation, this.getId())); } IStatus status = Status.OK_STATUS; if (error != null) { status = new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), error.getLocalizedMessage(), error); } done.done(AbstractExternalValueAdd.this, status); } /** * Returns the absolute path to the value-add executable image. * * @return The absolute path or <code>null</code> if not found. */ protected abstract IPath getLocation(); /** * Create a new value-add launcher instance. * * @param id The target peer id. Must not be <code>null</code>. * @param path The absolute path to the value-add executable image. Must not be <code>null</code>. * * @return The value-add launcher instance. */ protected ValueAddLauncher createLauncher(String id, IPath path) { Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$ Assert.isNotNull(id); Assert.isNotNull(path); return new ValueAddLauncher(id, path, getLabel() != null ? getLabel() : getId()); } /* (non-Javadoc) * @see org.eclipse.tcf.te.tcf.core.va.interfaces.IValueAdd#shutdown(java.lang.String, org.eclipse.tcf.te.runtime.interfaces.callback.ICallback) */ @Override public void shutdown(final String id, final ICallback done) { Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$ Assert.isNotNull(id); Assert.isNotNull(done); final ValueAddEntry entry = entries.get(id); if (entry != null) { isAlive(id, new Callback() { @Override protected void internalDone(Object caller, IStatus status) { boolean alive = ((Boolean)getResult()).booleanValue(); if (alive) { entries.remove(id); if (entry.process != null) { entry.process.destroy(); } } done.done(AbstractExternalValueAdd.this, Status.OK_STATUS); } }); } else { done.done(AbstractExternalValueAdd.this, Status.OK_STATUS); } } /* (non-Javadoc) * @see org.eclipse.tcf.te.tcf.core.va.interfaces.IValueAdd#shutdownAll(org.eclipse.tcf.te.runtime.interfaces.callback.ICallback) */ @Override public void shutdownAll(ICallback done) { Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$ Assert.isNotNull(done); AsyncCallbackCollector collector = new AsyncCallbackCollector(done, new CallbackInvocationDelegate()); for (String id : entries.keySet()) { ICallback callback = new AsyncCallbackCollector.SimpleCollectorCallback(collector); shutdown(id, callback); } collector.initDone(); } }
true
true
public void launch(String id, ICallback done) { Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$ Assert.isNotNull(id); Assert.isNotNull(done); Throwable error = null; // Get the location of the executable image IPath path = getLocation(); if (path != null && path.toFile().canRead()) { ValueAddLauncher launcher = createLauncher(id, path); try { launcher.launch(); } catch (Throwable e) { error = e; } // Prepare the value-add entry ValueAddEntry entry = new ValueAddEntry(); if (error == null) { // Get the external process Process process = launcher.getProcess(); try { // Check if the process exited right after the launch int exitCode = process.exitValue(); // Died -> Fail the launch error = new IOException("Value-add process died with exit code " + exitCode); //$NON-NLS-1$ } catch (IllegalThreadStateException e) { // Still running -> Associate the process with the entry entry.process = process; } } String output = null; if (error == null) { // The agent is started with "-S" to write out the peer attributes in JSON format. int counter = 10; while (counter > 0 && output == null) { // Try to read in the output output = launcher.getOutputReader().getOutput(); if ("".equals(output)) { //$NON-NLS-1$ output = null; try { Thread.sleep(200); } catch (InterruptedException e) { /* ignored on purpose */ } } counter--; } if (output == null) { error = new IOException("Failed to read output from value-add."); //$NON-NLS-1$ } } Map<String, String> attrs = null; if (error == null) { if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) { CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.AbstractExternalValueAdd_output, output, id), 0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this); } // Find the "Server-Properties: ..." string within the output int start = output.indexOf("Server-Properties:"); //$NON-NLS-1$ if (start != -1 && start > 0) { output = output.substring(start); } // Strip away "Server-Properties:" output = output.replace("Server-Properties:", " "); //$NON-NLS-1$ //$NON-NLS-2$ output = output.trim(); // Read into an object Object object = null; try { object = JSON.parseOne(output.getBytes("UTF-8")); //$NON-NLS-1$ attrs = new HashMap<String, String>((Map<String, String>)object); } catch (IOException e) { error = e; } } if (error == null) { // Construct the peer id from peer attributes // The expected peer id is "<transport>:<canonical IP>:<port>" String transport = attrs.get(IPeer.ATTR_TRANSPORT_NAME); String port = attrs.get(IPeer.ATTR_IP_PORT); String ip = IPAddressUtil.getInstance().getIPv4LoopbackAddress(); if (transport != null && ip != null && port != null) { String peerId = transport + ":" + ip + ":" + port; //$NON-NLS-1$ //$NON-NLS-2$ attrs.put(IPeer.ATTR_ID, peerId); attrs.put(IPeer.ATTR_IP_HOST, ip); entry.peer = new Peer(attrs); } else { error = new IOException("Invalid or incomplete peer attributes reported by value-add."); //$NON-NLS-1$ } } if (error == null) { Assert.isNotNull(entry.process); Assert.isNotNull(entry.peer); entries.put(id, entry); } // Stop the output reader thread launcher.getOutputReader().interrupt(); } else { error = new FileNotFoundException(NLS.bind(Messages.AbstractExternalValueAdd_error_invalidLocation, this.getId())); } IStatus status = Status.OK_STATUS; if (error != null) { status = new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), error.getLocalizedMessage(), error); } done.done(AbstractExternalValueAdd.this, status); }
public void launch(String id, ICallback done) { Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$ Assert.isNotNull(id); Assert.isNotNull(done); Throwable error = null; // Get the location of the executable image IPath path = getLocation(); if (path != null && path.toFile().canRead()) { ValueAddLauncher launcher = createLauncher(id, path); try { launcher.launch(); } catch (Throwable e) { error = e; } // Prepare the value-add entry ValueAddEntry entry = new ValueAddEntry(); if (error == null) { // Get the external process Process process = launcher.getProcess(); try { // Check if the process exited right after the launch int exitCode = process.exitValue(); // Died -> Fail the launch error = new IOException("Value-add process died with exit code " + exitCode); //$NON-NLS-1$ } catch (IllegalThreadStateException e) { // Still running -> Associate the process with the entry entry.process = process; } } String output = null; if (error == null) { // The agent is started with "-S" to write out the peer attributes in JSON format. int counter = 10; while (counter > 0 && output == null) { // Try to read in the output output = launcher.getOutputReader().getOutput(); if ("".equals(output) || output.indexOf("Server-Properties:") == -1) { //$NON-NLS-1$ //$NON-NLS-2$ output = null; try { Thread.sleep(200); } catch (InterruptedException e) { /* ignored on purpose */ } } counter--; } if (output == null) { error = new IOException("Failed to read output from value-add."); //$NON-NLS-1$ } } Map<String, String> attrs = null; if (error == null) { if (CoreBundleActivator.getTraceHandler().isSlotEnabled(0, ITraceIds.TRACE_CHANNEL_MANAGER)) { CoreBundleActivator.getTraceHandler().trace(NLS.bind(Messages.AbstractExternalValueAdd_output, output, id), 0, ITraceIds.TRACE_CHANNEL_MANAGER, IStatus.INFO, this); } // Find the "Server-Properties: ..." string within the output int start = output.indexOf("Server-Properties:"); //$NON-NLS-1$ if (start != -1 && start > 0) { output = output.substring(start); } // Strip away "Server-Properties:" output = output.replace("Server-Properties:", " "); //$NON-NLS-1$ //$NON-NLS-2$ output = output.trim(); // Read into an object Object object = null; try { object = JSON.parseOne(output.getBytes("UTF-8")); //$NON-NLS-1$ attrs = new HashMap<String, String>((Map<String, String>)object); } catch (IOException e) { error = e; } } if (error == null) { // Construct the peer id from peer attributes // The expected peer id is "<transport>:<canonical IP>:<port>" String transport = attrs.get(IPeer.ATTR_TRANSPORT_NAME); String port = attrs.get(IPeer.ATTR_IP_PORT); String ip = IPAddressUtil.getInstance().getIPv4LoopbackAddress(); if (transport != null && ip != null && port != null) { String peerId = transport + ":" + ip + ":" + port; //$NON-NLS-1$ //$NON-NLS-2$ attrs.put(IPeer.ATTR_ID, peerId); attrs.put(IPeer.ATTR_IP_HOST, ip); entry.peer = new Peer(attrs); } else { error = new IOException("Invalid or incomplete peer attributes reported by value-add."); //$NON-NLS-1$ } } if (error == null) { Assert.isNotNull(entry.process); Assert.isNotNull(entry.peer); entries.put(id, entry); } // Stop the output reader thread launcher.getOutputReader().interrupt(); } else { error = new FileNotFoundException(NLS.bind(Messages.AbstractExternalValueAdd_error_invalidLocation, this.getId())); } IStatus status = Status.OK_STATUS; if (error != null) { status = new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), error.getLocalizedMessage(), error); } done.done(AbstractExternalValueAdd.this, status); }
diff --git a/com.mobilesorcery.sdk.builder.android/src/com/mobilesorcery/sdk/builder/android/AndroidPackager.java b/com.mobilesorcery.sdk.builder.android/src/com/mobilesorcery/sdk/builder/android/AndroidPackager.java index a200c38c..3f1ed136 100644 --- a/com.mobilesorcery.sdk.builder.android/src/com/mobilesorcery/sdk/builder/android/AndroidPackager.java +++ b/com.mobilesorcery.sdk.builder.android/src/com/mobilesorcery/sdk/builder/android/AndroidPackager.java @@ -1,187 +1,192 @@ /* Copyright (C) 2009 Mobile Sorcery AB This program is free software; you can redistribute it and/or modify it under the terms of the Eclipse Public License v1.0. 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 Eclipse Public License v1.0 for more details. You should have received a copy of the Eclipse Public License v1.0 along with this program. It is also available at http://www.eclipse.org/legal/epl-v10.html */ package com.mobilesorcery.sdk.builder.android; import com.mobilesorcery.sdk.internal.builder.MoSyncIconBuilderVisitor; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import com.mobilesorcery.sdk.core.AbstractPackager; import com.mobilesorcery.sdk.core.DefaultPackager; import com.mobilesorcery.sdk.core.IBuildResult; import com.mobilesorcery.sdk.core.MoSyncProject; import com.mobilesorcery.sdk.profiles.IProfile; /* Built on the JavaMe packager code */ public class AndroidPackager extends AbstractPackager { public void createPackage(MoSyncProject project, IProfile targetProfile, IBuildResult buildResult) throws CoreException { DefaultPackager internal = new DefaultPackager(project, targetProfile, isFinalizerBuild()); internal.setParameters(getParameters()); internal.setParameter("D", shouldUseDebugRuntimes() ? "D" : ""); try { File packageOutputDir = internal.resolveFile("%package-output-dir%"); packageOutputDir.mkdirs(); // Delete previous apk file if any File projectAPK = new File(internal.resolve("%package-output-dir%\\%project-name%.apk")); projectAPK.delete(); String fixedName = project.getName().replace(' ', '_'); // Create manifest file File manifest = new File(internal.resolve("%compile-output-dir%\\package\\AndroidManifest.xml")); createManifest(fixedName, manifest); // Create layout (main.xml) file File main_xml = new File(internal.resolve("%compile-output-dir%\\package\\res\\layout\\main.xml")); createMain(project.getName(), main_xml); // Create values (strings.xml) file, in this file the application name is written File strings_xml = new File(internal.resolve("%compile-output-dir%\\package\\res\\values\\strings.xml")); createStrings(project.getName(), strings_xml); File res = new File(internal.resolve("%package-output-dir%\\res\\raw\\resources")); res.getParentFile().mkdirs(); File icon = new File(internal.resolve("%package-output-dir%\\res\\drawable\\icon.png")); icon.getParentFile().mkdirs(); // Need to set execution dir, o/w commandline optiones doesn't understand what to do. internal.getExecutor().setExecutionDirectory(projectAPK.getParentFile().getParent()); - // Copy and rename the program and resource file to package/res/raw/ and add .zip ending to the resource file to prevent it from being compressed + // Copy and rename the program and resource file to package/res/raw/ internal.runCommandLine("cmd", "/c", "copy", "%compile-output-dir%\\program", "%package-output-dir%\\res\\raw\\program", "/y"); File resources = new File(internal.resolve("%compile-output-dir%\\resources")); if (resources.exists()) { internal.runCommandLine("cmd", "/c", "copy", "%compile-output-dir%\\resources", "%package-output-dir%\\res\\raw\\resources", "/y"); } + else + { + String dummyResource = "dummy"; + DefaultPackager.writeFile(res, dummyResource); + } // If there was an icon provided, add it, else use the default icon MoSyncIconBuilderVisitor visitor = new MoSyncIconBuilderVisitor(); visitor.setProject(project.getWrappedProject()); IResource[] iconFiles = visitor.getIconFiles(); if (iconFiles.length > 0) { Object xObj = targetProfile.getProperties().get("MA_PROF_CONST_ICONSIZE_X"); Object yObj = targetProfile.getProperties().get("MA_PROF_CONST_ICONSIZE_Y"); if (xObj != null && yObj != null) { String sizeStr = ((Long) xObj) + "x" + ((Long) yObj); internal.runCommandLine("%mosync-bin%\\icon-injector", "-src", iconFiles[0].getLocation().toOSString(), "-size", sizeStr, "-platform", "android", "-dst", "%package-output-dir%\\res\\drawable\\icon.png"); } } else // Copy default icon internal.runCommandLine("cmd", "/c", "copy", "%mosync-bin%\\..\\etc\\icon.png", "%package-output-dir%\\res\\drawable\\icon.png", "/y"); // build a resources.ap_ file using aapt tool internal.runCommandLine("%mosync-bin%\\android\\aapt", "package", "-f", "-M", manifest.getAbsolutePath(), "-F", "%package-output-dir%\\resources.ap_", "-I", "%mosync-bin%\\android\\android-1.5.jar", "-S", "%package-output-dir%\\res"); // unzip the correct class zip File classes = new File(internal.resolve("%package-output-dir%\\classes\\class")); classes.getParentFile().mkdirs(); internal.runCommandLine("%mosync-bin%\\unzip", "-q", "%runtime-dir%\\MoSyncRuntime%D%.zip","-d","%package-output-dir%\\classes"); // run dx on class file, generating a dex file internal.runCommandLine("java","-jar","%mosync-bin%\\android\\dx.jar","--dex","--patch-string","com/mosync/java/android","com/mosync/app_"+fixedName,"--output=%package-output-dir%\\classes.dex","%package-output-dir%\\classes"); // generate android package , add dex file and resources.ap_ using apkBuilder internal.runCommandLine("java", "-jar", "%mosync-bin%\\android\\apkbuilder.jar","%package-output-dir%\\%project-name%_unsigned.apk","-u","-z","%package-output-dir%\\resources.ap_","-f","%package-output-dir%\\classes.dex"); // sign apk file using jarSigner internal.runCommandLine("java","-jar","%mosync-bin%\\android\\tools-stripped.jar","-keystore","%mosync-bin%\\..\\etc\\mosync.keystore","-storepass","default","-signedjar","%package-output-dir%\\%project-name%.apk","%package-output-dir%\\%project-name%_unsigned.apk","mosync.keystore"); // Clean up! internal.runCommandLine("cmd", "/c", "rd","/s","/q","%package-output-dir%\\classes"); internal.runCommandLine("cmd", "/c", "rd","/s","/q","%package-output-dir%\\res"); internal.runCommandLine("cmd", "/c", "del","/q","%package-output-dir%\\classes.dex"); internal.runCommandLine("cmd", "/c", "del","/q","%package-output-dir%\\resources.ap_"); internal.runCommandLine("cmd", "/c", "del","/q","%compile-output-dir%\\package\\AndroidManifest.xml"); buildResult.setBuildResult(projectAPK); } catch ( Exception e ) { StringWriter s = new StringWriter( ); PrintWriter pr= new PrintWriter( s ); e.printStackTrace( pr ); // Return stack trace in case of error throw new CoreException( new Status( IStatus.ERROR, "com.mobilesorcery.builder.android", s.toString( ) )); } } private void createManifest(String projectName, File manifest) throws IOException { manifest.getParentFile().mkdirs(); String manifest_string = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +"<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +"\tpackage=\"com.mosync.app_"+projectName+"\"\n" +"\tandroid:versionCode=\"1\"\n" +"\tandroid:versionName=\"1.0\">\n" +"\t<application android:icon=\"@drawable/icon\" android:label=\"@string/app_name\">\n" +"\t\t<activity android:name=\".MoSync\"\n" +"\t\t\tandroid:label=\"@string/app_name\">\n" +"\t\t\t<intent-filter>\n" +"\t\t\t\t<action android:name=\"android.intent.action.MAIN\" />\n" +"\t\t\t\t<category android:name=\"android.intent.category.LAUNCHER\" />\n" +"\t\t\t</intent-filter>\n" +"\t\t</activity>\n" +"\t</application>\n" +"\t<uses-sdk android:minSdkVersion=\"3\" />\n" +"\t<uses-permission android:name=\"android.permission.VIBRATE\" />\n" +"\t<uses-permission android:name=\"android.permission.INTERNET\" />\n" +"</manifest>\n"; DefaultPackager.writeFile(manifest, manifest_string); } private void createMain(String projectName, File main_xml) throws IOException { main_xml.getParentFile().mkdirs(); String main_xml_string = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +"<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +"\tandroid:orientation=\"vertical\"\n" +"\tandroid:layout_width=\"fill_parent\"\n" +"\tandroid:layout_height=\"fill_parent\"\n" +">\n" +"</LinearLayout>\n"; DefaultPackager.writeFile(main_xml, main_xml_string); } private void createStrings(String projectName, File strings_xml) throws IOException { strings_xml.getParentFile().mkdirs(); String strings_xml_string = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +"<resources>\n" +"\t<string name=\"app_name\">"+projectName+"</string>\n" +"</resources>\n"; DefaultPackager.writeFile(strings_xml, strings_xml_string); } }
false
true
public void createPackage(MoSyncProject project, IProfile targetProfile, IBuildResult buildResult) throws CoreException { DefaultPackager internal = new DefaultPackager(project, targetProfile, isFinalizerBuild()); internal.setParameters(getParameters()); internal.setParameter("D", shouldUseDebugRuntimes() ? "D" : ""); try { File packageOutputDir = internal.resolveFile("%package-output-dir%"); packageOutputDir.mkdirs(); // Delete previous apk file if any File projectAPK = new File(internal.resolve("%package-output-dir%\\%project-name%.apk")); projectAPK.delete(); String fixedName = project.getName().replace(' ', '_'); // Create manifest file File manifest = new File(internal.resolve("%compile-output-dir%\\package\\AndroidManifest.xml")); createManifest(fixedName, manifest); // Create layout (main.xml) file File main_xml = new File(internal.resolve("%compile-output-dir%\\package\\res\\layout\\main.xml")); createMain(project.getName(), main_xml); // Create values (strings.xml) file, in this file the application name is written File strings_xml = new File(internal.resolve("%compile-output-dir%\\package\\res\\values\\strings.xml")); createStrings(project.getName(), strings_xml); File res = new File(internal.resolve("%package-output-dir%\\res\\raw\\resources")); res.getParentFile().mkdirs(); File icon = new File(internal.resolve("%package-output-dir%\\res\\drawable\\icon.png")); icon.getParentFile().mkdirs(); // Need to set execution dir, o/w commandline optiones doesn't understand what to do. internal.getExecutor().setExecutionDirectory(projectAPK.getParentFile().getParent()); // Copy and rename the program and resource file to package/res/raw/ and add .zip ending to the resource file to prevent it from being compressed internal.runCommandLine("cmd", "/c", "copy", "%compile-output-dir%\\program", "%package-output-dir%\\res\\raw\\program", "/y"); File resources = new File(internal.resolve("%compile-output-dir%\\resources")); if (resources.exists()) { internal.runCommandLine("cmd", "/c", "copy", "%compile-output-dir%\\resources", "%package-output-dir%\\res\\raw\\resources", "/y"); } // If there was an icon provided, add it, else use the default icon MoSyncIconBuilderVisitor visitor = new MoSyncIconBuilderVisitor(); visitor.setProject(project.getWrappedProject()); IResource[] iconFiles = visitor.getIconFiles(); if (iconFiles.length > 0) { Object xObj = targetProfile.getProperties().get("MA_PROF_CONST_ICONSIZE_X"); Object yObj = targetProfile.getProperties().get("MA_PROF_CONST_ICONSIZE_Y"); if (xObj != null && yObj != null) { String sizeStr = ((Long) xObj) + "x" + ((Long) yObj); internal.runCommandLine("%mosync-bin%\\icon-injector", "-src", iconFiles[0].getLocation().toOSString(), "-size", sizeStr, "-platform", "android", "-dst", "%package-output-dir%\\res\\drawable\\icon.png"); } } else // Copy default icon internal.runCommandLine("cmd", "/c", "copy", "%mosync-bin%\\..\\etc\\icon.png", "%package-output-dir%\\res\\drawable\\icon.png", "/y"); // build a resources.ap_ file using aapt tool internal.runCommandLine("%mosync-bin%\\android\\aapt", "package", "-f", "-M", manifest.getAbsolutePath(), "-F", "%package-output-dir%\\resources.ap_", "-I", "%mosync-bin%\\android\\android-1.5.jar", "-S", "%package-output-dir%\\res"); // unzip the correct class zip File classes = new File(internal.resolve("%package-output-dir%\\classes\\class")); classes.getParentFile().mkdirs(); internal.runCommandLine("%mosync-bin%\\unzip", "-q", "%runtime-dir%\\MoSyncRuntime%D%.zip","-d","%package-output-dir%\\classes"); // run dx on class file, generating a dex file internal.runCommandLine("java","-jar","%mosync-bin%\\android\\dx.jar","--dex","--patch-string","com/mosync/java/android","com/mosync/app_"+fixedName,"--output=%package-output-dir%\\classes.dex","%package-output-dir%\\classes"); // generate android package , add dex file and resources.ap_ using apkBuilder internal.runCommandLine("java", "-jar", "%mosync-bin%\\android\\apkbuilder.jar","%package-output-dir%\\%project-name%_unsigned.apk","-u","-z","%package-output-dir%\\resources.ap_","-f","%package-output-dir%\\classes.dex"); // sign apk file using jarSigner internal.runCommandLine("java","-jar","%mosync-bin%\\android\\tools-stripped.jar","-keystore","%mosync-bin%\\..\\etc\\mosync.keystore","-storepass","default","-signedjar","%package-output-dir%\\%project-name%.apk","%package-output-dir%\\%project-name%_unsigned.apk","mosync.keystore"); // Clean up! internal.runCommandLine("cmd", "/c", "rd","/s","/q","%package-output-dir%\\classes"); internal.runCommandLine("cmd", "/c", "rd","/s","/q","%package-output-dir%\\res"); internal.runCommandLine("cmd", "/c", "del","/q","%package-output-dir%\\classes.dex"); internal.runCommandLine("cmd", "/c", "del","/q","%package-output-dir%\\resources.ap_"); internal.runCommandLine("cmd", "/c", "del","/q","%compile-output-dir%\\package\\AndroidManifest.xml"); buildResult.setBuildResult(projectAPK); } catch ( Exception e ) { StringWriter s = new StringWriter( ); PrintWriter pr= new PrintWriter( s ); e.printStackTrace( pr ); // Return stack trace in case of error throw new CoreException( new Status( IStatus.ERROR, "com.mobilesorcery.builder.android", s.toString( ) )); } }
public void createPackage(MoSyncProject project, IProfile targetProfile, IBuildResult buildResult) throws CoreException { DefaultPackager internal = new DefaultPackager(project, targetProfile, isFinalizerBuild()); internal.setParameters(getParameters()); internal.setParameter("D", shouldUseDebugRuntimes() ? "D" : ""); try { File packageOutputDir = internal.resolveFile("%package-output-dir%"); packageOutputDir.mkdirs(); // Delete previous apk file if any File projectAPK = new File(internal.resolve("%package-output-dir%\\%project-name%.apk")); projectAPK.delete(); String fixedName = project.getName().replace(' ', '_'); // Create manifest file File manifest = new File(internal.resolve("%compile-output-dir%\\package\\AndroidManifest.xml")); createManifest(fixedName, manifest); // Create layout (main.xml) file File main_xml = new File(internal.resolve("%compile-output-dir%\\package\\res\\layout\\main.xml")); createMain(project.getName(), main_xml); // Create values (strings.xml) file, in this file the application name is written File strings_xml = new File(internal.resolve("%compile-output-dir%\\package\\res\\values\\strings.xml")); createStrings(project.getName(), strings_xml); File res = new File(internal.resolve("%package-output-dir%\\res\\raw\\resources")); res.getParentFile().mkdirs(); File icon = new File(internal.resolve("%package-output-dir%\\res\\drawable\\icon.png")); icon.getParentFile().mkdirs(); // Need to set execution dir, o/w commandline optiones doesn't understand what to do. internal.getExecutor().setExecutionDirectory(projectAPK.getParentFile().getParent()); // Copy and rename the program and resource file to package/res/raw/ internal.runCommandLine("cmd", "/c", "copy", "%compile-output-dir%\\program", "%package-output-dir%\\res\\raw\\program", "/y"); File resources = new File(internal.resolve("%compile-output-dir%\\resources")); if (resources.exists()) { internal.runCommandLine("cmd", "/c", "copy", "%compile-output-dir%\\resources", "%package-output-dir%\\res\\raw\\resources", "/y"); } else { String dummyResource = "dummy"; DefaultPackager.writeFile(res, dummyResource); } // If there was an icon provided, add it, else use the default icon MoSyncIconBuilderVisitor visitor = new MoSyncIconBuilderVisitor(); visitor.setProject(project.getWrappedProject()); IResource[] iconFiles = visitor.getIconFiles(); if (iconFiles.length > 0) { Object xObj = targetProfile.getProperties().get("MA_PROF_CONST_ICONSIZE_X"); Object yObj = targetProfile.getProperties().get("MA_PROF_CONST_ICONSIZE_Y"); if (xObj != null && yObj != null) { String sizeStr = ((Long) xObj) + "x" + ((Long) yObj); internal.runCommandLine("%mosync-bin%\\icon-injector", "-src", iconFiles[0].getLocation().toOSString(), "-size", sizeStr, "-platform", "android", "-dst", "%package-output-dir%\\res\\drawable\\icon.png"); } } else // Copy default icon internal.runCommandLine("cmd", "/c", "copy", "%mosync-bin%\\..\\etc\\icon.png", "%package-output-dir%\\res\\drawable\\icon.png", "/y"); // build a resources.ap_ file using aapt tool internal.runCommandLine("%mosync-bin%\\android\\aapt", "package", "-f", "-M", manifest.getAbsolutePath(), "-F", "%package-output-dir%\\resources.ap_", "-I", "%mosync-bin%\\android\\android-1.5.jar", "-S", "%package-output-dir%\\res"); // unzip the correct class zip File classes = new File(internal.resolve("%package-output-dir%\\classes\\class")); classes.getParentFile().mkdirs(); internal.runCommandLine("%mosync-bin%\\unzip", "-q", "%runtime-dir%\\MoSyncRuntime%D%.zip","-d","%package-output-dir%\\classes"); // run dx on class file, generating a dex file internal.runCommandLine("java","-jar","%mosync-bin%\\android\\dx.jar","--dex","--patch-string","com/mosync/java/android","com/mosync/app_"+fixedName,"--output=%package-output-dir%\\classes.dex","%package-output-dir%\\classes"); // generate android package , add dex file and resources.ap_ using apkBuilder internal.runCommandLine("java", "-jar", "%mosync-bin%\\android\\apkbuilder.jar","%package-output-dir%\\%project-name%_unsigned.apk","-u","-z","%package-output-dir%\\resources.ap_","-f","%package-output-dir%\\classes.dex"); // sign apk file using jarSigner internal.runCommandLine("java","-jar","%mosync-bin%\\android\\tools-stripped.jar","-keystore","%mosync-bin%\\..\\etc\\mosync.keystore","-storepass","default","-signedjar","%package-output-dir%\\%project-name%.apk","%package-output-dir%\\%project-name%_unsigned.apk","mosync.keystore"); // Clean up! internal.runCommandLine("cmd", "/c", "rd","/s","/q","%package-output-dir%\\classes"); internal.runCommandLine("cmd", "/c", "rd","/s","/q","%package-output-dir%\\res"); internal.runCommandLine("cmd", "/c", "del","/q","%package-output-dir%\\classes.dex"); internal.runCommandLine("cmd", "/c", "del","/q","%package-output-dir%\\resources.ap_"); internal.runCommandLine("cmd", "/c", "del","/q","%compile-output-dir%\\package\\AndroidManifest.xml"); buildResult.setBuildResult(projectAPK); } catch ( Exception e ) { StringWriter s = new StringWriter( ); PrintWriter pr= new PrintWriter( s ); e.printStackTrace( pr ); // Return stack trace in case of error throw new CoreException( new Status( IStatus.ERROR, "com.mobilesorcery.builder.android", s.toString( ) )); } }
diff --git a/src/com/hackerdude/apps/sqlide/wizards/NewServerWizard.java b/src/com/hackerdude/apps/sqlide/wizards/NewServerWizard.java index 459d296..49e3513 100644 --- a/src/com/hackerdude/apps/sqlide/wizards/NewServerWizard.java +++ b/src/com/hackerdude/apps/sqlide/wizards/NewServerWizard.java @@ -1,115 +1,115 @@ /** * Title: JSqlIde<p> * Description: A Java SQL Integrated Development Environment * <p> * Copyright: Copyright (c) David Martinez<p> * Company: <p> * @author David Martinez * @version 1.0 */ package com.hackerdude.apps.sqlide.wizards; import com.hackerdude.lib.ui.*; import java.util.HashMap; import com.hackerdude.apps.sqlide.*; import com.hackerdude.apps.sqlide.dataaccess.*; import java.awt.Dimension; import java.io.File; import javax.swing.JFrame; /** * This is a server Wizard used to create new servers. */ public class NewServerWizard extends Wizard { NewServerWizSelectServerType pageNewServer; ServerDetailsWizardPage pageServerDetails; SelectClassPathWizardPage pageSelectClassPath; ConnectionConfig databaseSpec; public NewServerWizard(JFrame owner, boolean modal) { super(owner, "New Server Profile", "This wizard will guide you step by step on how to add a server profile " +"to your configuration.", modal ); databaseSpec = ConnectionConfigFactory.createConnectionConfig(); pageNewServer = new NewServerWizSelectServerType(); pageServerDetails = new ServerDetailsWizardPage(); pageSelectClassPath = new SelectClassPathWizardPage(); pageServerDetails.setWizard(this); pageSelectClassPath.setWizard(this); pageNewServer.setWizard(this); pageNewServer.setDatabaseSpec(databaseSpec); - pageNewServer.cmbServerType.setSelectedIndex(0); +// pageNewServer.cmbServerType.setSelectedIndex(0); pageSelectClassPath.setDatabaseSpec(databaseSpec); WizardPage[] pages = new WizardPage[3]; pages[0] = pageSelectClassPath; pages[1] = pageNewServer; pages[2] = pageServerDetails; File defaultFile = new File(ConnectionConfig.DEFAULT_DBSPEC_FILENAME); if ( ! defaultFile.exists() ) { setFileName(ConnectionConfig.DEFAULT_DBSPEC_FILENAME); pageNewServer.setFileNameEnabled(false); } setPages(pages); } public ConnectionConfig getDBSpec() { return databaseSpec; } public void setFileName(String fileName) { pageNewServer.fFileName.setText(fileName); } public void setServerType(String serverType) { pageServerDetails.setServerType(serverType); } public void setJDBCURL(String URL) { pageNewServer.setURL(URL); } public void setClassName(String className) { pageNewServer.setClassName(className); } public void setProperties(HashMap properties) { pageServerDetails.setServerProperties(properties); } public void setServerTitle(String title) { pageNewServer.setServerTitle(title); } public void doneWizard() { /** @todo Resolve this correctly. fFileName is only a base filename. It no longer has a path or anything. */ String baseFileName = pageNewServer.fFileName.getText(); String fileName = ProgramConfig.getInstance().getUserProfilePath()+baseFileName+".db.xml"; databaseSpec.setFileName(fileName); databaseSpec.setJDBCURL(pageNewServer.fURL.getText()); databaseSpec.setPoliteName(pageNewServer.cmbServerType.getSelectedItem().toString()+" on "+pageNewServer.fHostName.getText()); databaseSpec.setDriverClassName(pageNewServer.fClassName.getText()); databaseSpec.setConnectionProperties(pageServerDetails.propertiesModel.getProperties()); databaseSpec.setDefaultCatalog(pageNewServer.fCatalogName.getText()); setVisible(false); } public String getFileName() { return pageNewServer.fFileName.getText(); } public static NewServerWizard showWizard(boolean modal) { NewServerWizard wiz = new NewServerWizard(SqlIdeApplication.getFrame(), modal); wiz.setEnabled(true); wiz.pack(); Dimension screen = wiz.getToolkit().getScreenSize(); wiz.setLocation( ( screen.getSize().width - wiz.getSize().width) / 2,(screen.getSize().height - wiz.getSize().height) / 2); wiz.show(); return wiz; } public static void main(String[] args) { showWizard(true); } }
true
true
public NewServerWizard(JFrame owner, boolean modal) { super(owner, "New Server Profile", "This wizard will guide you step by step on how to add a server profile " +"to your configuration.", modal ); databaseSpec = ConnectionConfigFactory.createConnectionConfig(); pageNewServer = new NewServerWizSelectServerType(); pageServerDetails = new ServerDetailsWizardPage(); pageSelectClassPath = new SelectClassPathWizardPage(); pageServerDetails.setWizard(this); pageSelectClassPath.setWizard(this); pageNewServer.setWizard(this); pageNewServer.setDatabaseSpec(databaseSpec); pageNewServer.cmbServerType.setSelectedIndex(0); pageSelectClassPath.setDatabaseSpec(databaseSpec); WizardPage[] pages = new WizardPage[3]; pages[0] = pageSelectClassPath; pages[1] = pageNewServer; pages[2] = pageServerDetails; File defaultFile = new File(ConnectionConfig.DEFAULT_DBSPEC_FILENAME); if ( ! defaultFile.exists() ) { setFileName(ConnectionConfig.DEFAULT_DBSPEC_FILENAME); pageNewServer.setFileNameEnabled(false); } setPages(pages); }
public NewServerWizard(JFrame owner, boolean modal) { super(owner, "New Server Profile", "This wizard will guide you step by step on how to add a server profile " +"to your configuration.", modal ); databaseSpec = ConnectionConfigFactory.createConnectionConfig(); pageNewServer = new NewServerWizSelectServerType(); pageServerDetails = new ServerDetailsWizardPage(); pageSelectClassPath = new SelectClassPathWizardPage(); pageServerDetails.setWizard(this); pageSelectClassPath.setWizard(this); pageNewServer.setWizard(this); pageNewServer.setDatabaseSpec(databaseSpec); // pageNewServer.cmbServerType.setSelectedIndex(0); pageSelectClassPath.setDatabaseSpec(databaseSpec); WizardPage[] pages = new WizardPage[3]; pages[0] = pageSelectClassPath; pages[1] = pageNewServer; pages[2] = pageServerDetails; File defaultFile = new File(ConnectionConfig.DEFAULT_DBSPEC_FILENAME); if ( ! defaultFile.exists() ) { setFileName(ConnectionConfig.DEFAULT_DBSPEC_FILENAME); pageNewServer.setFileNameEnabled(false); } setPages(pages); }
diff --git a/src/com/oasisfeng/android/util/SafeSharedPreferences.java b/src/com/oasisfeng/android/util/SafeSharedPreferences.java index 78c5455..db3b73c 100644 --- a/src/com/oasisfeng/android/util/SafeSharedPreferences.java +++ b/src/com/oasisfeng/android/util/SafeSharedPreferences.java @@ -1,40 +1,40 @@ package com.oasisfeng.android.util; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import android.content.SharedPreferences; /** * Guard against ClassCastException in getters of SharedPreferences, return default value if type mismatched. * * @author Oasis */ public class SafeSharedPreferences { public static SharedPreferences wrap(final SharedPreferences prefs) { if (Proxy.isProxyClass(prefs.getClass()) && Proxy.getInvocationHandler(prefs).getClass() == SafeWrapper.class) return prefs; return (SharedPreferences) Proxy.newProxyInstance(prefs.getClass().getClassLoader(), new Class<?>[] { SharedPreferences.class }, new SafeWrapper(prefs)); } private static class SafeWrapper implements InvocationHandler { public SafeWrapper(final SharedPreferences prefs) { mPrefs = prefs; } @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { - if (args.length == 2 && method.getName().startsWith("get")) { // getAll() is excluded by "args.length == 2" + if (args != null && args.length == 2 && method.getName().startsWith("get")) { // getAll() is excluded by "args.length == 2" try { return method.invoke(mPrefs, args); } catch (final ClassCastException e) { return args[1]; // default value } } else return method.invoke(mPrefs, args); } private final SharedPreferences mPrefs; } }
true
true
@Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { if (args.length == 2 && method.getName().startsWith("get")) { // getAll() is excluded by "args.length == 2" try { return method.invoke(mPrefs, args); } catch (final ClassCastException e) { return args[1]; // default value } } else return method.invoke(mPrefs, args);
@Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { if (args != null && args.length == 2 && method.getName().startsWith("get")) { // getAll() is excluded by "args.length == 2" try { return method.invoke(mPrefs, args); } catch (final ClassCastException e) { return args[1]; // default value } } else return method.invoke(mPrefs, args);
diff --git a/org.eclipse.swtbot.eclipse.finder.test/src/org/eclipse/swtbot/eclipse/finder/widgets/helpers/PackageExplorerView.java b/org.eclipse.swtbot.eclipse.finder.test/src/org/eclipse/swtbot/eclipse/finder/widgets/helpers/PackageExplorerView.java index 49549c9..70619fe 100644 --- a/org.eclipse.swtbot.eclipse.finder.test/src/org/eclipse/swtbot/eclipse/finder/widgets/helpers/PackageExplorerView.java +++ b/org.eclipse.swtbot.eclipse.finder.test/src/org/eclipse/swtbot/eclipse/finder/widgets/helpers/PackageExplorerView.java @@ -1,79 +1,79 @@ /******************************************************************************* * Copyright (c) 2008 Ketan Padegaonkar 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: * Ketan Padegaonkar - initial API and implementation *******************************************************************************/ package org.eclipse.swtbot.eclipse.finder.widgets.helpers; import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.widgetOfType; import org.eclipse.core.runtime.Platform; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Tree; import org.eclipse.swtbot.eclipse.finder.SWTEclipseBot; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView; import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException; import org.eclipse.swtbot.swt.finder.waits.Conditions; import org.eclipse.swtbot.swt.finder.widgets.SWTBotCheckBox; import org.eclipse.swtbot.swt.finder.widgets.SWTBotRadio; import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree; /** * Screen object that represents the operations that can be performed on the package explorer view. * * @author Ketan Padegaonkar &lt;KetanPadegaonkar [at] gmail [dot] com&gt; * @version $Id$ */ public class PackageExplorerView { private SWTEclipseBot bot = new SWTEclipseBot(); public void deleteProject(String projectName) throws Exception { SWTBotTree tree = tree(); tree.setFocus(); tree.select(projectName); bot.menu("Edit").menu("Delete").click(); String version = (String) Platform.getBundle("org.eclipse.core.runtime").getHeaders().get("Bundle-Version"); if (version.startsWith("3.3")) { SWTBotShell shell = bot.shell("Confirm Project Delete"); shell.activate(); Button button = (Button) bot.widget(widgetOfType(Button.class), shell.widget); new SWTBotRadio(button).click(); bot.button("Yes").click(); bot.waitUntil(Conditions.shellCloses(shell)); } - if (version.startsWith("3.4")) { + if (version.startsWith("3.4") || version.startsWith("3.5")) { SWTBotShell shell = bot.shell("Delete Resources"); shell.activate(); Button button = (Button) bot.widget(widgetOfType(Button.class), shell.widget); new SWTBotCheckBox(button).select(); bot.button("OK").click(); bot.waitUntil(Conditions.shellCloses(shell)); } } /** * @return * @throws WidgetNotFoundException */ private SWTBotTree tree() throws WidgetNotFoundException { SWTBotView view = view(); SWTBotTree tree = new SWTBotTree((Tree) bot.widget(widgetOfType(Tree.class), view.getWidget())); return tree; } /** * @return * @throws WidgetNotFoundException */ private SWTBotView view() throws WidgetNotFoundException { return bot.view("Package Explorer"); } }
true
true
public void deleteProject(String projectName) throws Exception { SWTBotTree tree = tree(); tree.setFocus(); tree.select(projectName); bot.menu("Edit").menu("Delete").click(); String version = (String) Platform.getBundle("org.eclipse.core.runtime").getHeaders().get("Bundle-Version"); if (version.startsWith("3.3")) { SWTBotShell shell = bot.shell("Confirm Project Delete"); shell.activate(); Button button = (Button) bot.widget(widgetOfType(Button.class), shell.widget); new SWTBotRadio(button).click(); bot.button("Yes").click(); bot.waitUntil(Conditions.shellCloses(shell)); } if (version.startsWith("3.4")) { SWTBotShell shell = bot.shell("Delete Resources"); shell.activate(); Button button = (Button) bot.widget(widgetOfType(Button.class), shell.widget); new SWTBotCheckBox(button).select(); bot.button("OK").click(); bot.waitUntil(Conditions.shellCloses(shell)); } }
public void deleteProject(String projectName) throws Exception { SWTBotTree tree = tree(); tree.setFocus(); tree.select(projectName); bot.menu("Edit").menu("Delete").click(); String version = (String) Platform.getBundle("org.eclipse.core.runtime").getHeaders().get("Bundle-Version"); if (version.startsWith("3.3")) { SWTBotShell shell = bot.shell("Confirm Project Delete"); shell.activate(); Button button = (Button) bot.widget(widgetOfType(Button.class), shell.widget); new SWTBotRadio(button).click(); bot.button("Yes").click(); bot.waitUntil(Conditions.shellCloses(shell)); } if (version.startsWith("3.4") || version.startsWith("3.5")) { SWTBotShell shell = bot.shell("Delete Resources"); shell.activate(); Button button = (Button) bot.widget(widgetOfType(Button.class), shell.widget); new SWTBotCheckBox(button).select(); bot.button("OK").click(); bot.waitUntil(Conditions.shellCloses(shell)); } }
diff --git a/src/net/java/sip/communicator/plugin/provisioning/ProvisioningActivator.java b/src/net/java/sip/communicator/plugin/provisioning/ProvisioningActivator.java index 970f9f284..dc94dca6d 100644 --- a/src/net/java/sip/communicator/plugin/provisioning/ProvisioningActivator.java +++ b/src/net/java/sip/communicator/plugin/provisioning/ProvisioningActivator.java @@ -1,785 +1,791 @@ /* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.plugin.provisioning; import java.io.*; import java.net.*; import java.util.*; import javax.swing.*; import net.java.sip.communicator.service.configuration.*; import net.java.sip.communicator.service.credentialsstorage.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.httputil.*; import net.java.sip.communicator.service.netaddr.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.provdisc.*; import net.java.sip.communicator.service.resources.*; import net.java.sip.communicator.util.*; import org.osgi.framework.*; /** * Activator the provisioning system. It will gather provisioning URL depending * on the configuration (DHCP, manual, ...), retrieve configuration file and * push properties to the <tt>ConfigurationService</tt>. */ public class ProvisioningActivator implements BundleActivator { /** * Logger of this class */ private static final Logger logger = Logger.getLogger(ProvisioningActivator.class); /** * The current BundleContext. */ private static BundleContext bundleContext = null; /** * Name of the provisioning URL in the configuration service. */ private static final String PROPERTY_PROVISIONING_URL = "net.java.sip.communicator.plugin.provisioning.URL"; /** * Name of the provisioning username in the configuration service * authentication). */ private static final String PROPERTY_PROVISIONING_USERNAME = "net.java.sip.communicator.plugin.provisioning.auth.USERNAME"; /** * Name of the provisioning password in the configuration service (HTTP * authentication). */ private static final String PROPERTY_PROVISIONING_PASSWORD = "net.java.sip.communicator.plugin.provisioning.auth"; /** * Name of the property that contains the provisioning method (i.e. DHCP, * DNS, manual, ...). */ private static final String PROVISIONING_METHOD_PROP = "net.java.sip.communicator.plugin.provisioning.METHOD"; /** * Name of the property that contains enforce prefix list (separated by * pipe) for the provisioning. The retrieved configuration properties will * be checked against these prefixes to avoid having incorrect content in * the configuration file (such as HTML content resulting of HTTP error). */ private static final String PROVISIONING_ALLOW_PREFIX_PROP = "provisioning.ALLOW_PREFIX"; /** * Name of the enforce prefix property. */ private static final String PROVISIONING_ENFORCE_PREFIX_PROP = "provisioning.ENFORCE_PREFIX"; /** * A reference to the ConfigurationService implementation instance that * is currently registered with the bundle context. */ private static ConfigurationService configurationService = null; /** * A reference to the CredentialsStorageService implementation instance * that is registered with the bundle context. */ private static CredentialsStorageService credentialsService = null; /** * A reference to the NetworkAddressManagerService implementation instance * that is registered with the bundle context. */ private static NetworkAddressManagerService netaddrService = null; /** * User credentials to access URL (protected by HTTP authentication and/or * by provisioning) if any. */ private static UserCredentials userCredentials = null; /** * The user interface service. */ private static UIService uiService; /** * The resource service. */ private static ResourceManagementService resourceService; /** * HTTP method to request a page. */ private String method = "POST"; /** * List of allowed configuration prefixes. */ private List<String> allowedPrefixes = new ArrayList<String>(); /** * Starts this bundle * * @param bundleContext BundleContext * @throws Exception if anything goes wrong during the start of the bundle */ public void start(BundleContext bundleContext) throws Exception { String url = null; if (logger.isDebugEnabled()) logger.debug("Provisioning discovery [STARTED]"); ProvisioningActivator.bundleContext = bundleContext; Dictionary<String, String> properties = new Hashtable<String, String>(); properties.put( ConfigurationForm.FORM_TYPE, ConfigurationForm.ADVANCED_TYPE); bundleContext.registerService( ConfigurationForm.class.getName(), new LazyConfigurationForm( "net.java.sip.communicator.plugin.provisioning.ProvisioningForm", getClass().getClassLoader(), "plugin.provisioning.PLUGIN_ICON", "plugin.provisioning.PROVISIONING", 2000, true), properties); String method = getConfigurationService().getString( PROVISIONING_METHOD_PROP); if(method == null || method.equals("NONE")) { return; } ServiceReference serviceReferences[] = bundleContext. getServiceReferences(ProvisioningDiscoveryService.class.getName(), null); /* search the provisioning discovery implementation that correspond to * the method name */ if(serviceReferences != null) { for(ServiceReference ref : serviceReferences) { ProvisioningDiscoveryService provdisc = (ProvisioningDiscoveryService)bundleContext.getService(ref); if(provdisc.getMethodName().equals(method)) { /* may block for sometime depending on the method used */ url = provdisc.discoverURL(); break; } } } if(url == null) { /* try to see if provisioning URL is stored in properties */ url = getConfigurationService().getString( PROPERTY_PROVISIONING_URL); } if(url != null) { File file = retrieveConfigurationFile(url); if(file != null) { updateConfiguration(file); /* store the provisioning URL in local configuration in case * the provisioning discovery failed (DHCP/DNS unavailable, ...) */ getConfigurationService().setProperty( PROPERTY_PROVISIONING_URL, url); } } if (logger.isDebugEnabled()) logger.debug("Provisioning discovery [REGISTERED]"); } /** * Stops this bundle * * @param bundleContext BundleContext * @throws Exception if anything goes wrong during the stop of the bundle */ public void stop(BundleContext bundleContext) throws Exception { ProvisioningActivator.bundleContext = null; if (logger.isDebugEnabled()) logger.debug("Provisioning discovery [STOPPED]"); } /** * Indicates if the provisioning has been enabled. * * @return <tt>true</tt> if the provisioning is enabled, <tt>false</tt> - * otherwise */ public static String getProvisioningMethod() { String provMethod = getConfigurationService().getString(PROVISIONING_METHOD_PROP); if (provMethod == null || provMethod.length() <= 0) { provMethod = getResourceService().getSettingsString( "plugin.provisioning.DEFAULT_PROVISIONING_METHOD"); if (provMethod != null && provMethod.length() > 0) setProvisioningMethod(provMethod); } return provMethod; } /** * Enables the provisioning with the given method. If the provisioningMethod * is null disables the provisioning. * * @param provisioningMethod the provisioning method */ public static void setProvisioningMethod(String provisioningMethod) { getConfigurationService().setProperty( PROVISIONING_METHOD_PROP, provisioningMethod); } /** * Returns the provisioning URI. * * @return the provisioning URI */ public static String getProvisioningUri() { return getConfigurationService().getString(PROPERTY_PROVISIONING_URL); } /** * Sets the provisioning URI. * * @param uri the provisioning URI to set */ public static void setProvisioningUri(String uri) { getConfigurationService().setProperty( PROPERTY_PROVISIONING_URL, uri); } /** * Returns the <tt>UIService</tt> obtained from the bundle context. * * @return the <tt>UIService</tt> obtained from the bundle context */ public static UIService getUIService() { if (uiService == null) { ServiceReference uiReference = bundleContext.getServiceReference(UIService.class.getName()); uiService = (UIService) bundleContext .getService(uiReference); } return uiService; } /** * Returns the <tt>ResourceManagementService</tt> obtained from the * bundle context. * * @return the <tt>ResourceManagementService</tt> obtained from the * bundle context */ public static ResourceManagementService getResourceService() { if (resourceService == null) { ServiceReference resourceReference = bundleContext.getServiceReference( ResourceManagementService.class.getName()); resourceService = (ResourceManagementService) bundleContext .getService(resourceReference); } return resourceService; } /** * Retrieve configuration file from provisioning URL. * This method is blocking until configuration file is retrieved from the * network or if an exception happen * * @param url provisioning URL * @return provisioning file downloaded */ private File retrieveConfigurationFile(String url) { File tmpFile = null; try { String arg = null; String args[] = null; final File temp = File.createTempFile("provisioning", ".properties"); tmpFile = temp; if(url.contains("?")) { /* do not handle URL of type http://domain/index.php? (no * parameters) */ if((url.indexOf('?') + 1) != url.length()) { arg = url.substring(url.indexOf('?') + 1); args = arg.split("&"); } url = url.substring(0, url.indexOf('?')); } URL u = new URL(url); InetAddress ipaddr = getNetworkAddressManagerService(). getLocalHost(InetAddress.getByName(u.getHost())); String[] paramNames = null; String[] paramValues = null; int usernameIx = -1; int passwordIx = -1; if(args != null && args.length > 0) { paramNames = new String[args.length]; paramValues = new String[args.length]; for(int i = 0; i < args.length; i++) { String s = args[i]; if(s.equals("username=$username") || + s.equals("username=${username}") || s.equals("username")) { paramNames[i] = "username"; paramValues[i] = ""; usernameIx = i; } else if(s.equals("password=$password") || + s.equals("password=${password}") || s.equals("password")) { paramNames[i] = "password"; paramValues[i] = ""; passwordIx = i; } else if(s.equals("osname=$osname") || + s.equals("osname=${osname}") || s.equals("osname")) { paramNames[i] = "osname"; paramValues[i] = System.getProperty("os.name"); } else if(s.equals("build=$build") || + s.equals("build=${build}") || s.equals("build")) { paramNames[i] = "build"; paramValues[i] = System.getProperty("sip-communicator.version"); } else if(s.equals("ipaddr=$ipaddr") || + s.equals("ipaddr=${ipaddr}") || s.equals("ipaddr")) { paramNames[i] = "ipaddr"; paramValues[i] = ipaddr.getHostAddress(); } else if(s.equals("hwaddr=$hwaddr") || + s.equals("hwaddr=${hwaddr}") || s.equals("hwaddr")) { paramNames[i] = "hwaddr"; if(ipaddr != null) { /* find the hardware address of the interface * that has this IP address */ Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while(en.hasMoreElements()) { NetworkInterface iface = en.nextElement(); Enumeration<InetAddress> enInet = iface.getInetAddresses(); while(enInet.hasMoreElements()) { InetAddress inet = enInet.nextElement(); if(inet.equals(ipaddr)) { byte hw[] = getNetworkAddressManagerService(). getHardwareAddress(iface); StringBuffer buf = new StringBuffer(); for(byte h : hw) { int hi = h >= 0 ? h : h + 256; String t = new String( (hi <= 0xf) ? "0" : ""); t += Integer.toHexString(hi); buf.append(t); buf.append(":"); } buf.deleteCharAt(buf.length() - 1); paramValues[i] = buf.toString(); break; } } } } } else { paramNames[i] = ""; paramValues[i] = ""; } } } HttpUtils.HTTPResponseResult res = HttpUtils.postForm( url, PROPERTY_PROVISIONING_USERNAME, PROPERTY_PROVISIONING_PASSWORD, paramNames, paramValues, usernameIx, passwordIx); // if there was an error in retrieving stop if(res == null) return null; InputStream in = res.getContent(); // Chain a ProgressMonitorInputStream to the // URLConnection's InputStream final ProgressMonitorInputStream pin = new ProgressMonitorInputStream(null, u.toString(), in); // Set the maximum value of the ProgressMonitor ProgressMonitor pm = pin.getProgressMonitor(); pm.setMaximum((int)res.getContentLength()); final BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(temp)); try { int read = -1; byte[] buff = new byte[1024]; while((read = pin.read(buff)) != -1) { bout.write(buff, 0, read); } pin.close(); bout.flush(); bout.close(); return temp; } catch (Exception e) { logger.error("Error saving", e); try { pin.close(); bout.close(); } catch (Exception e1) { } return null; } } catch (Exception e) { if (logger.isInfoEnabled()) logger.info("Error retrieving provisioning file!", e); tmpFile.delete(); return null; } } /** * Update configuration with properties retrieved from provisioning URL. * * @param file provisioning file */ private void updateConfiguration(final File file) { Properties fileProps = new OrderedProperties(); InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); fileProps.load(in); Iterator<Map.Entry<Object, Object> > it = fileProps.entrySet().iterator(); while(it.hasNext()) { Map.Entry<Object, Object> entry = it.next(); String key = (String)entry.getKey(); Object value = entry.getValue(); if(key.equals(PROVISIONING_ALLOW_PREFIX_PROP)) { String prefixes[] = ((String)value).split("\\|"); /* updates allowed prefixes list */ for(String s : prefixes) { allowedPrefixes.add(s); } continue; } else if(key.equals(PROVISIONING_ENFORCE_PREFIX_PROP)) { checkEnforcePrefix((String)value); continue; } /* check that properties is allowed */ if(!isPrefixAllowed(key)) { continue; } processProperty(key, value); } try { /* save and reload the "new" configuration */ getConfigurationService().storeConfiguration(); getConfigurationService().reloadConfiguration(); } catch(Exception e) { logger.error("Cannot reload configuration"); } } catch(IOException e) { logger.warn("Error during load of provisioning file"); } finally { try { in.close(); file.delete(); } catch(IOException e) { } } } /** * Check if a property name belongs to the allowed prefixes. * * @param key property key name * @return true if key is allowed, false otherwise */ private boolean isPrefixAllowed(String key) { if(allowedPrefixes.size() > 0) { for(String s : allowedPrefixes) { if(key.startsWith(s)) { return true; } } /* current property prefix is not allowed */ return false; } else { /* no allowed prefixes configured so key is valid by default */ return true; } } /** * Process a new property. If value equals "${null}", it means to remove the * property in the configuration service. If the key name end with * "PASSWORD", its value is encrypted through credentials storage service, * otherwise the property is added/updated in the configuration service. * * @param key property key name * @param value property value */ private void processProperty(String key, Object value) { if((value instanceof String) && ((String)value).equals("${null}")) { getConfigurationService().removeProperty(key); } else if(key.endsWith(".PASSWORD")) { /* password => credentials storage service */ getCredentialsStorageService().storePassword( key.substring(0, key.lastIndexOf(".")), (String)value); } else { getConfigurationService().setProperty(key, value); } } /** * Walk through all properties and make sure all properties keys match * a specific set of prefixes defined in configuration. * * @param enforcePrefix list of enforce prefix. */ private void checkEnforcePrefix(String enforcePrefix) { ConfigurationService config = getConfigurationService(); String prefixes[] = null; if(enforcePrefix == null) { return; } /* must escape the | character */ prefixes = enforcePrefix.split("\\|"); /* get all properties */ for (String key : config.getAllPropertyNames()) { boolean isValid = false; for(String k : prefixes) { if(key.startsWith(k)) { isValid = true; break; } } /* property name does is not in the enforce prefix list * so remove it */ if(!isValid) { config.removeProperty(key); } } } /** * Returns a reference to a ConfigurationService implementation currently * registered in the bundle context or null if no such implementation was * found. * * @return a currently valid implementation of the ConfigurationService. */ public static ConfigurationService getConfigurationService() { if (configurationService == null) { ServiceReference confReference = bundleContext.getServiceReference( ConfigurationService.class.getName()); configurationService = (ConfigurationService)bundleContext.getService(confReference); } return configurationService; } /** * Returns a reference to a CredentialsStorageService implementation * currently registered in the bundle context or null if no such * implementation was found. * * @return a currently valid implementation of the * CredentialsStorageService. */ public static CredentialsStorageService getCredentialsStorageService() { if (credentialsService == null) { ServiceReference credentialsReference = bundleContext.getServiceReference( CredentialsStorageService.class.getName()); credentialsService = (CredentialsStorageService) bundleContext .getService(credentialsReference); } return credentialsService; } /** * Returns a reference to a NetworkAddressManagerService implementation * currently registered in the bundle context or null if no such * implementation was found. * * @return a currently valid implementation of the * NetworkAddressManagerService. */ public static NetworkAddressManagerService getNetworkAddressManagerService() { if (netaddrService == null) { ServiceReference netaddrReference = bundleContext.getServiceReference( NetworkAddressManagerService.class.getName()); netaddrService = (NetworkAddressManagerService) bundleContext .getService(netaddrReference); } return netaddrService; } }
false
true
private File retrieveConfigurationFile(String url) { File tmpFile = null; try { String arg = null; String args[] = null; final File temp = File.createTempFile("provisioning", ".properties"); tmpFile = temp; if(url.contains("?")) { /* do not handle URL of type http://domain/index.php? (no * parameters) */ if((url.indexOf('?') + 1) != url.length()) { arg = url.substring(url.indexOf('?') + 1); args = arg.split("&"); } url = url.substring(0, url.indexOf('?')); } URL u = new URL(url); InetAddress ipaddr = getNetworkAddressManagerService(). getLocalHost(InetAddress.getByName(u.getHost())); String[] paramNames = null; String[] paramValues = null; int usernameIx = -1; int passwordIx = -1; if(args != null && args.length > 0) { paramNames = new String[args.length]; paramValues = new String[args.length]; for(int i = 0; i < args.length; i++) { String s = args[i]; if(s.equals("username=$username") || s.equals("username")) { paramNames[i] = "username"; paramValues[i] = ""; usernameIx = i; } else if(s.equals("password=$password") || s.equals("password")) { paramNames[i] = "password"; paramValues[i] = ""; passwordIx = i; } else if(s.equals("osname=$osname") || s.equals("osname")) { paramNames[i] = "osname"; paramValues[i] = System.getProperty("os.name"); } else if(s.equals("build=$build") || s.equals("build")) { paramNames[i] = "build"; paramValues[i] = System.getProperty("sip-communicator.version"); } else if(s.equals("ipaddr=$ipaddr") || s.equals("ipaddr")) { paramNames[i] = "ipaddr"; paramValues[i] = ipaddr.getHostAddress(); } else if(s.equals("hwaddr=$hwaddr") || s.equals("hwaddr")) { paramNames[i] = "hwaddr"; if(ipaddr != null) { /* find the hardware address of the interface * that has this IP address */ Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while(en.hasMoreElements()) { NetworkInterface iface = en.nextElement(); Enumeration<InetAddress> enInet = iface.getInetAddresses(); while(enInet.hasMoreElements()) { InetAddress inet = enInet.nextElement(); if(inet.equals(ipaddr)) { byte hw[] = getNetworkAddressManagerService(). getHardwareAddress(iface); StringBuffer buf = new StringBuffer(); for(byte h : hw) { int hi = h >= 0 ? h : h + 256; String t = new String( (hi <= 0xf) ? "0" : ""); t += Integer.toHexString(hi); buf.append(t); buf.append(":"); } buf.deleteCharAt(buf.length() - 1); paramValues[i] = buf.toString(); break; } } } } } else { paramNames[i] = ""; paramValues[i] = ""; } } } HttpUtils.HTTPResponseResult res = HttpUtils.postForm( url, PROPERTY_PROVISIONING_USERNAME, PROPERTY_PROVISIONING_PASSWORD, paramNames, paramValues, usernameIx, passwordIx); // if there was an error in retrieving stop if(res == null) return null; InputStream in = res.getContent(); // Chain a ProgressMonitorInputStream to the // URLConnection's InputStream final ProgressMonitorInputStream pin = new ProgressMonitorInputStream(null, u.toString(), in); // Set the maximum value of the ProgressMonitor ProgressMonitor pm = pin.getProgressMonitor(); pm.setMaximum((int)res.getContentLength()); final BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(temp)); try { int read = -1; byte[] buff = new byte[1024]; while((read = pin.read(buff)) != -1) { bout.write(buff, 0, read); } pin.close(); bout.flush(); bout.close(); return temp; } catch (Exception e) { logger.error("Error saving", e); try { pin.close(); bout.close(); } catch (Exception e1) { } return null; } } catch (Exception e) { if (logger.isInfoEnabled()) logger.info("Error retrieving provisioning file!", e); tmpFile.delete(); return null; } }
private File retrieveConfigurationFile(String url) { File tmpFile = null; try { String arg = null; String args[] = null; final File temp = File.createTempFile("provisioning", ".properties"); tmpFile = temp; if(url.contains("?")) { /* do not handle URL of type http://domain/index.php? (no * parameters) */ if((url.indexOf('?') + 1) != url.length()) { arg = url.substring(url.indexOf('?') + 1); args = arg.split("&"); } url = url.substring(0, url.indexOf('?')); } URL u = new URL(url); InetAddress ipaddr = getNetworkAddressManagerService(). getLocalHost(InetAddress.getByName(u.getHost())); String[] paramNames = null; String[] paramValues = null; int usernameIx = -1; int passwordIx = -1; if(args != null && args.length > 0) { paramNames = new String[args.length]; paramValues = new String[args.length]; for(int i = 0; i < args.length; i++) { String s = args[i]; if(s.equals("username=$username") || s.equals("username=${username}") || s.equals("username")) { paramNames[i] = "username"; paramValues[i] = ""; usernameIx = i; } else if(s.equals("password=$password") || s.equals("password=${password}") || s.equals("password")) { paramNames[i] = "password"; paramValues[i] = ""; passwordIx = i; } else if(s.equals("osname=$osname") || s.equals("osname=${osname}") || s.equals("osname")) { paramNames[i] = "osname"; paramValues[i] = System.getProperty("os.name"); } else if(s.equals("build=$build") || s.equals("build=${build}") || s.equals("build")) { paramNames[i] = "build"; paramValues[i] = System.getProperty("sip-communicator.version"); } else if(s.equals("ipaddr=$ipaddr") || s.equals("ipaddr=${ipaddr}") || s.equals("ipaddr")) { paramNames[i] = "ipaddr"; paramValues[i] = ipaddr.getHostAddress(); } else if(s.equals("hwaddr=$hwaddr") || s.equals("hwaddr=${hwaddr}") || s.equals("hwaddr")) { paramNames[i] = "hwaddr"; if(ipaddr != null) { /* find the hardware address of the interface * that has this IP address */ Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while(en.hasMoreElements()) { NetworkInterface iface = en.nextElement(); Enumeration<InetAddress> enInet = iface.getInetAddresses(); while(enInet.hasMoreElements()) { InetAddress inet = enInet.nextElement(); if(inet.equals(ipaddr)) { byte hw[] = getNetworkAddressManagerService(). getHardwareAddress(iface); StringBuffer buf = new StringBuffer(); for(byte h : hw) { int hi = h >= 0 ? h : h + 256; String t = new String( (hi <= 0xf) ? "0" : ""); t += Integer.toHexString(hi); buf.append(t); buf.append(":"); } buf.deleteCharAt(buf.length() - 1); paramValues[i] = buf.toString(); break; } } } } } else { paramNames[i] = ""; paramValues[i] = ""; } } } HttpUtils.HTTPResponseResult res = HttpUtils.postForm( url, PROPERTY_PROVISIONING_USERNAME, PROPERTY_PROVISIONING_PASSWORD, paramNames, paramValues, usernameIx, passwordIx); // if there was an error in retrieving stop if(res == null) return null; InputStream in = res.getContent(); // Chain a ProgressMonitorInputStream to the // URLConnection's InputStream final ProgressMonitorInputStream pin = new ProgressMonitorInputStream(null, u.toString(), in); // Set the maximum value of the ProgressMonitor ProgressMonitor pm = pin.getProgressMonitor(); pm.setMaximum((int)res.getContentLength()); final BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(temp)); try { int read = -1; byte[] buff = new byte[1024]; while((read = pin.read(buff)) != -1) { bout.write(buff, 0, read); } pin.close(); bout.flush(); bout.close(); return temp; } catch (Exception e) { logger.error("Error saving", e); try { pin.close(); bout.close(); } catch (Exception e1) { } return null; } } catch (Exception e) { if (logger.isInfoEnabled()) logger.info("Error retrieving provisioning file!", e); tmpFile.delete(); return null; } }
diff --git a/perun-core/src/main/java/cz/metacentrum/perun/core/blImpl/AuthzResolverBlImpl.java b/perun-core/src/main/java/cz/metacentrum/perun/core/blImpl/AuthzResolverBlImpl.java index 316f8f4e4..48cc84f97 100644 --- a/perun-core/src/main/java/cz/metacentrum/perun/core/blImpl/AuthzResolverBlImpl.java +++ b/perun-core/src/main/java/cz/metacentrum/perun/core/blImpl/AuthzResolverBlImpl.java @@ -1,755 +1,755 @@ package cz.metacentrum.perun.core.blImpl; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cz.metacentrum.perun.core.api.ActionType; import cz.metacentrum.perun.core.api.AttributeDefinition; import cz.metacentrum.perun.core.api.AttributesManager; import cz.metacentrum.perun.core.api.Facility; import cz.metacentrum.perun.core.api.Group; import cz.metacentrum.perun.core.api.Host; import cz.metacentrum.perun.core.api.Member; import cz.metacentrum.perun.core.api.PerunBean; import cz.metacentrum.perun.core.api.PerunPrincipal; import cz.metacentrum.perun.core.api.PerunSession; import cz.metacentrum.perun.core.api.Resource; import cz.metacentrum.perun.core.api.Role; import cz.metacentrum.perun.core.api.Service; import cz.metacentrum.perun.core.api.User; import cz.metacentrum.perun.core.api.Vo; import cz.metacentrum.perun.core.api.exceptions.ActionTypeNotExistsException; import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException; import cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException; import cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException; import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import cz.metacentrum.perun.core.api.exceptions.PerunException; import cz.metacentrum.perun.core.api.exceptions.UserNotExistsException; import cz.metacentrum.perun.core.api.exceptions.VoNotExistsException; import cz.metacentrum.perun.core.bl.AuthzResolverBl; import cz.metacentrum.perun.core.impl.AuthzRoles; import cz.metacentrum.perun.core.impl.Utils; import cz.metacentrum.perun.core.implApi.AuthzResolverImplApi; import java.util.Map; import java.util.Set; /** * Authorization resolver. It decides if the perunPrincipal has rights to do the provided operation. * * @author Michal Prochazka <[email protected]> * */ public class AuthzResolverBlImpl implements AuthzResolverBl { private final static Logger log = LoggerFactory.getLogger(AuthzResolverBlImpl.class); private static AuthzResolverImplApi authzResolverImpl; private static PerunBlImpl perunBlImpl; /** * Retrieves information about the perun principal (in which VOs the principal is admin, ...) * * @param sess perunSession * @throws InternalErrorException */ protected static void init(PerunSession sess) throws InternalErrorException { log.debug("Initializing AuthzResolver for [{}]", sess.getPerunPrincipal()); // Load list of perunAdmins from the configuration, split the list by the comma List<String> perunAdmins = new ArrayList<String>(Arrays.asList(Utils.getPropertyFromConfiguration("perun.admins").split("[ \t]*,[ \t]*"))); // Check if the PerunPrincipal is in a group of Perun Admins if (perunAdmins.contains(sess.getPerunPrincipal().getActor())) { sess.getPerunPrincipal().getRoles().putAuthzRole(Role.PERUNADMIN); sess.getPerunPrincipal().setAuthzInitialized(true); // We can quit, because perun admin has all privileges log.debug("AuthzResolver.init: Perun Admin {} loaded", sess.getPerunPrincipal().getActor()); return; } String perunRpcAdmin = Utils.getPropertyFromConfiguration("perun.rpc.principal"); if (sess.getPerunPrincipal().getActor().equals(perunRpcAdmin)) { sess.getPerunPrincipal().getRoles().putAuthzRole(Role.RPC); log.debug("AuthzResolver.init: Perun RPC {} loaded", perunRpcAdmin); } List<String> perunServiceAdmins = new ArrayList<String>(Arrays.asList(Utils.getPropertyFromConfiguration("perun.service.principals").split("[ \t]*,[ \t]*"))); if (perunServiceAdmins.contains(sess.getPerunPrincipal().getActor())) { sess.getPerunPrincipal().getRoles().putAuthzRole(Role.SERVICE); log.debug("AuthzResolver.init: Perun Service {} loaded", perunServiceAdmins); } List<String> perunEngineAdmins = new ArrayList<String>(Arrays.asList(Utils.getPropertyFromConfiguration("perun.engine.principals").split("[ \t]*,[ \t]*"))); if (perunEngineAdmins.contains(sess.getPerunPrincipal().getActor())) { sess.getPerunPrincipal().getRoles().putAuthzRole(Role.ENGINE); log.debug("AuthzResolver.init: Perun Engine {} loaded", perunEngineAdmins); } List<String> perunSynchronizers = new ArrayList<String>(Arrays.asList(Utils.getPropertyFromConfiguration("perun.synchronizer.principals").split("[ \t]*,[ \t]*"))); if (perunSynchronizers.contains(sess.getPerunPrincipal().getActor())) { sess.getPerunPrincipal().getRoles().putAuthzRole(Role.SYNCHRONIZER); log.debug("AuthzResolver.init: Perun Synchronizer {} loaded", perunSynchronizers); } List<String> perunNotifications = new ArrayList<String>(Arrays.asList(Utils.getPropertyFromConfiguration("perun.notification.principals").split("[ \t]*,[ \t]*"))); if (perunNotifications.contains(sess.getPerunPrincipal().getActor())) { sess.getPerunPrincipal().getRoles().putAuthzRole(Role.NOTIFICATIONS); //FIXME ted pridame i roli plneho admina sess.getPerunPrincipal().getRoles().putAuthzRole(Role.PERUNADMIN); log.debug("AuthzResolver.init: Perun Notifications {} loaded", perunNotifications); } List<String> perunRegistrars = new ArrayList<String>(Arrays.asList(Utils.getPropertyFromConfiguration("perun.registrar.principals").split("[ \t]*,[ \t]*"))); if (perunRegistrars.contains(sess.getPerunPrincipal().getActor())) { sess.getPerunPrincipal().getRoles().putAuthzRole(Role.REGISTRAR); //FIXME ted pridame i roli plneho admina sess.getPerunPrincipal().getRoles().putAuthzRole(Role.PERUNADMIN); log.debug("AuthzResolver.init: Perun Registrar {} loaded", perunRegistrars); } if (!sess.getPerunPrincipal().getRoles().isEmpty()) { // We have some of the service principal, so we can quit sess.getPerunPrincipal().setAuthzInitialized(true); return; } // Prepare first users rights on all subgroups of groups where user is GroupAdmin and add them to AuthzRoles of the user AuthzRoles authzRoles = addAllSubgroupsToAuthzRoles(sess, authzResolverImpl.getRoles(sess.getPerunPrincipal().getUser())); // Load all user's roles with all possible subgroups sess.getPerunPrincipal().setRoles(authzRoles); // Add self role for the user if (sess.getPerunPrincipal().getUser() != null) { sess.getPerunPrincipal().getRoles().putAuthzRole(Role.SELF, sess.getPerunPrincipal().getUser()); // Add service user role if (sess.getPerunPrincipal().getUser().isServiceUser()) { sess.getPerunPrincipal().getRoles().putAuthzRole(Role.SERVICEUSER); } } sess.getPerunPrincipal().setAuthzInitialized(true); log.debug("AuthzResolver: Complete PerunPrincipal: {}", sess.getPerunPrincipal()); } public static boolean isAuthorized(PerunSession sess, Role role, PerunBean complementaryObject) throws InternalErrorException { log.trace("Entering isAuthorized: sess='" + sess + "', role='" + role + "', complementaryObject='" + complementaryObject + "'"); Utils.notNull(sess, "sess"); // We need to load additional information about the principal if (!sess.getPerunPrincipal().isAuthzInitialized()) { init(sess); } // If the user has no roles, deny access if (sess.getPerunPrincipal().getRoles() == null) { return false; } // Perun admin can do anything if (sess.getPerunPrincipal().getRoles().hasRole(Role.PERUNADMIN)) { return true; } // If user doesn't have requested role, deny request if (!sess.getPerunPrincipal().getRoles().hasRole(role)) { return false; } // Check if the principal has the priviledge if (complementaryObject != null) { // Check various combinations of role and complementary objects if (role.equals(Role.VOADMIN) || role.equals(Role.VOOBSERVER)) { // VO admin (or VoObserver) and group, get vo id from group and check if the user is vo admin (or VoObserver) if (complementaryObject.getBeanName().equals(Group.class.getSimpleName())) { return sess.getPerunPrincipal().getRoles().hasRole(role, Vo.class.getSimpleName(), ((Group) complementaryObject).getVoId()); } // VO admin (or VoObserver) and resource, check if the user is vo admin (or VoObserver) if (complementaryObject.getBeanName().equals(Resource.class.getSimpleName())) { return sess.getPerunPrincipal().getRoles().hasRole(role, Vo.class.getSimpleName(), ((Resource) complementaryObject).getVoId()); } // VO admin (or VoObserver) and member, check if the member is from that VO if (complementaryObject.getBeanName().equals(Member.class.getSimpleName())) { return sess.getPerunPrincipal().getRoles().hasRole(role, Vo.class.getSimpleName(), ((Member) complementaryObject).getVoId()); } } else if (role.equals(Role.FACILITYADMIN)) { // Facility admin and resource, get facility id from resource and check if the user is facility admin if (complementaryObject.getBeanName().equals(Resource.class.getSimpleName())) { return sess.getPerunPrincipal().getRoles().hasRole(role, Facility.class.getSimpleName(), ((Resource) complementaryObject).getFacilityId()); } } else if (role.equals(Role.GROUPADMIN)) { // Group admin can see some of the date of the VO if (complementaryObject.getBeanName().equals(Vo.class.getSimpleName())) { return sess.getPerunPrincipal().getRoles().hasRole(role, Vo.class.getSimpleName(), ((Vo) complementaryObject).getId()); } } else if (role.equals(Role.SELF)) { // Check if the member belogs to the self role if (complementaryObject.getBeanName().equals(Member.class.getSimpleName())) { return sess.getPerunPrincipal().getRoles().hasRole(role, User.class.getSimpleName(), ((Member) complementaryObject).getUserId()); } } return sess.getPerunPrincipal().getRoles().hasRole(role, complementaryObject); } else { return true; } } public static boolean isAuthorizedForAttribute(PerunSession sess, ActionType actionType, AttributeDefinition attrDef, Object primaryHolder, Object secondaryHolder) throws InternalErrorException, AttributeNotExistsException, ActionTypeNotExistsException { log.trace("Entering isAuthorizedForAttribute: sess='" + sess + "', actiontType='" + actionType + "', attrDef='" + attrDef + "', primaryHolder='" + primaryHolder + "', secondaryHolder='" + secondaryHolder + "'"); Utils.notNull(sess, "sess"); Utils.notNull(actionType, "ActionType"); Utils.notNull(attrDef, "AttributeDefinition"); getPerunBlImpl().getAttributesManagerBl().checkActionTypeExists(sess, actionType); getPerunBlImpl().getAttributesManagerBl().checkAttributeExists(sess, attrDef); // We need to load additional information about the principal if (!sess.getPerunPrincipal().isAuthzInitialized()) { init(sess); } // If the user has no roles, deny access if (sess.getPerunPrincipal().getRoles() == null) { return false; } // Perun admin can do anything if (sess.getPerunPrincipal().getRoles().hasRole(Role.PERUNADMIN)) { return true; } // Engine and Service can read attributes if ((sess.getPerunPrincipal().getRoles().hasRole(Role.ENGINE) || sess.getPerunPrincipal().getRoles().hasRole(Role.SERVICE)) && actionType.equals(ActionType.READ)) { return true; } //If attrDef is type of entityless, return false (only perunAdmin can read and write to entityless) if(getPerunBlImpl().getAttributesManagerBl().isFromNamespace(sess, attrDef, AttributesManager.NS_ENTITYLESS_ATTR)) return false; //This method get all possible roles which can do action on attribute List<Role> roles = getRolesWhichCanWorkWithAttribute(sess, actionType, attrDef); //Now get information about primary and secondary holders to identify them! //All possible useful perunBeans Vo vo = null; Facility facility = null; Group group = null; Member member = null; User user = null; Host host = null; Resource resource = null; //Get object for primaryHolder if(primaryHolder != null) { if(primaryHolder instanceof Vo) vo = (Vo) primaryHolder; else if(primaryHolder instanceof Facility) facility = (Facility) primaryHolder; else if(primaryHolder instanceof Group) group = (Group) primaryHolder; else if(primaryHolder instanceof Member) member = (Member) primaryHolder; else if(primaryHolder instanceof User) user = (User) primaryHolder; else if(primaryHolder instanceof Host) host = (Host) primaryHolder; else if(primaryHolder instanceof Resource) resource = (Resource) primaryHolder; else { throw new InternalErrorException("There is unrecognized object in primaryHolder."); } } else { throw new InternalErrorException("Aiding attribtue must have perunBean which is not null."); } //Get object for secondaryHolder if(secondaryHolder != null) { if(secondaryHolder instanceof Vo) vo = (Vo) secondaryHolder; else if(secondaryHolder instanceof Facility) facility = (Facility) secondaryHolder; else if(secondaryHolder instanceof Group) group = (Group) secondaryHolder; else if(secondaryHolder instanceof Member) member = (Member) secondaryHolder; else if(secondaryHolder instanceof User) user = (User) secondaryHolder; else if(secondaryHolder instanceof Host) host = (Host) secondaryHolder; else if(secondaryHolder instanceof Resource) resource = (Resource) secondaryHolder; else { throw new InternalErrorException("There is unrecognized perunBean in secondaryHolder."); } } // If not, its ok, secondary holder can be null //Important: There is no options for other roles like service, serviceUser and other! try { if(resource != null && member != null) { if(roles.contains(Role.VOADMIN)) { List<Vo> vos = getPerunBlImpl().getVosManagerBl().getVosByPerunBean(sess, resource); for(Vo v: vos) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { List<Vo> vos = getPerunBlImpl().getVosManagerBl().getVosByPerunBean(sess, resource); for(Vo v: vos) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) { List<Group> groups = getPerunBlImpl().getGroupsManagerBl().getGroupsByPerunBean(sess, member); groups.retainAll(getPerunBlImpl().getGroupsManagerBl().getGroupsByPerunBean(sess, resource)); groups = new ArrayList<Group>(new HashSet<Group>(groups)); for(Group g: groups) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)) { Facility facilityFromResource = getPerunBlImpl().getResourcesManagerBl().getFacility(sess, resource); if(isAuthorized(sess, Role.FACILITYADMIN, facilityFromResource)) return true; } if(roles.contains(Role.SELF)) { if(getPerunBlImpl().getUsersManagerBl().getUserByMember(sess, member).equals(sess.getPerunPrincipal().getUser())) return true; } } else if(resource != null && group != null) { if(roles.contains(Role.VOADMIN)) { List<Vo> vos = getPerunBlImpl().getVosManagerBl().getVosByPerunBean(sess, resource); for(Vo v: vos) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { List<Vo> vos = getPerunBlImpl().getVosManagerBl().getVosByPerunBean(sess, resource); for(Vo v: vos) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) if(isAuthorized(sess, Role.GROUPADMIN, group)) return true; if(roles.contains(Role.FACILITYADMIN)) { //IMPORTANT "for now possible, but need to discuss" if(getPerunBlImpl().getResourcesManagerBl().getAssignedGroups(sess, resource).contains(group)) { List<Group> groups = getPerunBlImpl().getGroupsManagerBl().getGroupsByPerunBean(sess, resource); for(Group g: groups) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } } if(roles.contains(Role.SELF)); //Not Allowed } else if(user != null && facility != null) { if(roles.contains(Role.VOADMIN)) { List<Member> membersFromUser = getPerunBlImpl().getMembersManagerBl().getMembersByUser(sess, user); List<Resource> resourcesFromUser = new ArrayList<Resource>(); for(Member memberElement: membersFromUser) { resourcesFromUser.addAll(getPerunBlImpl().getResourcesManagerBl().getAssignedResources(sess, memberElement)); } resourcesFromUser = new ArrayList<Resource>(new HashSet<Resource>(resourcesFromUser)); resourcesFromUser.retainAll(getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility)); List<Vo> vos = new ArrayList<Vo>(); for(Resource resourceElement: resourcesFromUser) { vos.add(getPerunBlImpl().getResourcesManagerBl().getVo(sess, resourceElement)); } for(Vo v: vos) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { List<Member> membersFromUser = getPerunBlImpl().getMembersManagerBl().getMembersByUser(sess, user); List<Resource> resourcesFromUser = new ArrayList<Resource>(); for(Member memberElement: membersFromUser) { resourcesFromUser.addAll(getPerunBlImpl().getResourcesManagerBl().getAssignedResources(sess, memberElement)); } resourcesFromUser = new ArrayList<Resource>(new HashSet<Resource>(resourcesFromUser)); resourcesFromUser.retainAll(getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility)); List<Vo> vos = new ArrayList<Vo>(); for(Resource resourceElement: resourcesFromUser) { vos.add(getPerunBlImpl().getResourcesManagerBl().getVo(sess, resourceElement)); } for(Vo v: vos) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) { List<Member> membersFromUser = getPerunBlImpl().getMembersManagerBl().getMembersByUser(sess, user); List<Group> groupsFromUser = new ArrayList<Group>(); for(Member memberElement: membersFromUser) { groupsFromUser.addAll(getPerunBlImpl().getGroupsManagerBl().getAllMemberGroups(sess, memberElement)); } List<Resource> resourcesFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility); List<Group> groupsFromFacility = new ArrayList<Group>(); for(Resource resourceElement: resourcesFromFacility) { groupsFromFacility.addAll(getPerunBlImpl().getResourcesManagerBl().getAssignedGroups(sess, resourceElement)); } groupsFromUser.retainAll(groupsFromFacility); groupsFromUser = new ArrayList<Group>(new HashSet<Group>(groupsFromUser)); for(Group g: groupsFromUser) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)) if(isAuthorized(sess, Role.FACILITYADMIN, facility)) return true; if(roles.contains(Role.SELF)) if(isAuthorized(sess, Role.SELF, user)) return true; } else if(user != null) { if(roles.contains(Role.VOADMIN)) { //TEMPORARY, PROBABLY WILL BE FALSE List<Vo> vosFromUser = getPerunBlImpl().getUsersManagerBl().getVosWhereUserIsMember(sess, user); for(Vo v: vosFromUser) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { //TEMPORARY, PROBABLY WILL BE FALSE List<Vo> vosFromUser = getPerunBlImpl().getUsersManagerBl().getVosWhereUserIsMember(sess, user); for(Vo v: vosFromUser) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) { List<Member> membersFromUser = getPerunBlImpl().getMembersManagerBl().getMembersByUser(sess, user); List<Group> groupsFromUser = new ArrayList<Group>(); for(Member memberElement: membersFromUser) { groupsFromUser.addAll(getPerunBlImpl().getGroupsManagerBl().getAllMemberGroups(sess, memberElement)); } for(Group g: groupsFromUser) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)); //Not allowed if(roles.contains(Role.SELF)) if(isAuthorized(sess, Role.SELF, user)) return true; } else if(member != null) { if(roles.contains(Role.VOADMIN)) { Vo v = getPerunBlImpl().getMembersManagerBl().getMemberVo(sess, member); if(isAuthorized(sess, Role.VOADMIN, v)) return true; } if(roles.contains(Role.VOOBSERVER)) { Vo v = getPerunBlImpl().getMembersManagerBl().getMemberVo(sess, member); if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } if(roles.contains(Role.GROUPADMIN)) { List<Group> groupsFromMember = getPerunBlImpl().getGroupsManagerBl().getAllMemberGroups(sess, member); for(Group g: groupsFromMember) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)); //Not allowed if(roles.contains(Role.SELF)) { User u = getPerunBlImpl().getUsersManagerBl().getUserByMember(sess, member); - if(isAuthorized(sess, Role.SELF, user)) return true; + if(isAuthorized(sess, Role.SELF, u)) return true; } } else if(vo != null) { if(roles.contains(Role.VOADMIN)) { if(isAuthorized(sess, Role.VOADMIN, vo)) return true; } if(roles.contains(Role.VOOBSERVER)) { if(isAuthorized(sess, Role.VOOBSERVER, vo)) return true; } if(roles.contains(Role.GROUPADMIN)); //Not allowed if(roles.contains(Role.FACILITYADMIN)); //Not allowed if(roles.contains(Role.SELF)); //Not allowed } else if(group != null) { if(roles.contains(Role.VOADMIN)) { Vo v = getPerunBlImpl().getGroupsManagerBl().getVo(sess, group); if(isAuthorized(sess, Role.VOADMIN, v)) return true; } if(roles.contains(Role.VOOBSERVER)) { Vo v = getPerunBlImpl().getGroupsManagerBl().getVo(sess, group); if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } if(roles.contains(Role.GROUPADMIN)) if(isAuthorized(sess, Role.GROUPADMIN, group)) return true; if(roles.contains(Role.FACILITYADMIN)); //Not allowed if(roles.contains(Role.SELF)); //Not allowed } else if(resource != null) { if(roles.contains(Role.VOADMIN)) { Vo v = getPerunBlImpl().getResourcesManagerBl().getVo(sess, resource); if(isAuthorized(sess, Role.VOADMIN, v)) return true; } if(roles.contains(Role.VOOBSERVER)) { Vo v = getPerunBlImpl().getResourcesManagerBl().getVo(sess, resource); if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } if(roles.contains(Role.GROUPADMIN)); { List<Group> groupsFromResource = getPerunBlImpl().getResourcesManagerBl().getAssignedGroups(sess, resource); for(Group g: groupsFromResource) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)) { Facility f = getPerunBlImpl().getResourcesManagerBl().getFacility(sess, resource); if(isAuthorized(sess, Role.FACILITYADMIN, f)) return true; } if(roles.contains(Role.SELF)); //Not allowed } else if(facility != null) { if(roles.contains(Role.VOADMIN)) { List<Resource> resourcesFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility); List<Vo> vosFromResources = new ArrayList<Vo>(); for(Resource resourceElement: resourcesFromFacility) { vosFromResources.add(getPerunBlImpl().getResourcesManagerBl().getVo(sess, resourceElement)); } vosFromResources = new ArrayList<Vo>(new HashSet<Vo>(vosFromResources)); for(Vo v: vosFromResources) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { List<Resource> resourcesFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility); List<Vo> vosFromResources = new ArrayList<Vo>(); for(Resource resourceElement: resourcesFromFacility) { vosFromResources.add(getPerunBlImpl().getResourcesManagerBl().getVo(sess, resourceElement)); } vosFromResources = new ArrayList<Vo>(new HashSet<Vo>(vosFromResources)); for(Vo v: vosFromResources) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) { List<Resource> resourcesFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility); List<Group> groupsFromFacility = new ArrayList<Group>(); for(Resource resourceElement: resourcesFromFacility) { groupsFromFacility.addAll(getPerunBlImpl().getResourcesManagerBl().getAssignedGroups(sess, resourceElement)); } groupsFromFacility = new ArrayList<Group>(new HashSet<Group>(groupsFromFacility)); for(Group g: groupsFromFacility){ if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)) if(isAuthorized(sess, Role.FACILITYADMIN, facility)) return true; if(roles.contains(Role.SELF)) { List<User> usersFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAllowedUsers(sess, facility); if(usersFromFacility.contains(sess.getPerunPrincipal().getUser())) { return true; } } } else if(host != null) { if(roles.contains(Role.VOADMIN)); //Not allowed if(roles.contains(Role.VOOBSERVER)); //Not allowed if(roles.contains(Role.GROUPADMIN)); //Not allowed if(roles.contains(Role.FACILITYADMIN)) { Facility f = getPerunBlImpl().getFacilitiesManagerBl().getFacilityForHost(sess, host); if(isAuthorized(sess, Role.FACILITYADMIN, f)) return true; } if(roles.contains(Role.SELF)); //Not allowed } else { throw new InternalErrorException("There is no other possible variants for now!"); } } catch (VoNotExistsException ex) { throw new InternalErrorException(ex); } return false; } public static List<Role> getRolesWhichCanWorkWithAttribute(PerunSession sess, ActionType actionType, AttributeDefinition attrDef) throws InternalErrorException, AttributeNotExistsException, ActionTypeNotExistsException { getPerunBlImpl().getAttributesManagerBl().checkAttributeExists(sess, attrDef); getPerunBlImpl().getAttributesManagerBl().checkActionTypeExists(sess, actionType); return cz.metacentrum.perun.core.impl.AuthzResolverImpl.getRolesWhichCanWorkWithAttribute(sess, actionType, attrDef); } /** * Checks if the principal is authorized. * * @param sess perunSession * @param role required role * * @return true if the principal authorized, false otherwise * @throws InternalErrorException if something goes wrong */ public static boolean isAuthorized(PerunSession sess, Role role) throws InternalErrorException { return isAuthorized(sess, role, null); } /** * Returns true if the perunPrincipal has requested role. * * @param perunPrincipal * @param role role to be checked */ public static boolean hasRole(PerunPrincipal perunPrincipal, Role role) { return perunPrincipal.getRoles().hasRole(role); } public String toString() { return getClass().getSimpleName() + ":[]"; } public static boolean isVoAdmin(PerunSession sess) { return sess.getPerunPrincipal().getRoles().hasRole(Role.VOADMIN); } public static boolean isGroupAdmin(PerunSession sess) { return sess.getPerunPrincipal().getRoles().hasRole(Role.GROUPADMIN); } public static boolean isFacilityAdmin(PerunSession sess) { return sess.getPerunPrincipal().getRoles().hasRole(Role.FACILITYADMIN); } public static boolean isPerunAdmin(PerunSession sess) { return sess.getPerunPrincipal().getRoles().hasRole(Role.PERUNADMIN); } /* * Extracts only roles without complementary objects. */ public static List<String> getPrincipalRoleNames(PerunSession sess) throws InternalErrorException { // We need to load the principals roles if (!sess.getPerunPrincipal().isAuthzInitialized()) { init(sess); } return sess.getPerunPrincipal().getRoles().getRolesNames(); } public static User getLoggedUser(PerunSession sess) throws UserNotExistsException, InternalErrorException { // We need to load additional information about the principal if (!sess.getPerunPrincipal().isAuthzInitialized()) { init(sess); } return sess.getPerunPrincipal().getUser(); } public static PerunPrincipal getPerunPrincipal(PerunSession sess) throws InternalErrorException, UserNotExistsException { Utils.checkPerunSession(sess); if (!sess.getPerunPrincipal().isAuthzInitialized()) { init(sess); } return sess.getPerunPrincipal(); } /** * Returns all complementary objects for defined role. * * @param sess * @param role * @return list of complementary objects * @throws InternalErrorException */ public static List<PerunBean> getComplementaryObjectsForRole(PerunSession sess, Role role) throws InternalErrorException { return AuthzResolverBlImpl.getComplementaryObjectsForRole(sess, role, null); } /** * Returns only complementary objects for defined role wich fits perunBeanClass class. * * @param sess * @param role * @param PerunBean particular class (e.g. Vo, Group, ...) * @return list of complementary objects * @throws InternalErrorException */ public static List<PerunBean> getComplementaryObjectsForRole(PerunSession sess, Role role, Class perunBeanClass) throws InternalErrorException { Utils.checkPerunSession(sess); Utils.notNull(sess.getPerunPrincipal(), "sess.getPerunPrincipal()"); List<PerunBean> complementaryObjects = new ArrayList<PerunBean>(); try { if (sess.getPerunPrincipal().getRoles().get(role) != null) { for (String beanName : sess.getPerunPrincipal().getRoles().get(role).keySet()) { // Do we filter results on particular class? if (perunBeanClass == null || beanName.equals(perunBeanClass.getSimpleName())) { if (beanName.equals(Vo.class.getSimpleName())) { for (Integer beanId : sess.getPerunPrincipal().getRoles().get(role).get(beanName)) { complementaryObjects.add(perunBlImpl.getVosManagerBl().getVoById(sess, beanId)); } } if (beanName.equals(Group.class.getSimpleName())) { for (Integer beanId : sess.getPerunPrincipal().getRoles().get(role).get(beanName)) { complementaryObjects.add(perunBlImpl.getGroupsManagerBl().getGroupById(sess, beanId)); } } if (beanName.equals(Facility.class.getSimpleName())) { for (Integer beanId : sess.getPerunPrincipal().getRoles().get(role).get(beanName)) { complementaryObjects.add(perunBlImpl.getFacilitiesManagerBl().getFacilityById(sess, beanId)); } } if (beanName.equals(Resource.class.getSimpleName())) { for (Integer beanId : sess.getPerunPrincipal().getRoles().get(role).get(beanName)) { complementaryObjects.add(perunBlImpl.getResourcesManagerBl().getResourceById(sess, beanId)); } } if (beanName.equals(Service.class.getSimpleName())) { for (Integer beanId : sess.getPerunPrincipal().getRoles().get(role).get(beanName)) { complementaryObjects.add(perunBlImpl.getServicesManagerBl().getServiceById(sess, beanId)); } } } } } return complementaryObjects; } catch (PerunException e) { throw new InternalErrorException(e); } } public static void refreshAuthz(PerunSession sess) throws InternalErrorException { Utils.checkPerunSession(sess); if (sess.getPerunPrincipal().isAuthzInitialized()) { log.debug("Refreshing authz roles for session {}.", sess); sess.getPerunPrincipal().getRoles().clear(); sess.getPerunPrincipal().setAuthzInitialized(false); init(sess); } else { log.debug("Authz roles for session {} haven't been initialized yet, doing initialization.", sess); init(sess); } } /** * For role GroupAdmin with association to "Group" add also all subgroups to authzRoles. * If authzRoles is null, return empty AuthzRoles. * If there is no GroupAdmin role or Group object for this role, return not changed authzRoles. * * @param sess * @param authzRoles authzRoles for some user * @return authzRoles also with subgroups of groups * @throws InternalErrorException */ public static AuthzRoles addAllSubgroupsToAuthzRoles(PerunSession sess, AuthzRoles authzRoles) throws InternalErrorException { if(authzRoles == null) return new AuthzRoles(); if(authzRoles.hasRole(Role.GROUPADMIN)) { Map<String, Set<Integer>> groupAdminRoles = authzRoles.get(Role.GROUPADMIN); Set<Integer> groupsIds = groupAdminRoles.get("Group"); Set<Integer> newGroupsIds = new HashSet<Integer>(groupsIds); for(Integer id: groupsIds) { Group parentGroup; try { parentGroup = getPerunBlImpl().getGroupsManagerBl().getGroupById(sess, id); } catch (GroupNotExistsException ex) { log.debug("Group with id=" + id + " not exists when initializing rights for user: " + sess.getPerunPrincipal().getUser()); continue; } List<Group> subGroups = getPerunBlImpl().getGroupsManagerBl().getAllSubGroups(sess, parentGroup); for(Group g: subGroups) { newGroupsIds.add(g.getId()); } } groupAdminRoles.put("Group", newGroupsIds); authzRoles.put(Role.GROUPADMIN, groupAdminRoles); } return authzRoles; } // Filled by Spring public static AuthzResolverImplApi setAuthzResolverImpl(AuthzResolverImplApi authzResolverImpl) { AuthzResolverBlImpl.authzResolverImpl = authzResolverImpl; return authzResolverImpl; } //Filled by Spring public static PerunBlImpl setPerunBlImpl(PerunBlImpl perunBlImpl) { AuthzResolverBlImpl.perunBlImpl = perunBlImpl; return perunBlImpl; } public static PerunBlImpl getPerunBlImpl() { return perunBlImpl; } }
true
true
public static boolean isAuthorizedForAttribute(PerunSession sess, ActionType actionType, AttributeDefinition attrDef, Object primaryHolder, Object secondaryHolder) throws InternalErrorException, AttributeNotExistsException, ActionTypeNotExistsException { log.trace("Entering isAuthorizedForAttribute: sess='" + sess + "', actiontType='" + actionType + "', attrDef='" + attrDef + "', primaryHolder='" + primaryHolder + "', secondaryHolder='" + secondaryHolder + "'"); Utils.notNull(sess, "sess"); Utils.notNull(actionType, "ActionType"); Utils.notNull(attrDef, "AttributeDefinition"); getPerunBlImpl().getAttributesManagerBl().checkActionTypeExists(sess, actionType); getPerunBlImpl().getAttributesManagerBl().checkAttributeExists(sess, attrDef); // We need to load additional information about the principal if (!sess.getPerunPrincipal().isAuthzInitialized()) { init(sess); } // If the user has no roles, deny access if (sess.getPerunPrincipal().getRoles() == null) { return false; } // Perun admin can do anything if (sess.getPerunPrincipal().getRoles().hasRole(Role.PERUNADMIN)) { return true; } // Engine and Service can read attributes if ((sess.getPerunPrincipal().getRoles().hasRole(Role.ENGINE) || sess.getPerunPrincipal().getRoles().hasRole(Role.SERVICE)) && actionType.equals(ActionType.READ)) { return true; } //If attrDef is type of entityless, return false (only perunAdmin can read and write to entityless) if(getPerunBlImpl().getAttributesManagerBl().isFromNamespace(sess, attrDef, AttributesManager.NS_ENTITYLESS_ATTR)) return false; //This method get all possible roles which can do action on attribute List<Role> roles = getRolesWhichCanWorkWithAttribute(sess, actionType, attrDef); //Now get information about primary and secondary holders to identify them! //All possible useful perunBeans Vo vo = null; Facility facility = null; Group group = null; Member member = null; User user = null; Host host = null; Resource resource = null; //Get object for primaryHolder if(primaryHolder != null) { if(primaryHolder instanceof Vo) vo = (Vo) primaryHolder; else if(primaryHolder instanceof Facility) facility = (Facility) primaryHolder; else if(primaryHolder instanceof Group) group = (Group) primaryHolder; else if(primaryHolder instanceof Member) member = (Member) primaryHolder; else if(primaryHolder instanceof User) user = (User) primaryHolder; else if(primaryHolder instanceof Host) host = (Host) primaryHolder; else if(primaryHolder instanceof Resource) resource = (Resource) primaryHolder; else { throw new InternalErrorException("There is unrecognized object in primaryHolder."); } } else { throw new InternalErrorException("Aiding attribtue must have perunBean which is not null."); } //Get object for secondaryHolder if(secondaryHolder != null) { if(secondaryHolder instanceof Vo) vo = (Vo) secondaryHolder; else if(secondaryHolder instanceof Facility) facility = (Facility) secondaryHolder; else if(secondaryHolder instanceof Group) group = (Group) secondaryHolder; else if(secondaryHolder instanceof Member) member = (Member) secondaryHolder; else if(secondaryHolder instanceof User) user = (User) secondaryHolder; else if(secondaryHolder instanceof Host) host = (Host) secondaryHolder; else if(secondaryHolder instanceof Resource) resource = (Resource) secondaryHolder; else { throw new InternalErrorException("There is unrecognized perunBean in secondaryHolder."); } } // If not, its ok, secondary holder can be null //Important: There is no options for other roles like service, serviceUser and other! try { if(resource != null && member != null) { if(roles.contains(Role.VOADMIN)) { List<Vo> vos = getPerunBlImpl().getVosManagerBl().getVosByPerunBean(sess, resource); for(Vo v: vos) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { List<Vo> vos = getPerunBlImpl().getVosManagerBl().getVosByPerunBean(sess, resource); for(Vo v: vos) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) { List<Group> groups = getPerunBlImpl().getGroupsManagerBl().getGroupsByPerunBean(sess, member); groups.retainAll(getPerunBlImpl().getGroupsManagerBl().getGroupsByPerunBean(sess, resource)); groups = new ArrayList<Group>(new HashSet<Group>(groups)); for(Group g: groups) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)) { Facility facilityFromResource = getPerunBlImpl().getResourcesManagerBl().getFacility(sess, resource); if(isAuthorized(sess, Role.FACILITYADMIN, facilityFromResource)) return true; } if(roles.contains(Role.SELF)) { if(getPerunBlImpl().getUsersManagerBl().getUserByMember(sess, member).equals(sess.getPerunPrincipal().getUser())) return true; } } else if(resource != null && group != null) { if(roles.contains(Role.VOADMIN)) { List<Vo> vos = getPerunBlImpl().getVosManagerBl().getVosByPerunBean(sess, resource); for(Vo v: vos) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { List<Vo> vos = getPerunBlImpl().getVosManagerBl().getVosByPerunBean(sess, resource); for(Vo v: vos) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) if(isAuthorized(sess, Role.GROUPADMIN, group)) return true; if(roles.contains(Role.FACILITYADMIN)) { //IMPORTANT "for now possible, but need to discuss" if(getPerunBlImpl().getResourcesManagerBl().getAssignedGroups(sess, resource).contains(group)) { List<Group> groups = getPerunBlImpl().getGroupsManagerBl().getGroupsByPerunBean(sess, resource); for(Group g: groups) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } } if(roles.contains(Role.SELF)); //Not Allowed } else if(user != null && facility != null) { if(roles.contains(Role.VOADMIN)) { List<Member> membersFromUser = getPerunBlImpl().getMembersManagerBl().getMembersByUser(sess, user); List<Resource> resourcesFromUser = new ArrayList<Resource>(); for(Member memberElement: membersFromUser) { resourcesFromUser.addAll(getPerunBlImpl().getResourcesManagerBl().getAssignedResources(sess, memberElement)); } resourcesFromUser = new ArrayList<Resource>(new HashSet<Resource>(resourcesFromUser)); resourcesFromUser.retainAll(getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility)); List<Vo> vos = new ArrayList<Vo>(); for(Resource resourceElement: resourcesFromUser) { vos.add(getPerunBlImpl().getResourcesManagerBl().getVo(sess, resourceElement)); } for(Vo v: vos) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { List<Member> membersFromUser = getPerunBlImpl().getMembersManagerBl().getMembersByUser(sess, user); List<Resource> resourcesFromUser = new ArrayList<Resource>(); for(Member memberElement: membersFromUser) { resourcesFromUser.addAll(getPerunBlImpl().getResourcesManagerBl().getAssignedResources(sess, memberElement)); } resourcesFromUser = new ArrayList<Resource>(new HashSet<Resource>(resourcesFromUser)); resourcesFromUser.retainAll(getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility)); List<Vo> vos = new ArrayList<Vo>(); for(Resource resourceElement: resourcesFromUser) { vos.add(getPerunBlImpl().getResourcesManagerBl().getVo(sess, resourceElement)); } for(Vo v: vos) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) { List<Member> membersFromUser = getPerunBlImpl().getMembersManagerBl().getMembersByUser(sess, user); List<Group> groupsFromUser = new ArrayList<Group>(); for(Member memberElement: membersFromUser) { groupsFromUser.addAll(getPerunBlImpl().getGroupsManagerBl().getAllMemberGroups(sess, memberElement)); } List<Resource> resourcesFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility); List<Group> groupsFromFacility = new ArrayList<Group>(); for(Resource resourceElement: resourcesFromFacility) { groupsFromFacility.addAll(getPerunBlImpl().getResourcesManagerBl().getAssignedGroups(sess, resourceElement)); } groupsFromUser.retainAll(groupsFromFacility); groupsFromUser = new ArrayList<Group>(new HashSet<Group>(groupsFromUser)); for(Group g: groupsFromUser) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)) if(isAuthorized(sess, Role.FACILITYADMIN, facility)) return true; if(roles.contains(Role.SELF)) if(isAuthorized(sess, Role.SELF, user)) return true; } else if(user != null) { if(roles.contains(Role.VOADMIN)) { //TEMPORARY, PROBABLY WILL BE FALSE List<Vo> vosFromUser = getPerunBlImpl().getUsersManagerBl().getVosWhereUserIsMember(sess, user); for(Vo v: vosFromUser) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { //TEMPORARY, PROBABLY WILL BE FALSE List<Vo> vosFromUser = getPerunBlImpl().getUsersManagerBl().getVosWhereUserIsMember(sess, user); for(Vo v: vosFromUser) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) { List<Member> membersFromUser = getPerunBlImpl().getMembersManagerBl().getMembersByUser(sess, user); List<Group> groupsFromUser = new ArrayList<Group>(); for(Member memberElement: membersFromUser) { groupsFromUser.addAll(getPerunBlImpl().getGroupsManagerBl().getAllMemberGroups(sess, memberElement)); } for(Group g: groupsFromUser) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)); //Not allowed if(roles.contains(Role.SELF)) if(isAuthorized(sess, Role.SELF, user)) return true; } else if(member != null) { if(roles.contains(Role.VOADMIN)) { Vo v = getPerunBlImpl().getMembersManagerBl().getMemberVo(sess, member); if(isAuthorized(sess, Role.VOADMIN, v)) return true; } if(roles.contains(Role.VOOBSERVER)) { Vo v = getPerunBlImpl().getMembersManagerBl().getMemberVo(sess, member); if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } if(roles.contains(Role.GROUPADMIN)) { List<Group> groupsFromMember = getPerunBlImpl().getGroupsManagerBl().getAllMemberGroups(sess, member); for(Group g: groupsFromMember) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)); //Not allowed if(roles.contains(Role.SELF)) { User u = getPerunBlImpl().getUsersManagerBl().getUserByMember(sess, member); if(isAuthorized(sess, Role.SELF, user)) return true; } } else if(vo != null) { if(roles.contains(Role.VOADMIN)) { if(isAuthorized(sess, Role.VOADMIN, vo)) return true; } if(roles.contains(Role.VOOBSERVER)) { if(isAuthorized(sess, Role.VOOBSERVER, vo)) return true; } if(roles.contains(Role.GROUPADMIN)); //Not allowed if(roles.contains(Role.FACILITYADMIN)); //Not allowed if(roles.contains(Role.SELF)); //Not allowed } else if(group != null) { if(roles.contains(Role.VOADMIN)) { Vo v = getPerunBlImpl().getGroupsManagerBl().getVo(sess, group); if(isAuthorized(sess, Role.VOADMIN, v)) return true; } if(roles.contains(Role.VOOBSERVER)) { Vo v = getPerunBlImpl().getGroupsManagerBl().getVo(sess, group); if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } if(roles.contains(Role.GROUPADMIN)) if(isAuthorized(sess, Role.GROUPADMIN, group)) return true; if(roles.contains(Role.FACILITYADMIN)); //Not allowed if(roles.contains(Role.SELF)); //Not allowed } else if(resource != null) { if(roles.contains(Role.VOADMIN)) { Vo v = getPerunBlImpl().getResourcesManagerBl().getVo(sess, resource); if(isAuthorized(sess, Role.VOADMIN, v)) return true; } if(roles.contains(Role.VOOBSERVER)) { Vo v = getPerunBlImpl().getResourcesManagerBl().getVo(sess, resource); if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } if(roles.contains(Role.GROUPADMIN)); { List<Group> groupsFromResource = getPerunBlImpl().getResourcesManagerBl().getAssignedGroups(sess, resource); for(Group g: groupsFromResource) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)) { Facility f = getPerunBlImpl().getResourcesManagerBl().getFacility(sess, resource); if(isAuthorized(sess, Role.FACILITYADMIN, f)) return true; } if(roles.contains(Role.SELF)); //Not allowed } else if(facility != null) { if(roles.contains(Role.VOADMIN)) { List<Resource> resourcesFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility); List<Vo> vosFromResources = new ArrayList<Vo>(); for(Resource resourceElement: resourcesFromFacility) { vosFromResources.add(getPerunBlImpl().getResourcesManagerBl().getVo(sess, resourceElement)); } vosFromResources = new ArrayList<Vo>(new HashSet<Vo>(vosFromResources)); for(Vo v: vosFromResources) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { List<Resource> resourcesFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility); List<Vo> vosFromResources = new ArrayList<Vo>(); for(Resource resourceElement: resourcesFromFacility) { vosFromResources.add(getPerunBlImpl().getResourcesManagerBl().getVo(sess, resourceElement)); } vosFromResources = new ArrayList<Vo>(new HashSet<Vo>(vosFromResources)); for(Vo v: vosFromResources) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) { List<Resource> resourcesFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility); List<Group> groupsFromFacility = new ArrayList<Group>(); for(Resource resourceElement: resourcesFromFacility) { groupsFromFacility.addAll(getPerunBlImpl().getResourcesManagerBl().getAssignedGroups(sess, resourceElement)); } groupsFromFacility = new ArrayList<Group>(new HashSet<Group>(groupsFromFacility)); for(Group g: groupsFromFacility){ if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)) if(isAuthorized(sess, Role.FACILITYADMIN, facility)) return true; if(roles.contains(Role.SELF)) { List<User> usersFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAllowedUsers(sess, facility); if(usersFromFacility.contains(sess.getPerunPrincipal().getUser())) { return true; } } } else if(host != null) { if(roles.contains(Role.VOADMIN)); //Not allowed if(roles.contains(Role.VOOBSERVER)); //Not allowed if(roles.contains(Role.GROUPADMIN)); //Not allowed if(roles.contains(Role.FACILITYADMIN)) { Facility f = getPerunBlImpl().getFacilitiesManagerBl().getFacilityForHost(sess, host); if(isAuthorized(sess, Role.FACILITYADMIN, f)) return true; } if(roles.contains(Role.SELF)); //Not allowed } else { throw new InternalErrorException("There is no other possible variants for now!"); } } catch (VoNotExistsException ex) { throw new InternalErrorException(ex); } return false; }
public static boolean isAuthorizedForAttribute(PerunSession sess, ActionType actionType, AttributeDefinition attrDef, Object primaryHolder, Object secondaryHolder) throws InternalErrorException, AttributeNotExistsException, ActionTypeNotExistsException { log.trace("Entering isAuthorizedForAttribute: sess='" + sess + "', actiontType='" + actionType + "', attrDef='" + attrDef + "', primaryHolder='" + primaryHolder + "', secondaryHolder='" + secondaryHolder + "'"); Utils.notNull(sess, "sess"); Utils.notNull(actionType, "ActionType"); Utils.notNull(attrDef, "AttributeDefinition"); getPerunBlImpl().getAttributesManagerBl().checkActionTypeExists(sess, actionType); getPerunBlImpl().getAttributesManagerBl().checkAttributeExists(sess, attrDef); // We need to load additional information about the principal if (!sess.getPerunPrincipal().isAuthzInitialized()) { init(sess); } // If the user has no roles, deny access if (sess.getPerunPrincipal().getRoles() == null) { return false; } // Perun admin can do anything if (sess.getPerunPrincipal().getRoles().hasRole(Role.PERUNADMIN)) { return true; } // Engine and Service can read attributes if ((sess.getPerunPrincipal().getRoles().hasRole(Role.ENGINE) || sess.getPerunPrincipal().getRoles().hasRole(Role.SERVICE)) && actionType.equals(ActionType.READ)) { return true; } //If attrDef is type of entityless, return false (only perunAdmin can read and write to entityless) if(getPerunBlImpl().getAttributesManagerBl().isFromNamespace(sess, attrDef, AttributesManager.NS_ENTITYLESS_ATTR)) return false; //This method get all possible roles which can do action on attribute List<Role> roles = getRolesWhichCanWorkWithAttribute(sess, actionType, attrDef); //Now get information about primary and secondary holders to identify them! //All possible useful perunBeans Vo vo = null; Facility facility = null; Group group = null; Member member = null; User user = null; Host host = null; Resource resource = null; //Get object for primaryHolder if(primaryHolder != null) { if(primaryHolder instanceof Vo) vo = (Vo) primaryHolder; else if(primaryHolder instanceof Facility) facility = (Facility) primaryHolder; else if(primaryHolder instanceof Group) group = (Group) primaryHolder; else if(primaryHolder instanceof Member) member = (Member) primaryHolder; else if(primaryHolder instanceof User) user = (User) primaryHolder; else if(primaryHolder instanceof Host) host = (Host) primaryHolder; else if(primaryHolder instanceof Resource) resource = (Resource) primaryHolder; else { throw new InternalErrorException("There is unrecognized object in primaryHolder."); } } else { throw new InternalErrorException("Aiding attribtue must have perunBean which is not null."); } //Get object for secondaryHolder if(secondaryHolder != null) { if(secondaryHolder instanceof Vo) vo = (Vo) secondaryHolder; else if(secondaryHolder instanceof Facility) facility = (Facility) secondaryHolder; else if(secondaryHolder instanceof Group) group = (Group) secondaryHolder; else if(secondaryHolder instanceof Member) member = (Member) secondaryHolder; else if(secondaryHolder instanceof User) user = (User) secondaryHolder; else if(secondaryHolder instanceof Host) host = (Host) secondaryHolder; else if(secondaryHolder instanceof Resource) resource = (Resource) secondaryHolder; else { throw new InternalErrorException("There is unrecognized perunBean in secondaryHolder."); } } // If not, its ok, secondary holder can be null //Important: There is no options for other roles like service, serviceUser and other! try { if(resource != null && member != null) { if(roles.contains(Role.VOADMIN)) { List<Vo> vos = getPerunBlImpl().getVosManagerBl().getVosByPerunBean(sess, resource); for(Vo v: vos) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { List<Vo> vos = getPerunBlImpl().getVosManagerBl().getVosByPerunBean(sess, resource); for(Vo v: vos) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) { List<Group> groups = getPerunBlImpl().getGroupsManagerBl().getGroupsByPerunBean(sess, member); groups.retainAll(getPerunBlImpl().getGroupsManagerBl().getGroupsByPerunBean(sess, resource)); groups = new ArrayList<Group>(new HashSet<Group>(groups)); for(Group g: groups) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)) { Facility facilityFromResource = getPerunBlImpl().getResourcesManagerBl().getFacility(sess, resource); if(isAuthorized(sess, Role.FACILITYADMIN, facilityFromResource)) return true; } if(roles.contains(Role.SELF)) { if(getPerunBlImpl().getUsersManagerBl().getUserByMember(sess, member).equals(sess.getPerunPrincipal().getUser())) return true; } } else if(resource != null && group != null) { if(roles.contains(Role.VOADMIN)) { List<Vo> vos = getPerunBlImpl().getVosManagerBl().getVosByPerunBean(sess, resource); for(Vo v: vos) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { List<Vo> vos = getPerunBlImpl().getVosManagerBl().getVosByPerunBean(sess, resource); for(Vo v: vos) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) if(isAuthorized(sess, Role.GROUPADMIN, group)) return true; if(roles.contains(Role.FACILITYADMIN)) { //IMPORTANT "for now possible, but need to discuss" if(getPerunBlImpl().getResourcesManagerBl().getAssignedGroups(sess, resource).contains(group)) { List<Group> groups = getPerunBlImpl().getGroupsManagerBl().getGroupsByPerunBean(sess, resource); for(Group g: groups) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } } if(roles.contains(Role.SELF)); //Not Allowed } else if(user != null && facility != null) { if(roles.contains(Role.VOADMIN)) { List<Member> membersFromUser = getPerunBlImpl().getMembersManagerBl().getMembersByUser(sess, user); List<Resource> resourcesFromUser = new ArrayList<Resource>(); for(Member memberElement: membersFromUser) { resourcesFromUser.addAll(getPerunBlImpl().getResourcesManagerBl().getAssignedResources(sess, memberElement)); } resourcesFromUser = new ArrayList<Resource>(new HashSet<Resource>(resourcesFromUser)); resourcesFromUser.retainAll(getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility)); List<Vo> vos = new ArrayList<Vo>(); for(Resource resourceElement: resourcesFromUser) { vos.add(getPerunBlImpl().getResourcesManagerBl().getVo(sess, resourceElement)); } for(Vo v: vos) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { List<Member> membersFromUser = getPerunBlImpl().getMembersManagerBl().getMembersByUser(sess, user); List<Resource> resourcesFromUser = new ArrayList<Resource>(); for(Member memberElement: membersFromUser) { resourcesFromUser.addAll(getPerunBlImpl().getResourcesManagerBl().getAssignedResources(sess, memberElement)); } resourcesFromUser = new ArrayList<Resource>(new HashSet<Resource>(resourcesFromUser)); resourcesFromUser.retainAll(getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility)); List<Vo> vos = new ArrayList<Vo>(); for(Resource resourceElement: resourcesFromUser) { vos.add(getPerunBlImpl().getResourcesManagerBl().getVo(sess, resourceElement)); } for(Vo v: vos) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) { List<Member> membersFromUser = getPerunBlImpl().getMembersManagerBl().getMembersByUser(sess, user); List<Group> groupsFromUser = new ArrayList<Group>(); for(Member memberElement: membersFromUser) { groupsFromUser.addAll(getPerunBlImpl().getGroupsManagerBl().getAllMemberGroups(sess, memberElement)); } List<Resource> resourcesFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility); List<Group> groupsFromFacility = new ArrayList<Group>(); for(Resource resourceElement: resourcesFromFacility) { groupsFromFacility.addAll(getPerunBlImpl().getResourcesManagerBl().getAssignedGroups(sess, resourceElement)); } groupsFromUser.retainAll(groupsFromFacility); groupsFromUser = new ArrayList<Group>(new HashSet<Group>(groupsFromUser)); for(Group g: groupsFromUser) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)) if(isAuthorized(sess, Role.FACILITYADMIN, facility)) return true; if(roles.contains(Role.SELF)) if(isAuthorized(sess, Role.SELF, user)) return true; } else if(user != null) { if(roles.contains(Role.VOADMIN)) { //TEMPORARY, PROBABLY WILL BE FALSE List<Vo> vosFromUser = getPerunBlImpl().getUsersManagerBl().getVosWhereUserIsMember(sess, user); for(Vo v: vosFromUser) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { //TEMPORARY, PROBABLY WILL BE FALSE List<Vo> vosFromUser = getPerunBlImpl().getUsersManagerBl().getVosWhereUserIsMember(sess, user); for(Vo v: vosFromUser) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) { List<Member> membersFromUser = getPerunBlImpl().getMembersManagerBl().getMembersByUser(sess, user); List<Group> groupsFromUser = new ArrayList<Group>(); for(Member memberElement: membersFromUser) { groupsFromUser.addAll(getPerunBlImpl().getGroupsManagerBl().getAllMemberGroups(sess, memberElement)); } for(Group g: groupsFromUser) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)); //Not allowed if(roles.contains(Role.SELF)) if(isAuthorized(sess, Role.SELF, user)) return true; } else if(member != null) { if(roles.contains(Role.VOADMIN)) { Vo v = getPerunBlImpl().getMembersManagerBl().getMemberVo(sess, member); if(isAuthorized(sess, Role.VOADMIN, v)) return true; } if(roles.contains(Role.VOOBSERVER)) { Vo v = getPerunBlImpl().getMembersManagerBl().getMemberVo(sess, member); if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } if(roles.contains(Role.GROUPADMIN)) { List<Group> groupsFromMember = getPerunBlImpl().getGroupsManagerBl().getAllMemberGroups(sess, member); for(Group g: groupsFromMember) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)); //Not allowed if(roles.contains(Role.SELF)) { User u = getPerunBlImpl().getUsersManagerBl().getUserByMember(sess, member); if(isAuthorized(sess, Role.SELF, u)) return true; } } else if(vo != null) { if(roles.contains(Role.VOADMIN)) { if(isAuthorized(sess, Role.VOADMIN, vo)) return true; } if(roles.contains(Role.VOOBSERVER)) { if(isAuthorized(sess, Role.VOOBSERVER, vo)) return true; } if(roles.contains(Role.GROUPADMIN)); //Not allowed if(roles.contains(Role.FACILITYADMIN)); //Not allowed if(roles.contains(Role.SELF)); //Not allowed } else if(group != null) { if(roles.contains(Role.VOADMIN)) { Vo v = getPerunBlImpl().getGroupsManagerBl().getVo(sess, group); if(isAuthorized(sess, Role.VOADMIN, v)) return true; } if(roles.contains(Role.VOOBSERVER)) { Vo v = getPerunBlImpl().getGroupsManagerBl().getVo(sess, group); if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } if(roles.contains(Role.GROUPADMIN)) if(isAuthorized(sess, Role.GROUPADMIN, group)) return true; if(roles.contains(Role.FACILITYADMIN)); //Not allowed if(roles.contains(Role.SELF)); //Not allowed } else if(resource != null) { if(roles.contains(Role.VOADMIN)) { Vo v = getPerunBlImpl().getResourcesManagerBl().getVo(sess, resource); if(isAuthorized(sess, Role.VOADMIN, v)) return true; } if(roles.contains(Role.VOOBSERVER)) { Vo v = getPerunBlImpl().getResourcesManagerBl().getVo(sess, resource); if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } if(roles.contains(Role.GROUPADMIN)); { List<Group> groupsFromResource = getPerunBlImpl().getResourcesManagerBl().getAssignedGroups(sess, resource); for(Group g: groupsFromResource) { if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)) { Facility f = getPerunBlImpl().getResourcesManagerBl().getFacility(sess, resource); if(isAuthorized(sess, Role.FACILITYADMIN, f)) return true; } if(roles.contains(Role.SELF)); //Not allowed } else if(facility != null) { if(roles.contains(Role.VOADMIN)) { List<Resource> resourcesFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility); List<Vo> vosFromResources = new ArrayList<Vo>(); for(Resource resourceElement: resourcesFromFacility) { vosFromResources.add(getPerunBlImpl().getResourcesManagerBl().getVo(sess, resourceElement)); } vosFromResources = new ArrayList<Vo>(new HashSet<Vo>(vosFromResources)); for(Vo v: vosFromResources) { if(isAuthorized(sess, Role.VOADMIN, v)) return true; } } if(roles.contains(Role.VOOBSERVER)) { List<Resource> resourcesFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility); List<Vo> vosFromResources = new ArrayList<Vo>(); for(Resource resourceElement: resourcesFromFacility) { vosFromResources.add(getPerunBlImpl().getResourcesManagerBl().getVo(sess, resourceElement)); } vosFromResources = new ArrayList<Vo>(new HashSet<Vo>(vosFromResources)); for(Vo v: vosFromResources) { if(isAuthorized(sess, Role.VOOBSERVER, v)) return true; } } if(roles.contains(Role.GROUPADMIN)) { List<Resource> resourcesFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAssignedResources(sess, facility); List<Group> groupsFromFacility = new ArrayList<Group>(); for(Resource resourceElement: resourcesFromFacility) { groupsFromFacility.addAll(getPerunBlImpl().getResourcesManagerBl().getAssignedGroups(sess, resourceElement)); } groupsFromFacility = new ArrayList<Group>(new HashSet<Group>(groupsFromFacility)); for(Group g: groupsFromFacility){ if(isAuthorized(sess, Role.GROUPADMIN, g)) return true; } } if(roles.contains(Role.FACILITYADMIN)) if(isAuthorized(sess, Role.FACILITYADMIN, facility)) return true; if(roles.contains(Role.SELF)) { List<User> usersFromFacility = getPerunBlImpl().getFacilitiesManagerBl().getAllowedUsers(sess, facility); if(usersFromFacility.contains(sess.getPerunPrincipal().getUser())) { return true; } } } else if(host != null) { if(roles.contains(Role.VOADMIN)); //Not allowed if(roles.contains(Role.VOOBSERVER)); //Not allowed if(roles.contains(Role.GROUPADMIN)); //Not allowed if(roles.contains(Role.FACILITYADMIN)) { Facility f = getPerunBlImpl().getFacilitiesManagerBl().getFacilityForHost(sess, host); if(isAuthorized(sess, Role.FACILITYADMIN, f)) return true; } if(roles.contains(Role.SELF)); //Not allowed } else { throw new InternalErrorException("There is no other possible variants for now!"); } } catch (VoNotExistsException ex) { throw new InternalErrorException(ex); } return false; }
diff --git a/src/main/java/org/jboss/virtual/VFSUtils.java b/src/main/java/org/jboss/virtual/VFSUtils.java index 4b328e1..98337d4 100644 --- a/src/main/java/org/jboss/virtual/VFSUtils.java +++ b/src/main/java/org/jboss/virtual/VFSUtils.java @@ -1,369 +1,370 @@ /* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.virtual; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; import org.jboss.logging.Logger; import org.jboss.util.StringPropertyReplacer; import org.jboss.virtual.spi.LinkInfo; /** * VFS Utilities * * @author <a href="[email protected]">Adrian Brock</a> * @version $Revision: 1.1 $ */ public class VFSUtils { /** The log */ private static final Logger log = Logger.getLogger(VFSUtils.class); /** */ public static final String VFS_LINK_PREFIX = ".vfslink"; /** */ public static final String VFS_LINK_NAME = "vfs.link.name"; public static final String VFS_LINK_TARGET = "vfs.link.target"; /** * Get the paths string for a collection of virtual files * * @param paths the paths * @return the string * @throws IllegalArgumentException for null paths */ public static String getPathsString(Collection<VirtualFile> paths) { StringBuilder buffer = new StringBuilder(); boolean first = true; for (VirtualFile path : paths) { if (path == null) throw new IllegalArgumentException("Null path in " + paths); if (first == false) buffer.append(':'); else first = false; buffer.append(path.getPathName()); } if (first == true) buffer.append("<empty>"); return buffer.toString(); } /** * Add manifest paths * * @param file the file * @param paths the paths to add to * @throws IOException if there is an error reading the manifest or the * virtual file is closed * @throws IllegalStateException if the file has no parent * @throws IllegalArgumentException for a null file or paths */ public static void addManifestLocations(VirtualFile file, List<VirtualFile> paths) throws IOException { if (file == null) throw new IllegalArgumentException("Null file"); if (paths == null) throw new IllegalArgumentException("Null paths"); Manifest manifest = getManifest(file); if (manifest == null) return; Attributes mainAttributes = manifest.getMainAttributes(); String classPath = mainAttributes.getValue(Attributes.Name.CLASS_PATH); if (classPath == null) { if (log.isTraceEnabled()) log.trace("Manifest has no Class-Path for " + file.getPathName()); return; } VirtualFile parent = file.getParent(); if (parent == null) throw new IllegalStateException(file + " has no parent."); URL parentURL = null; URL vfsRootURL = null; int rootPathLength = 0; try { parentURL = parent.toURL(); vfsRootURL = file.getVFS().getRoot().toURL(); rootPathLength = vfsRootURL.getPath().length(); } catch(URISyntaxException e) { - IOException ioe = new IOException("Failed to get parent URL"); + IOException ioe = new IOException("Failed to get parent URL for " + file); ioe.initCause(e); + throw ioe; } StringTokenizer tokenizer = new StringTokenizer(classPath); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { URL libURL = new URL(parentURL, path); String libPath = libURL.getPath(); // TODO, this occurs for inner jars. Doubtful that such a mf cp is valid if( rootPathLength > libPath.length() ) throw new IOException("Invalid rootPath: "+vfsRootURL+", libPath: "+libPath); String vfsLibPath = libPath.substring(rootPathLength); VirtualFile vf = file.getVFS().findChild(vfsLibPath); paths.add(vf); } catch (IOException e) { log.debug("Manifest Class-Path entry " + path + " ignored for " + file.getPathName() + " reason=" + e); } } } /** * Get a manifest from a virtual file, * assuming the virtual file is the root of an archive * * @param archive the root the archive * @return the manifest or null if not found * @throws IOException if there is an error reading the manifest or the * virtual file is closed * @throws IllegalArgumentException for a null archive */ public static Manifest getManifest(VirtualFile archive) throws IOException { if (archive == null) throw new IllegalArgumentException("Null archive"); VirtualFile manifest; try { manifest = archive.findChild(JarFile.MANIFEST_NAME); } catch (IOException ignored) { log.debug("Can't find manifest for " + archive.getPathName()); return null; } return readManifest(manifest); } /** * Read the manifest from given manifest VirtualFile. * * @param manifest the VF to read from * @return JAR's manifest * @throws IOException if problems while opening VF stream occur */ public static Manifest readManifest(VirtualFile manifest) throws IOException { InputStream stream = manifest.openStream(); try { return new Manifest(stream); } finally { try { stream.close(); } catch (IOException ignored) { } } } /** * Get a manifest from a virtual file system, * assuming the root of the VFS is the root of an archive * * @param archive the vfs * @return the manifest or null if not found * @throws IOException if there is an error reading the manifest * @throws IllegalArgumentException for a null archive */ public static Manifest getManifest(VFS archive) throws IOException { VirtualFile root = archive.getRoot(); return getManifest(root); } /** * Fix a name (removes any trailing slash) * * @param name the name to fix * @return the fixed name * @throws IllegalArgumentException for a null name */ public static String fixName(String name) { if (name == null) throw new IllegalArgumentException("Null name"); int length = name.length(); if (length <= 1) return name; if (name.charAt(length-1) == '/') return name.substring(0, length-1); return name; } /** * * @param uri * @return name from uri's path */ public static String getName(URI uri) { String name = uri.getPath(); if( name != null ) { // TODO: Not correct for certain uris like jar:...!/ int lastSlash = name.lastIndexOf('/'); if( lastSlash > 0 ) name = name.substring(lastSlash+1); } return name; } /** * Take a URL.getQuery string and parse it into name=value pairs * * @param query Possibly empty/null url query string * @return String[] for the name/value pairs in the query. May be empty but never null. */ public static Map<String, String> parseURLQuery(String query) { HashMap<String, String> pairsMap = new HashMap<String, String>(); if( query != null ) { StringTokenizer tokenizer = new StringTokenizer(query, "=&"); while( tokenizer.hasMoreTokens() ) { String name = tokenizer.nextToken(); String value = tokenizer.nextToken(); pairsMap.put(name, value); } } return pairsMap; } /** * Does a vf name contain the VFS link prefix * @param name - the name portion of a virtual file * @return true if the name starts with VFS_LINK_PREFIX, false otherwise */ public static boolean isLink(String name) { return name.indexOf(VFS_LINK_PREFIX) >= 0; } /** * Read the link information from the stream based on the type as determined * from the name suffix. * * @param is - input stream to the link file contents * @param name - the name of the virtual file representing the link * @param props the propertes * @return a list of the links read from the stream * @throws IOException on failure to read/parse the stream * @throws URISyntaxException for an error parsing a URI */ public static List<LinkInfo> readLinkInfo(InputStream is, String name, Properties props) throws IOException, URISyntaxException { ArrayList<LinkInfo> info = new ArrayList<LinkInfo>(); if( name.endsWith(".properties") ) parseLinkProperties(is, info, props); else throw new UnsupportedEncodingException("Unknown link format: "+name); return info; } /** * Parse a properties link file * * @param is - input stream to the link file contents * @param info the link infos * @param props the propertes * @throws IOException on failure to read/parse the stream * @throws URISyntaxException for an error parsing a URI */ public static void parseLinkProperties(InputStream is, List<LinkInfo> info, Properties props) throws IOException, URISyntaxException { props.load(is); // Iterate over the property tuples for(int n = 0; ; n ++) { String nameKey = VFS_LINK_NAME + "." + n; String name = props.getProperty(nameKey); String uriKey = VFS_LINK_TARGET + "." + n; String uri = props.getProperty(uriKey); // End when the value is null since a link may not have a name if (uri == null) { break; } // Replace any system property references uri = StringPropertyReplacer.replaceProperties(uri); LinkInfo link = new LinkInfo(name, new URI(uri)); info.add(link); } } /** * Deal with urls that may include spaces. * * @param url the url * @return uri the uri * @throws URISyntaxException for any error */ public static URI toURI(URL url) throws URISyntaxException { String urispec = url.toExternalForm(); // Escape any spaces urispec = urispec.replaceAll(" ", "%20"); return new URI(urispec); } }
false
true
public static void addManifestLocations(VirtualFile file, List<VirtualFile> paths) throws IOException { if (file == null) throw new IllegalArgumentException("Null file"); if (paths == null) throw new IllegalArgumentException("Null paths"); Manifest manifest = getManifest(file); if (manifest == null) return; Attributes mainAttributes = manifest.getMainAttributes(); String classPath = mainAttributes.getValue(Attributes.Name.CLASS_PATH); if (classPath == null) { if (log.isTraceEnabled()) log.trace("Manifest has no Class-Path for " + file.getPathName()); return; } VirtualFile parent = file.getParent(); if (parent == null) throw new IllegalStateException(file + " has no parent."); URL parentURL = null; URL vfsRootURL = null; int rootPathLength = 0; try { parentURL = parent.toURL(); vfsRootURL = file.getVFS().getRoot().toURL(); rootPathLength = vfsRootURL.getPath().length(); } catch(URISyntaxException e) { IOException ioe = new IOException("Failed to get parent URL"); ioe.initCause(e); } StringTokenizer tokenizer = new StringTokenizer(classPath); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { URL libURL = new URL(parentURL, path); String libPath = libURL.getPath(); // TODO, this occurs for inner jars. Doubtful that such a mf cp is valid if( rootPathLength > libPath.length() ) throw new IOException("Invalid rootPath: "+vfsRootURL+", libPath: "+libPath); String vfsLibPath = libPath.substring(rootPathLength); VirtualFile vf = file.getVFS().findChild(vfsLibPath); paths.add(vf); } catch (IOException e) { log.debug("Manifest Class-Path entry " + path + " ignored for " + file.getPathName() + " reason=" + e); } } }
public static void addManifestLocations(VirtualFile file, List<VirtualFile> paths) throws IOException { if (file == null) throw new IllegalArgumentException("Null file"); if (paths == null) throw new IllegalArgumentException("Null paths"); Manifest manifest = getManifest(file); if (manifest == null) return; Attributes mainAttributes = manifest.getMainAttributes(); String classPath = mainAttributes.getValue(Attributes.Name.CLASS_PATH); if (classPath == null) { if (log.isTraceEnabled()) log.trace("Manifest has no Class-Path for " + file.getPathName()); return; } VirtualFile parent = file.getParent(); if (parent == null) throw new IllegalStateException(file + " has no parent."); URL parentURL = null; URL vfsRootURL = null; int rootPathLength = 0; try { parentURL = parent.toURL(); vfsRootURL = file.getVFS().getRoot().toURL(); rootPathLength = vfsRootURL.getPath().length(); } catch(URISyntaxException e) { IOException ioe = new IOException("Failed to get parent URL for " + file); ioe.initCause(e); throw ioe; } StringTokenizer tokenizer = new StringTokenizer(classPath); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { URL libURL = new URL(parentURL, path); String libPath = libURL.getPath(); // TODO, this occurs for inner jars. Doubtful that such a mf cp is valid if( rootPathLength > libPath.length() ) throw new IOException("Invalid rootPath: "+vfsRootURL+", libPath: "+libPath); String vfsLibPath = libPath.substring(rootPathLength); VirtualFile vf = file.getVFS().findChild(vfsLibPath); paths.add(vf); } catch (IOException e) { log.debug("Manifest Class-Path entry " + path + " ignored for " + file.getPathName() + " reason=" + e); } } }
diff --git a/src/test/TestFramework.java b/src/test/TestFramework.java index ada2ae76f1..6c9b362be1 100644 --- a/src/test/TestFramework.java +++ b/src/test/TestFramework.java @@ -1,133 +1,133 @@ package test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PrintWriter; import org.eclipse.imp.pdb.facts.IConstructor; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.impl.reference.ValueFactory; import org.meta_environment.rascal.ast.ASTFactory; import org.meta_environment.rascal.ast.Command; import org.meta_environment.rascal.ast.Module; import org.meta_environment.rascal.interpreter.Evaluator; import org.meta_environment.rascal.interpreter.exceptions.RascalBug; import org.meta_environment.rascal.interpreter.exceptions.RascalRunTimeError; import org.meta_environment.rascal.parser.ASTBuilder; import org.meta_environment.rascal.parser.Parser; import org.meta_environment.uptr.Factory; public class TestFramework { private Parser parser = Parser.getInstance(); private ASTFactory factory = new ASTFactory(); private ASTBuilder builder = new ASTBuilder(factory); private Evaluator evaluator; public TestFramework () { evaluator = new Evaluator(ValueFactory.getInstance(), factory, new PrintWriter(System.err)); } public TestFramework (String command){ try { prepare(command); } catch (Exception e){ throw new RascalRunTimeError("Exception while creating TestFramework: " + e); } } boolean runTest(String command) throws IOException { evaluator = new Evaluator(ValueFactory.getInstance(), factory, new PrintWriter(System.err)); return execute(command); } boolean runTestInSameEvaluator(String command) throws IOException { return execute(command); } boolean runTest(String command1, String command2) throws IOException { evaluator = new Evaluator(ValueFactory.getInstance(), factory, new PrintWriter(System.err)); execute(command1); return execute(command2); } boolean runWithError(String command, String msg){ evaluator = new Evaluator(ValueFactory.getInstance(), factory, new PrintWriter(System.err)); try { execute(command); } catch (Exception e){ return e.toString().indexOf(msg) >= 0; } return false; } boolean runWithErrorInSameEvaluator(String command, String msg){ try { execute(command); } catch (Exception e){ return e.toString().indexOf(msg) >= 0; } return false; } TestFramework prepare(String command){ try{ evaluator = new Evaluator(ValueFactory.getInstance(), factory, new PrintWriter(System.err)); execute(command); } catch (Exception e){ System.err.println("Unhandled exception: " + e); } return this; } TestFramework prepareMore(String command) throws IOException{ execute(command); return this; } boolean prepareModule(String module) throws IOException { IConstructor tree = parser.parse(new ByteArrayInputStream(module.getBytes())); if (tree.getType() == Factory.ParseTree_Summary) { System.err.println(tree); return false; } else { evaluator = new Evaluator(ValueFactory.getInstance(), factory, new PrintWriter(System.err)); Module mod = builder.buildModule(tree); mod.accept(evaluator); return true; } } private boolean execute(String command) throws IOException { IConstructor tree = parser.parse(new ByteArrayInputStream(command.getBytes())); - if (tree.getType() == Factory.ParseTree_Summary) { + if (tree.getConstructorType() == Factory.ParseTree_Summary) { System.err.println(tree); return false; } else { Command cmd = builder.buildCommand(tree); if (cmd.isStatement()) { IValue value = evaluator.eval(cmd.getStatement()); if (value == null || !value.getType().isBoolType()) return false; return value.isEqual(ValueFactory.getInstance().bool(true)) ? true : false; } else if (cmd.isImport()) { evaluator.eval(cmd.getImported()); return true; } else if (cmd.isDeclaration()) { evaluator.eval(cmd.getDeclaration()); return true; } else { throw new RascalBug("unexpected case in eval: " + cmd); } } } }
true
true
private boolean execute(String command) throws IOException { IConstructor tree = parser.parse(new ByteArrayInputStream(command.getBytes())); if (tree.getType() == Factory.ParseTree_Summary) { System.err.println(tree); return false; } else { Command cmd = builder.buildCommand(tree); if (cmd.isStatement()) { IValue value = evaluator.eval(cmd.getStatement()); if (value == null || !value.getType().isBoolType()) return false; return value.isEqual(ValueFactory.getInstance().bool(true)) ? true : false; } else if (cmd.isImport()) { evaluator.eval(cmd.getImported()); return true; } else if (cmd.isDeclaration()) { evaluator.eval(cmd.getDeclaration()); return true; } else { throw new RascalBug("unexpected case in eval: " + cmd); } } }
private boolean execute(String command) throws IOException { IConstructor tree = parser.parse(new ByteArrayInputStream(command.getBytes())); if (tree.getConstructorType() == Factory.ParseTree_Summary) { System.err.println(tree); return false; } else { Command cmd = builder.buildCommand(tree); if (cmd.isStatement()) { IValue value = evaluator.eval(cmd.getStatement()); if (value == null || !value.getType().isBoolType()) return false; return value.isEqual(ValueFactory.getInstance().bool(true)) ? true : false; } else if (cmd.isImport()) { evaluator.eval(cmd.getImported()); return true; } else if (cmd.isDeclaration()) { evaluator.eval(cmd.getDeclaration()); return true; } else { throw new RascalBug("unexpected case in eval: " + cmd); } } }
diff --git a/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/IRStatisticsImpl.java b/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/IRStatisticsImpl.java index f6aadae1b..f82f95840 100644 --- a/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/IRStatisticsImpl.java +++ b/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/IRStatisticsImpl.java @@ -1,89 +1,89 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.mahout.cf.taste.impl.eval; import java.io.Serializable; import org.apache.mahout.cf.taste.eval.IRStatistics; import com.google.common.base.Preconditions; public final class IRStatisticsImpl implements IRStatistics, Serializable { private final double precision; private final double recall; private final double fallOut; private final double ndcg; private final double reach; IRStatisticsImpl(double precision, double recall, double fallOut, double ndcg, double reach) { Preconditions.checkArgument(precision >= 0.0 && precision <= 1.0, "Illegal precision: " + precision); Preconditions.checkArgument(recall >= 0.0 && recall <= 1.0, "Illegal recall: " + recall); Preconditions.checkArgument(fallOut >= 0.0 && fallOut <= 1.0, "Illegal fallOut: " + fallOut); - Preconditions.checkArgument(fallOut >= 0.0 && fallOut <= 1.0, "Illegal nDCG: " + ndcg); - Preconditions.checkArgument(reach >= 0.0 && reach <= 1.0, "Illegal reach: " + ndcg); + Preconditions.checkArgument(ndcg >= 0.0 && ndcg <= 1.0, "Illegal nDCG: " + ndcg); + Preconditions.checkArgument(reach >= 0.0 && reach <= 1.0, "Illegal reach: " + reach); this.precision = precision; this.recall = recall; this.fallOut = fallOut; this.ndcg = ndcg; this.reach = reach; } @Override public double getPrecision() { return precision; } @Override public double getRecall() { return recall; } @Override public double getFallOut() { return fallOut; } @Override public double getF1Measure() { return getFNMeasure(1.0); } @Override public double getFNMeasure(double n) { double sum = n * precision + recall; return sum == 0.0 ? Double.NaN : (1.0 + n) * precision * recall / sum; } @Override public double getNormalizedDiscountedCumulativeGain() { return ndcg; } @Override public double getReach() { return reach; } @Override public String toString() { return "IRStatisticsImpl[precision:" + precision + ",recall:" + recall + ",fallOut:" + fallOut + ",nDCG:" + ndcg + ",reach:" + reach + ']'; } }
true
true
IRStatisticsImpl(double precision, double recall, double fallOut, double ndcg, double reach) { Preconditions.checkArgument(precision >= 0.0 && precision <= 1.0, "Illegal precision: " + precision); Preconditions.checkArgument(recall >= 0.0 && recall <= 1.0, "Illegal recall: " + recall); Preconditions.checkArgument(fallOut >= 0.0 && fallOut <= 1.0, "Illegal fallOut: " + fallOut); Preconditions.checkArgument(fallOut >= 0.0 && fallOut <= 1.0, "Illegal nDCG: " + ndcg); Preconditions.checkArgument(reach >= 0.0 && reach <= 1.0, "Illegal reach: " + ndcg); this.precision = precision; this.recall = recall; this.fallOut = fallOut; this.ndcg = ndcg; this.reach = reach; }
IRStatisticsImpl(double precision, double recall, double fallOut, double ndcg, double reach) { Preconditions.checkArgument(precision >= 0.0 && precision <= 1.0, "Illegal precision: " + precision); Preconditions.checkArgument(recall >= 0.0 && recall <= 1.0, "Illegal recall: " + recall); Preconditions.checkArgument(fallOut >= 0.0 && fallOut <= 1.0, "Illegal fallOut: " + fallOut); Preconditions.checkArgument(ndcg >= 0.0 && ndcg <= 1.0, "Illegal nDCG: " + ndcg); Preconditions.checkArgument(reach >= 0.0 && reach <= 1.0, "Illegal reach: " + reach); this.precision = precision; this.recall = recall; this.fallOut = fallOut; this.ndcg = ndcg; this.reach = reach; }
diff --git a/rse/plugins/org.eclipse.dltk.rse.core/src/org/eclipse/dltk/core/internal/rse/MyHostShellProcessAdapter.java b/rse/plugins/org.eclipse.dltk.rse.core/src/org/eclipse/dltk/core/internal/rse/MyHostShellProcessAdapter.java index d01321e78..f31c366fd 100644 --- a/rse/plugins/org.eclipse.dltk.rse.core/src/org/eclipse/dltk/core/internal/rse/MyHostShellProcessAdapter.java +++ b/rse/plugins/org.eclipse.dltk.rse.core/src/org/eclipse/dltk/core/internal/rse/MyHostShellProcessAdapter.java @@ -1,209 +1,209 @@ /******************************************************************************* * Copyright (c) 2006 PalmSource, Inc. * 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: * Ewa Matejska (PalmSource) - initial version * Martin Oberhuber (Wind River) - adapt to IHostOutput API (bug 161773, 158312) * Martin Oberhuber (Wind River) - moved from org.eclipse.rse.remotecdt (bug 161777) * Martin Oberhuber (Wind River) - renamed from HostShellAdapter (bug 161777) * Martin Oberhuber (Wind River) - improved Javadoc *******************************************************************************/ package org.eclipse.dltk.core.internal.rse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import org.eclipse.rse.services.shells.HostShellOutputStream; import org.eclipse.rse.services.shells.IHostOutput; import org.eclipse.rse.services.shells.IHostShell; import org.eclipse.rse.services.shells.IHostShellChangeEvent; import org.eclipse.rse.services.shells.IHostShellOutputListener; /** * This class represents a host shell process. It does not represent one process * running in the shell. This means that the output of multiple shell commands * will be returned until the shell exits. * * @author Ewa Matejska */ public class MyHostShellProcessAdapter extends Process implements IHostShellOutputListener { private IHostShell hostShell; private PipedInputStream inputStream = null; private PipedInputStream errorStream = null; private HostShellOutputStream outputStream = null; private PipedOutputStream hostShellInput = null; private PipedOutputStream hostShellError = null; private String pattern1; /** * Constructor. * * @param hostShell * An instance of the IHostShell class. * @param postfix * @throws java.io.IOException */ public MyHostShellProcessAdapter(IHostShell hostShell, String pattern1) throws java.io.IOException { this.hostShell = hostShell; hostShellInput = new PipedOutputStream(); hostShellError = new PipedOutputStream(); inputStream = new PipedInputStream(hostShellInput); errorStream = new PipedInputStream(hostShellError); outputStream = new HostShellOutputStream(hostShell); this.hostShell.getStandardOutputReader().addOutputListener(this); this.hostShell.getStandardErrorReader().addOutputListener(this); this.pattern1 = pattern1; } /** * Exits the shell. * * @see java.lang.Process#destroy() */ public synchronized void destroy() { hostShell.exit(); notifyAll(); try { hostShellInput.close(); hostShellError.close(); inputStream.close(); errorStream.close(); outputStream.close(); } catch (IOException e) { // FIXME IOException when closing one of the streams will leave // others open // Ignore } } /** * There is no relevant exit value to return when the shell exits. This * always returns 0. */ public synchronized int exitValue() { if (hostShell.isActive()) throw new IllegalThreadStateException(); // No way to tell what the exit value was. // TODO it would be possible to get the exit value // when the remote process is started like this: // sh -c' remotecmd ; echo" -->RSETAG<-- $?\"' // Then the output steram could be examined for -->RSETAG<-- to get the // exit value. return 0; } /** * Returns the error stream of the shell. * * @see java.lang.Process#getErrorStream() */ public InputStream getErrorStream() { return errorStream; } /** * Returns the input stream for the shell. * * @see java.lang.Process#getInputStream() */ public InputStream getInputStream() { return inputStream; } /** * Returns the output stream for the shell. * * @see java.lang.Process#getOutputStream() */ public OutputStream getOutputStream() { return outputStream; } /** * Waits for the shell to exit. * * @see java.lang.Process#waitFor() */ public synchronized int waitFor() throws InterruptedException { while (hostShell.isActive()) { try { wait(1000); } catch (InterruptedException e) { // ignore because we're polling to see if shell is still active. } } try { // Wait a second to try to get some more output from the target // shell before closing. wait(1000); // Allow for the data from the stream to be read if it's available if (inputStream.available() != 0 || errorStream.available() != 0) throw new InterruptedException(); hostShellInput.close(); hostShellError.close(); inputStream.close(); errorStream.close(); outputStream.close(); } catch (IOException e) { // Ignore } return 0; } /** * Process an RSE Shell event, by writing the lines of text contained in the * event into the adapter's streams. * * @see org.eclipse.rse.services.shells.IHostShellOutputListener# * shellOutputChanged * (org.eclipse.rse.services.shells.IHostShellChangeEvent) */ private boolean skip = true; private int prefixCounter = 0; public void shellOutputChanged(IHostShellChangeEvent event) { IHostOutput[] input = event.getLines(); OutputStream outputStream = event.isError() ? hostShellError : hostShellInput; try { for (int i = 0; i < input.length; i++) { String line = input[i].getString(); - System.out.println("RSEExecEnvironment:" + line); +// System.out.println("RSEExecEnvironment:" + line); if (line.trim().equals(this.pattern1)) { prefixCounter++; if (prefixCounter == 2) { - System.out.println("CALL DESTROY"); +// System.out.println("CALL DESTROY"); hostShellError.close(); hostShellInput.close(); return; } skip = !skip; continue; } if (!skip) { outputStream.write(line.getBytes()); outputStream.write('\n'); outputStream.flush(); } } } catch (IOException e) { // Ignore } } }
false
true
public void shellOutputChanged(IHostShellChangeEvent event) { IHostOutput[] input = event.getLines(); OutputStream outputStream = event.isError() ? hostShellError : hostShellInput; try { for (int i = 0; i < input.length; i++) { String line = input[i].getString(); System.out.println("RSEExecEnvironment:" + line); if (line.trim().equals(this.pattern1)) { prefixCounter++; if (prefixCounter == 2) { System.out.println("CALL DESTROY"); hostShellError.close(); hostShellInput.close(); return; } skip = !skip; continue; } if (!skip) { outputStream.write(line.getBytes()); outputStream.write('\n'); outputStream.flush(); } } } catch (IOException e) { // Ignore } }
public void shellOutputChanged(IHostShellChangeEvent event) { IHostOutput[] input = event.getLines(); OutputStream outputStream = event.isError() ? hostShellError : hostShellInput; try { for (int i = 0; i < input.length; i++) { String line = input[i].getString(); // System.out.println("RSEExecEnvironment:" + line); if (line.trim().equals(this.pattern1)) { prefixCounter++; if (prefixCounter == 2) { // System.out.println("CALL DESTROY"); hostShellError.close(); hostShellInput.close(); return; } skip = !skip; continue; } if (!skip) { outputStream.write(line.getBytes()); outputStream.write('\n'); outputStream.flush(); } } } catch (IOException e) { // Ignore } }
diff --git a/src/com/android/gallery3d/ui/TileImageView.java b/src/com/android/gallery3d/ui/TileImageView.java index eb5da89..7e811fc 100644 --- a/src/com/android/gallery3d/ui/TileImageView.java +++ b/src/com/android/gallery3d/ui/TileImageView.java @@ -1,757 +1,757 @@ /* * 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.gallery3d.ui; import android.graphics.Bitmap; import android.graphics.Point; import android.graphics.Rect; import android.graphics.RectF; import android.util.FloatMath; import android.util.LongSparseArray; import com.android.gallery3d.app.GalleryContext; import com.android.gallery3d.common.Utils; import com.android.gallery3d.data.DecodeUtils; import com.android.gallery3d.util.Future; import com.android.gallery3d.util.ThreadPool; import com.android.gallery3d.util.ThreadPool.CancelListener; import com.android.gallery3d.util.ThreadPool.JobContext; import java.util.concurrent.atomic.AtomicBoolean; public class TileImageView extends GLView { public static final int SIZE_UNKNOWN = -1; @SuppressWarnings("unused") private static final String TAG = "TileImageView"; // TILE_SIZE must be 2^N - 2. We put one pixel border in each side of the // texture to avoid seams between tiles. private static final int TILE_SIZE = 254; private static final int TILE_BORDER = 1; private static final int UPLOAD_LIMIT = 1; /* * This is the tile state in the CPU side. * Life of a Tile: * ACTIVATED (initial state) * --> IN_QUEUE - by queueForDecode() * --> RECYCLED - by recycleTile() * IN_QUEUE --> DECODING - by decodeTile() * --> RECYCLED - by recycleTile) * DECODING --> RECYCLING - by recycleTile() * --> DECODED - by decodeTile() * --> DECODE_FAIL - by decodeTile() * RECYCLING --> RECYCLED - by decodeTile() * DECODED --> ACTIVATED - (after the decoded bitmap is uploaded) * DECODED --> RECYCLED - by recycleTile() * DECODE_FAIL -> RECYCLED - by recycleTile() * RECYCLED --> ACTIVATED - by obtainTile() */ private static final int STATE_ACTIVATED = 0x01; private static final int STATE_IN_QUEUE = 0x02; private static final int STATE_DECODING = 0x04; private static final int STATE_DECODED = 0x08; private static final int STATE_DECODE_FAIL = 0x10; private static final int STATE_RECYCLING = 0x20; private static final int STATE_RECYCLED = 0x40; private Model mModel; private ScreenNail mScreenNail; protected int mLevelCount; // cache the value of mScaledBitmaps.length // The mLevel variable indicates which level of bitmap we should use. // Level 0 means the original full-sized bitmap, and a larger value means // a smaller scaled bitmap (The width and height of each scaled bitmap is // half size of the previous one). If the value is in [0, mLevelCount), we // use the bitmap in mScaledBitmaps[mLevel] for display, otherwise the value // is mLevelCount, and that means we use mScreenNail for display. private int mLevel = 0; // The offsets of the (left, top) of the upper-left tile to the (left, top) // of the view. private int mOffsetX; private int mOffsetY; private int mUploadQuota; private boolean mRenderComplete; private final RectF mSourceRect = new RectF(); private final RectF mTargetRect = new RectF(); private final LongSparseArray<Tile> mActiveTiles = new LongSparseArray<Tile>(); // The following three queue is guarded by TileImageView.this private TileQueue mRecycledQueue = new TileQueue(); private TileQueue mUploadQueue = new TileQueue(); private TileQueue mDecodeQueue = new TileQueue(); // The width and height of the full-sized bitmap protected int mImageWidth = SIZE_UNKNOWN; protected int mImageHeight = SIZE_UNKNOWN; protected int mCenterX; protected int mCenterY; protected float mScale; protected int mRotation; protected float mAlpha = 1.0f; // Temp variables to avoid memory allocation private final Rect mTileRange = new Rect(); private final Rect mActiveRange[] = {new Rect(), new Rect()}; private final TileUploader mTileUploader = new TileUploader(); private boolean mIsTextureFreed; private Future<Void> mTileDecoder; private ThreadPool mThreadPool; private boolean mBackgroundTileUploaded; public static interface Model { public int getLevelCount(); public ScreenNail getScreenNail(); public int getImageWidth(); public int getImageHeight(); // The tile returned by this method can be specified this way: Assuming // the image size is (width, height), first take the intersection of (0, // 0) - (width, height) and (x, y) - (x + tileSize, y + tileSize). Then // extend this intersection region by borderSize pixels on each side. If // in extending the region, we found some part of the region are outside // the image, those pixels are filled with black. // // If level > 0, it does the same operation on a down-scaled version of // the original image (down-scaled by a factor of 2^level), but (x, y) // still refers to the coordinate on the original image. // // The method would be called in another thread. public Bitmap getTile(int level, int x, int y, int tileSize, int borderSize); public boolean isFailedToLoad(); } public TileImageView(GalleryContext context) { mThreadPool = context.getThreadPool(); mTileDecoder = mThreadPool.submit(new TileDecoder()); } public void setModel(Model model) { mModel = model; if (model != null) notifyModelInvalidated(); } public void setScreenNail(ScreenNail s) { mScreenNail = s; } public void notifyModelInvalidated() { invalidateTiles(); if (mModel == null) { mScreenNail = null; mImageWidth = 0; mImageHeight = 0; mLevelCount = 0; } else { setScreenNail(mModel.getScreenNail()); mImageWidth = mModel.getImageWidth(); mImageHeight = mModel.getImageHeight(); mLevelCount = mModel.getLevelCount(); } layoutTiles(mCenterX, mCenterY, mScale, mRotation); invalidate(); } @Override protected void onLayout( boolean changeSize, int left, int top, int right, int bottom) { super.onLayout(changeSize, left, top, right, bottom); if (changeSize) layoutTiles(mCenterX, mCenterY, mScale, mRotation); } // Prepare the tiles we want to use for display. // // 1. Decide the tile level we want to use for display. // 2. Decide the tile levels we want to keep as texture (in addition to // the one we use for display). // 3. Recycle unused tiles. // 4. Activate the tiles we want. private void layoutTiles(int centerX, int centerY, float scale, int rotation) { // The width and height of this view. int width = getWidth(); int height = getHeight(); // The tile levels we want to keep as texture is in the range // [fromLevel, endLevel). int fromLevel; int endLevel; // We want to use a texture larger than or equal to the display size. mLevel = Utils.clamp(Utils.floorLog2(1f / scale), 0, mLevelCount); // We want to keep one more tile level as texture in addition to what // we use for display. So it can be faster when the scale moves to the // next level. We choose a level closer to the current scale. if (mLevel != mLevelCount) { Rect range = mTileRange; getRange(range, centerX, centerY, mLevel, scale, rotation); mOffsetX = Math.round(width / 2f + (range.left - centerX) * scale); mOffsetY = Math.round(height / 2f + (range.top - centerY) * scale); fromLevel = scale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel; } else { // Activate the tiles of the smallest two levels. fromLevel = mLevel - 2; mOffsetX = Math.round(width / 2f - centerX * scale); mOffsetY = Math.round(height / 2f - centerY * scale); } fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2)); endLevel = Math.min(fromLevel + 2, mLevelCount); Rect range[] = mActiveRange; for (int i = fromLevel; i < endLevel; ++i) { getRange(range[i - fromLevel], centerX, centerY, i, rotation); } // If rotation is transient, don't update the tile. if (rotation % 90 != 0) return; synchronized (this) { mDecodeQueue.clean(); mUploadQueue.clean(); mBackgroundTileUploaded = false; - } - // Recycle unused tiles: if the level of the active tile is outside the - // range [fromLevel, endLevel) or not in the visible range. - int n = mActiveTiles.size(); - for (int i = 0; i < n; i++) { - Tile tile = mActiveTiles.valueAt(i); - int level = tile.mTileLevel; - if (level < fromLevel || level >= endLevel - || !range[level - fromLevel].contains(tile.mX, tile.mY)) { - mActiveTiles.removeAt(i); - i--; - n--; - recycleTile(tile); + // Recycle unused tiles: if the level of the active tile is outside the + // range [fromLevel, endLevel) or not in the visible range. + int n = mActiveTiles.size(); + for (int i = 0; i < n; i++) { + Tile tile = mActiveTiles.valueAt(i); + int level = tile.mTileLevel; + if (level < fromLevel || level >= endLevel + || !range[level - fromLevel].contains(tile.mX, tile.mY)) { + mActiveTiles.removeAt(i); + i--; + n--; + recycleTile(tile); + } } } for (int i = fromLevel; i < endLevel; ++i) { int size = TILE_SIZE << i; Rect r = range[i - fromLevel]; for (int y = r.top, bottom = r.bottom; y < bottom; y += size) { for (int x = r.left, right = r.right; x < right; x += size) { activateTile(x, y, i); } } } invalidate(); } protected synchronized void invalidateTiles() { mDecodeQueue.clean(); mUploadQueue.clean(); // TODO disable decoder int n = mActiveTiles.size(); for (int i = 0; i < n; i++) { Tile tile = mActiveTiles.valueAt(i); recycleTile(tile); } mActiveTiles.clear(); } private void getRange(Rect out, int cX, int cY, int level, int rotation) { getRange(out, cX, cY, level, 1f / (1 << (level + 1)), rotation); } // If the bitmap is scaled by the given factor "scale", return the // rectangle containing visible range. The left-top coordinate returned is // aligned to the tile boundary. // // (cX, cY) is the point on the original bitmap which will be put in the // center of the ImageViewer. private void getRange(Rect out, int cX, int cY, int level, float scale, int rotation) { double radians = Math.toRadians(-rotation); double w = getWidth(); double h = getHeight(); double cos = Math.cos(radians); double sin = Math.sin(radians); int width = (int) Math.ceil(Math.max( Math.abs(cos * w - sin * h), Math.abs(cos * w + sin * h))); int height = (int) Math.ceil(Math.max( Math.abs(sin * w + cos * h), Math.abs(sin * w - cos * h))); int left = (int) FloatMath.floor(cX - width / (2f * scale)); int top = (int) FloatMath.floor(cY - height / (2f * scale)); int right = (int) FloatMath.ceil(left + width / scale); int bottom = (int) FloatMath.ceil(top + height / scale); // align the rectangle to tile boundary int size = TILE_SIZE << level; left = Math.max(0, size * (left / size)); top = Math.max(0, size * (top / size)); right = Math.min(mImageWidth, right); bottom = Math.min(mImageHeight, bottom); out.set(left, top, right, bottom); } // Calculate where the center of the image is, in the view coordinates. public void getImageCenter(Point center) { // The width and height of this view. int viewW = getWidth(); int viewH = getHeight(); // The distance between the center of the view to the center of the // bitmap, in bitmap units. (mCenterX and mCenterY are the bitmap // coordinates correspond to the center of view) int distW, distH; if (mRotation % 180 == 0) { distW = mImageWidth / 2 - mCenterX; distH = mImageHeight / 2 - mCenterY; } else { distW = mImageHeight / 2 - mCenterY; distH = mImageWidth / 2 - mCenterX; } // Convert to view coordinates. mScale translates from bitmap units to // view units. center.x = Math.round(viewW / 2f + distW * mScale); center.y = Math.round(viewH / 2f + distH * mScale); } public boolean setPosition(int centerX, int centerY, float scale, int rotation) { if (mCenterX == centerX && mCenterY == centerY && mScale == scale && mRotation == rotation) return false; mCenterX = centerX; mCenterY = centerY; mScale = scale; mRotation = rotation; layoutTiles(centerX, centerY, scale, rotation); invalidate(); return true; } public boolean setAlpha(float alpha) { if (mAlpha == alpha) return false; mAlpha = alpha; invalidate(); return true; } public void freeTextures() { mIsTextureFreed = true; if (mTileDecoder != null) { mTileDecoder.cancel(); mTileDecoder.get(); mTileDecoder = null; } int n = mActiveTiles.size(); for (int i = 0; i < n; i++) { Tile texture = mActiveTiles.valueAt(i); texture.recycle(); } mActiveTiles.clear(); mTileRange.set(0, 0, 0, 0); synchronized (this) { mUploadQueue.clean(); mDecodeQueue.clean(); Tile tile = mRecycledQueue.pop(); while (tile != null) { tile.recycle(); tile = mRecycledQueue.pop(); } } setScreenNail(null); } public void prepareTextures() { if (mTileDecoder == null) { mTileDecoder = mThreadPool.submit(new TileDecoder()); } if (mIsTextureFreed) { layoutTiles(mCenterX, mCenterY, mScale, mRotation); mIsTextureFreed = false; setScreenNail(mModel == null ? null : mModel.getScreenNail()); } } @Override protected void render(GLCanvas canvas) { mUploadQuota = UPLOAD_LIMIT; mRenderComplete = true; int level = mLevel; int rotation = mRotation; int flags = 0; if (rotation != 0) flags |= GLCanvas.SAVE_FLAG_MATRIX; if (mAlpha != 1.0f) flags |= GLCanvas.SAVE_FLAG_ALPHA; if (flags != 0) { canvas.save(flags); if (rotation != 0) { int centerX = getWidth() / 2, centerY = getHeight() / 2; canvas.translate(centerX, centerY); canvas.rotate(rotation, 0, 0, 1); canvas.translate(-centerX, -centerY); } if (mAlpha != 1.0f) canvas.multiplyAlpha(mAlpha); } try { if (level != mLevelCount) { if (mScreenNail != null) { mScreenNail.noDraw(); } int size = (TILE_SIZE << level); float length = size * mScale; Rect r = mTileRange; for (int ty = r.top, i = 0; ty < r.bottom; ty += size, i++) { float y = mOffsetY + i * length; for (int tx = r.left, j = 0; tx < r.right; tx += size, j++) { float x = mOffsetX + j * length; drawTile(canvas, tx, ty, level, x, y, length); } } } else if (mScreenNail != null) { mScreenNail.draw(canvas, mOffsetX, mOffsetY, Math.round(mImageWidth * mScale), Math.round(mImageHeight * mScale)); } } finally { if (flags != 0) canvas.restore(); } if (mRenderComplete) { if (!mBackgroundTileUploaded) uploadBackgroundTiles(canvas); } else { invalidate(); } } private void uploadBackgroundTiles(GLCanvas canvas) { mBackgroundTileUploaded = true; int n = mActiveTiles.size(); for (int i = 0; i < n; i++) { Tile tile = mActiveTiles.valueAt(i); if (!tile.isContentValid(canvas)) queueForDecode(tile); } } void queueForUpload(Tile tile) { synchronized (this) { mUploadQueue.push(tile); } if (mTileUploader.mActive.compareAndSet(false, true)) { getGLRoot().addOnGLIdleListener(mTileUploader); } } synchronized void queueForDecode(Tile tile) { if (tile.mTileState == STATE_ACTIVATED) { tile.mTileState = STATE_IN_QUEUE; if (mDecodeQueue.push(tile)) notifyAll(); } } boolean decodeTile(Tile tile) { synchronized (this) { if (tile.mTileState != STATE_IN_QUEUE) return false; tile.mTileState = STATE_DECODING; } boolean decodeComplete = tile.decode(); synchronized (this) { if (tile.mTileState == STATE_RECYCLING) { tile.mTileState = STATE_RECYCLED; tile.mDecodedTile = null; mRecycledQueue.push(tile); return false; } tile.mTileState = decodeComplete ? STATE_DECODED : STATE_DECODE_FAIL; return decodeComplete; } } private synchronized Tile obtainTile(int x, int y, int level) { Tile tile = mRecycledQueue.pop(); if (tile != null) { tile.mTileState = STATE_ACTIVATED; tile.update(x, y, level); return tile; } return new Tile(x, y, level); } synchronized void recycleTile(Tile tile) { if (tile.mTileState == STATE_DECODING) { tile.mTileState = STATE_RECYCLING; return; } tile.mTileState = STATE_RECYCLED; tile.mDecodedTile = null; mRecycledQueue.push(tile); } private void activateTile(int x, int y, int level) { long key = makeTileKey(x, y, level); Tile tile = mActiveTiles.get(key); if (tile != null) { if (tile.mTileState == STATE_IN_QUEUE) { tile.mTileState = STATE_ACTIVATED; } return; } tile = obtainTile(x, y, level); mActiveTiles.put(key, tile); } private Tile getTile(int x, int y, int level) { return mActiveTiles.get(makeTileKey(x, y, level)); } private static long makeTileKey(int x, int y, int level) { long result = x; result = (result << 16) | y; result = (result << 16) | level; return result; } private class TileUploader implements GLRoot.OnGLIdleListener { AtomicBoolean mActive = new AtomicBoolean(false); @Override public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) { if (renderRequested) return false; int quota = UPLOAD_LIMIT; Tile tile; while (true) { synchronized (TileImageView.this) { tile = mUploadQueue.pop(); } if (tile == null || quota <= 0) break; if (!tile.isContentValid(canvas)) { Utils.assertTrue(tile.mTileState == STATE_DECODED); tile.updateContent(canvas); --quota; } } mActive.set(tile != null); return tile != null; } } // Draw the tile to a square at canvas that locates at (x, y) and // has a side length of length. public void drawTile(GLCanvas canvas, int tx, int ty, int level, float x, float y, float length) { RectF source = mSourceRect; RectF target = mTargetRect; target.set(x, y, x + length, y + length); source.set(0, 0, TILE_SIZE, TILE_SIZE); Tile tile = getTile(tx, ty, level); if (tile != null) { if (!tile.isContentValid(canvas)) { if (tile.mTileState == STATE_DECODED) { if (mUploadQuota > 0) { --mUploadQuota; tile.updateContent(canvas); } else { mRenderComplete = false; } } else if (tile.mTileState != STATE_DECODE_FAIL){ mRenderComplete = false; queueForDecode(tile); } } if (drawTile(tile, canvas, source, target)) return; } if (mScreenNail != null) { int size = TILE_SIZE << level; float scaleX = (float) mScreenNail.getWidth() / mImageWidth; float scaleY = (float) mScreenNail.getHeight() / mImageHeight; source.set(tx * scaleX, ty * scaleY, (tx + size) * scaleX, (ty + size) * scaleY); mScreenNail.draw(canvas, source, target); } } // TODO: avoid drawing the unused part of the textures. static boolean drawTile( Tile tile, GLCanvas canvas, RectF source, RectF target) { while (true) { if (tile.isContentValid(canvas)) { // offset source rectangle for the texture border. source.offset(TILE_BORDER, TILE_BORDER); canvas.drawTexture(tile, source, target); return true; } // Parent can be divided to four quads and tile is one of the four. Tile parent = tile.getParentTile(); if (parent == null) return false; if (tile.mX == parent.mX) { source.left /= 2f; source.right /= 2f; } else { source.left = (TILE_SIZE + source.left) / 2f; source.right = (TILE_SIZE + source.right) / 2f; } if (tile.mY == parent.mY) { source.top /= 2f; source.bottom /= 2f; } else { source.top = (TILE_SIZE + source.top) / 2f; source.bottom = (TILE_SIZE + source.bottom) / 2f; } tile = parent; } } private class Tile extends UploadedTexture { int mX; int mY; int mTileLevel; Tile mNext; Bitmap mDecodedTile; volatile int mTileState = STATE_ACTIVATED; public Tile(int x, int y, int level) { mX = x; mY = y; mTileLevel = level; } @Override protected void onFreeBitmap(Bitmap bitmap) { bitmap.recycle(); } boolean decode() { // Get a tile from the original image. The tile is down-scaled // by (1 << mTilelevel) from a region in the original image. try { mDecodedTile = DecodeUtils.ensureGLCompatibleBitmap(mModel.getTile( mTileLevel, mX, mY, TILE_SIZE, TILE_BORDER)); } catch (Throwable t) { Log.w(TAG, "fail to decode tile", t); } return mDecodedTile != null; } @Override protected Bitmap onGetBitmap() { Utils.assertTrue(mTileState == STATE_DECODED); Bitmap bitmap = mDecodedTile; mDecodedTile = null; mTileState = STATE_ACTIVATED; return bitmap; } // We override getTextureWidth() and getTextureHeight() here, so the // texture can be re-used for different tiles regardless of the actual // size of the tile (which may be small because it is a tile at the // boundary). @Override public int getTextureWidth() { return TILE_SIZE + TILE_BORDER * 2; } @Override public int getTextureHeight() { return TILE_SIZE + TILE_BORDER * 2; } public void update(int x, int y, int level) { mX = x; mY = y; mTileLevel = level; invalidateContent(); } public Tile getParentTile() { if (mTileLevel + 1 == mLevelCount) return null; int size = TILE_SIZE << (mTileLevel + 1); int x = size * (mX / size); int y = size * (mY / size); return getTile(x, y, mTileLevel + 1); } @Override public String toString() { return String.format("tile(%s, %s, %s / %s)", mX / TILE_SIZE, mY / TILE_SIZE, mLevel, mLevelCount); } } private static class TileQueue { private Tile mHead; public Tile pop() { Tile tile = mHead; if (tile != null) mHead = tile.mNext; return tile; } public boolean push(Tile tile) { boolean wasEmpty = mHead == null; tile.mNext = mHead; mHead = tile; return wasEmpty; } public void clean() { mHead = null; } } private class TileDecoder implements ThreadPool.Job<Void> { private CancelListener mNotifier = new CancelListener() { @Override public void onCancel() { synchronized (TileImageView.this) { TileImageView.this.notifyAll(); } } }; @Override public Void run(JobContext jc) { jc.setMode(ThreadPool.MODE_NONE); jc.setCancelListener(mNotifier); while (!jc.isCancelled()) { Tile tile = null; synchronized(TileImageView.this) { tile = mDecodeQueue.pop(); if (tile == null && !jc.isCancelled()) { Utils.waitWithoutInterrupt(TileImageView.this); } } if (tile == null) continue; if (decodeTile(tile)) queueForUpload(tile); } return null; } } }
false
true
private void layoutTiles(int centerX, int centerY, float scale, int rotation) { // The width and height of this view. int width = getWidth(); int height = getHeight(); // The tile levels we want to keep as texture is in the range // [fromLevel, endLevel). int fromLevel; int endLevel; // We want to use a texture larger than or equal to the display size. mLevel = Utils.clamp(Utils.floorLog2(1f / scale), 0, mLevelCount); // We want to keep one more tile level as texture in addition to what // we use for display. So it can be faster when the scale moves to the // next level. We choose a level closer to the current scale. if (mLevel != mLevelCount) { Rect range = mTileRange; getRange(range, centerX, centerY, mLevel, scale, rotation); mOffsetX = Math.round(width / 2f + (range.left - centerX) * scale); mOffsetY = Math.round(height / 2f + (range.top - centerY) * scale); fromLevel = scale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel; } else { // Activate the tiles of the smallest two levels. fromLevel = mLevel - 2; mOffsetX = Math.round(width / 2f - centerX * scale); mOffsetY = Math.round(height / 2f - centerY * scale); } fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2)); endLevel = Math.min(fromLevel + 2, mLevelCount); Rect range[] = mActiveRange; for (int i = fromLevel; i < endLevel; ++i) { getRange(range[i - fromLevel], centerX, centerY, i, rotation); } // If rotation is transient, don't update the tile. if (rotation % 90 != 0) return; synchronized (this) { mDecodeQueue.clean(); mUploadQueue.clean(); mBackgroundTileUploaded = false; } // Recycle unused tiles: if the level of the active tile is outside the // range [fromLevel, endLevel) or not in the visible range. int n = mActiveTiles.size(); for (int i = 0; i < n; i++) { Tile tile = mActiveTiles.valueAt(i); int level = tile.mTileLevel; if (level < fromLevel || level >= endLevel || !range[level - fromLevel].contains(tile.mX, tile.mY)) { mActiveTiles.removeAt(i); i--; n--; recycleTile(tile); } } for (int i = fromLevel; i < endLevel; ++i) { int size = TILE_SIZE << i; Rect r = range[i - fromLevel]; for (int y = r.top, bottom = r.bottom; y < bottom; y += size) { for (int x = r.left, right = r.right; x < right; x += size) { activateTile(x, y, i); } } } invalidate(); }
private void layoutTiles(int centerX, int centerY, float scale, int rotation) { // The width and height of this view. int width = getWidth(); int height = getHeight(); // The tile levels we want to keep as texture is in the range // [fromLevel, endLevel). int fromLevel; int endLevel; // We want to use a texture larger than or equal to the display size. mLevel = Utils.clamp(Utils.floorLog2(1f / scale), 0, mLevelCount); // We want to keep one more tile level as texture in addition to what // we use for display. So it can be faster when the scale moves to the // next level. We choose a level closer to the current scale. if (mLevel != mLevelCount) { Rect range = mTileRange; getRange(range, centerX, centerY, mLevel, scale, rotation); mOffsetX = Math.round(width / 2f + (range.left - centerX) * scale); mOffsetY = Math.round(height / 2f + (range.top - centerY) * scale); fromLevel = scale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel; } else { // Activate the tiles of the smallest two levels. fromLevel = mLevel - 2; mOffsetX = Math.round(width / 2f - centerX * scale); mOffsetY = Math.round(height / 2f - centerY * scale); } fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2)); endLevel = Math.min(fromLevel + 2, mLevelCount); Rect range[] = mActiveRange; for (int i = fromLevel; i < endLevel; ++i) { getRange(range[i - fromLevel], centerX, centerY, i, rotation); } // If rotation is transient, don't update the tile. if (rotation % 90 != 0) return; synchronized (this) { mDecodeQueue.clean(); mUploadQueue.clean(); mBackgroundTileUploaded = false; // Recycle unused tiles: if the level of the active tile is outside the // range [fromLevel, endLevel) or not in the visible range. int n = mActiveTiles.size(); for (int i = 0; i < n; i++) { Tile tile = mActiveTiles.valueAt(i); int level = tile.mTileLevel; if (level < fromLevel || level >= endLevel || !range[level - fromLevel].contains(tile.mX, tile.mY)) { mActiveTiles.removeAt(i); i--; n--; recycleTile(tile); } } } for (int i = fromLevel; i < endLevel; ++i) { int size = TILE_SIZE << i; Rect r = range[i - fromLevel]; for (int y = r.top, bottom = r.bottom; y < bottom; y += size) { for (int x = r.left, right = r.right; x < right; x += size) { activateTile(x, y, i); } } } invalidate(); }
diff --git a/dspace/src/org/dspace/app/webui/servlet/CommunityListServlet.java b/dspace/src/org/dspace/app/webui/servlet/CommunityListServlet.java index 32a190cc6..21e7cc2cf 100644 --- a/dspace/src/org/dspace/app/webui/servlet/CommunityListServlet.java +++ b/dspace/src/org/dspace/app/webui/servlet/CommunityListServlet.java @@ -1,95 +1,95 @@ /* * CommunityListServlet.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2001, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.JSPManager; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.core.Context; import org.dspace.core.LogManager; /** * Servlet for listing communities (and collections within them) * * @author Robert Tansley * @version $Revision$ */ public class CommunityListServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(DSpaceServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { log.info(LogManager.getHeader(context, "view_community_list", "")); // This will map community IDs to arrays of collections Map colMap = new HashMap(); Community[] communities = Community.findAll(context); for (int com = 0; com < communities.length; com++) { Integer comID = new Integer(communities[com].getID()); colMap.put(comID, communities[com].getCollections()); } request.setAttribute("communities", communities); - request.setAttribute("collection.map", colMap); + request.setAttribute("collections.map", colMap); JSPManager.showJSP(request, response, "/community-list.jsp"); } }
true
true
protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { log.info(LogManager.getHeader(context, "view_community_list", "")); // This will map community IDs to arrays of collections Map colMap = new HashMap(); Community[] communities = Community.findAll(context); for (int com = 0; com < communities.length; com++) { Integer comID = new Integer(communities[com].getID()); colMap.put(comID, communities[com].getCollections()); } request.setAttribute("communities", communities); request.setAttribute("collection.map", colMap); JSPManager.showJSP(request, response, "/community-list.jsp"); }
protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { log.info(LogManager.getHeader(context, "view_community_list", "")); // This will map community IDs to arrays of collections Map colMap = new HashMap(); Community[] communities = Community.findAll(context); for (int com = 0; com < communities.length; com++) { Integer comID = new Integer(communities[com].getID()); colMap.put(comID, communities[com].getCollections()); } request.setAttribute("communities", communities); request.setAttribute("collections.map", colMap); JSPManager.showJSP(request, response, "/community-list.jsp"); }
diff --git a/src/main/java/com/danhaywood/isis/wicket/ui/components/collectioncontents/fullcalendar/CollectionContentsAsFullCalendar.java b/src/main/java/com/danhaywood/isis/wicket/ui/components/collectioncontents/fullcalendar/CollectionContentsAsFullCalendar.java index 247a837..ffa807c 100644 --- a/src/main/java/com/danhaywood/isis/wicket/ui/components/collectioncontents/fullcalendar/CollectionContentsAsFullCalendar.java +++ b/src/main/java/com/danhaywood/isis/wicket/ui/components/collectioncontents/fullcalendar/CollectionContentsAsFullCalendar.java @@ -1,110 +1,109 @@ /* * 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 com.danhaywood.isis.wicket.ui.components.collectioncontents.fullcalendar; import java.util.List; import net.ftlines.wicket.fullcalendar.Config; import net.ftlines.wicket.fullcalendar.EventSource; import net.ftlines.wicket.fullcalendar.FullCalendar; import net.ftlines.wicket.fullcalendar.selector.EventSourceSelector; import org.apache.isis.core.metamodel.spec.ObjectSpecification; import org.apache.isis.core.metamodel.spec.feature.ObjectAssociation; import org.apache.isis.viewer.wicket.model.models.EntityCollectionModel; import org.apache.isis.viewer.wicket.ui.panels.PanelAbstract; import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxFallbackDefaultDataTable; import org.apache.wicket.markup.html.panel.FeedbackPanel; /** * {@link PanelAbstract Panel} that represents a {@link EntityCollectionModel * collection of entity}s rendered using {@link AjaxFallbackDefaultDataTable}. */ public class CollectionContentsAsFullCalendar extends PanelAbstract<EntityCollectionModel> { private static final long serialVersionUID = 1L; private static final String ID_SELECTOR = "selector"; private static final String ID_FULL_CALENDAR = "fullCalendar"; private static final String ID_FEEDBACK = "feedback"; private final static String[] COLORS = { "#63BA68", "#B1ADAC", "#E6CC7F" }; public CollectionContentsAsFullCalendar(final String id, final EntityCollectionModel model) { super(id, model); buildGui(); } private void buildGui() { final EntityCollectionModel model = getModel(); final ObjectSpecification elementSpec = model.getTypeOfSpecification(); final FeedbackPanel feedback = new FeedbackPanel(ID_FEEDBACK); feedback.setOutputMarkupId(true); addOrReplace(feedback); final Config config = new Config(); config.setSelectable(true); config.setSelectHelper(false); List<ObjectAssociation> dateAssociations = elementSpec.getAssociations(CollectionContentsAsFullCalendarFactory.OF_TYPE_DATE); int i=0; for (ObjectAssociation dateAssociation : dateAssociations) { final EventSource association = new EventSource(); association.setTitle(dateAssociation.getName()); association.setEventsProvider(new DateAssociationEventsProvider(model, dateAssociation)); association.setEditable(true); String color = COLORS[i++ % COLORS.length]; association.setBackgroundColor(color); association.setBorderColor(color); config.add(association); } config.setAspectRatio(2.5f); config.getHeader().setLeft("prevYear,prev,next,nextYear, today"); config.getHeader().setCenter("title"); config.getHeader().setRight(""); config.setLoading("function(bool) { if (bool) $(\"#loading\").show(); else $(\"#loading\").hide(); }"); config.setAllDaySlot(true); final FullCalendar calendar = new FullCalendarWithEventHandling(ID_FULL_CALENDAR, config, feedback); - calendar.setMarkupId(ID_FULL_CALENDAR); addOrReplace(calendar); addOrReplace(new EventSourceSelector(ID_SELECTOR, calendar)); } @Override protected void onModelChanged() { buildGui(); } }
true
true
private void buildGui() { final EntityCollectionModel model = getModel(); final ObjectSpecification elementSpec = model.getTypeOfSpecification(); final FeedbackPanel feedback = new FeedbackPanel(ID_FEEDBACK); feedback.setOutputMarkupId(true); addOrReplace(feedback); final Config config = new Config(); config.setSelectable(true); config.setSelectHelper(false); List<ObjectAssociation> dateAssociations = elementSpec.getAssociations(CollectionContentsAsFullCalendarFactory.OF_TYPE_DATE); int i=0; for (ObjectAssociation dateAssociation : dateAssociations) { final EventSource association = new EventSource(); association.setTitle(dateAssociation.getName()); association.setEventsProvider(new DateAssociationEventsProvider(model, dateAssociation)); association.setEditable(true); String color = COLORS[i++ % COLORS.length]; association.setBackgroundColor(color); association.setBorderColor(color); config.add(association); } config.setAspectRatio(2.5f); config.getHeader().setLeft("prevYear,prev,next,nextYear, today"); config.getHeader().setCenter("title"); config.getHeader().setRight(""); config.setLoading("function(bool) { if (bool) $(\"#loading\").show(); else $(\"#loading\").hide(); }"); config.setAllDaySlot(true); final FullCalendar calendar = new FullCalendarWithEventHandling(ID_FULL_CALENDAR, config, feedback); calendar.setMarkupId(ID_FULL_CALENDAR); addOrReplace(calendar); addOrReplace(new EventSourceSelector(ID_SELECTOR, calendar)); }
private void buildGui() { final EntityCollectionModel model = getModel(); final ObjectSpecification elementSpec = model.getTypeOfSpecification(); final FeedbackPanel feedback = new FeedbackPanel(ID_FEEDBACK); feedback.setOutputMarkupId(true); addOrReplace(feedback); final Config config = new Config(); config.setSelectable(true); config.setSelectHelper(false); List<ObjectAssociation> dateAssociations = elementSpec.getAssociations(CollectionContentsAsFullCalendarFactory.OF_TYPE_DATE); int i=0; for (ObjectAssociation dateAssociation : dateAssociations) { final EventSource association = new EventSource(); association.setTitle(dateAssociation.getName()); association.setEventsProvider(new DateAssociationEventsProvider(model, dateAssociation)); association.setEditable(true); String color = COLORS[i++ % COLORS.length]; association.setBackgroundColor(color); association.setBorderColor(color); config.add(association); } config.setAspectRatio(2.5f); config.getHeader().setLeft("prevYear,prev,next,nextYear, today"); config.getHeader().setCenter("title"); config.getHeader().setRight(""); config.setLoading("function(bool) { if (bool) $(\"#loading\").show(); else $(\"#loading\").hide(); }"); config.setAllDaySlot(true); final FullCalendar calendar = new FullCalendarWithEventHandling(ID_FULL_CALENDAR, config, feedback); addOrReplace(calendar); addOrReplace(new EventSourceSelector(ID_SELECTOR, calendar)); }
diff --git a/c/YetiBuiltins.java b/c/YetiBuiltins.java index c0e5fcb..deb89e6 100644 --- a/c/YetiBuiltins.java +++ b/c/YetiBuiltins.java @@ -1,1218 +1,1218 @@ // ex: se sts=4 sw=4 expandtab: /* * Yeti language compiler java bytecode generator. * * Copyright (c) 2007,2008,2009 Madis Janson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package yeti.lang.compiler; import org.objectweb.asm.*; import java.util.*; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; final class BuiltIn implements Binder { int op; public BuiltIn(int op) { this.op = op; } public BindRef getRef(int line) { BindRef r = null; switch (op) { case 1: r = new Argv(); r.type = YetiType.STRING_ARRAY; break; case 2: r = new InOpFun(line); break; case 3: r = new Cons(line); break; case 4: r = new LazyCons(line); break; case 5: r = new For(line); break; case 6: r = new Compose(line); break; case 7: r = new Synchronized(line); break; case 8: - r = new IsNullPtr(YetiType.A_TO_BOOL, "nullptr?", line); + r = new IsNullPtr(YetiType.A_TO_BOOL, "nullptr$q", line); break; case 9: r = new IsDefined(line); break; case 10: r = new IsEmpty(line); break; case 11: r = new Head(line); break; case 12: r = new Tail(line); break; case 13: r = new MatchOpFun(line, true); break; case 14: r = new MatchOpFun(line, false); break; case 15: r = new NotOp(line); break; case 16: r = new StrChar(line); break; case 17: r = new UnitConstant(YetiType.BOOL_TYPE); break; case 18: r = new BooleanConstant(false); break; case 19: r = new BooleanConstant(true); break; case 20: r = new Negate(); break; case 21: r = new Same(); break; case 22: r = new StaticRef("yeti/lang/Core", "RANDINT", YetiType.NUM_TO_NUM, this, true, line); break; case 23: r = new StaticRef("yeti/lang/Core", "UNDEF_STR", YetiType.STR_TYPE, this, true, line); break; case 24: r = new Escape(line); break; } r.binder = this; return r; } } final class Argv extends BindRef { void gen(Ctx ctx) { ctx.visitFieldInsn(GETSTATIC, "yeti/lang/Core", "ARGV", "Ljava/lang/ThreadLocal;"); ctx.visitMethodInsn(INVOKEVIRTUAL, "java/lang/ThreadLocal", "get", "()Ljava/lang/Object;"); } Code assign(final Code value) { return new Code() { void gen(Ctx ctx) { ctx.visitFieldInsn(GETSTATIC, "yeti/lang/Core", "ARGV", "Ljava/lang/ThreadLocal;"); value.gen(ctx); ctx.visitMethodInsn(INVOKEVIRTUAL, "java/lang/ThreadLocal", "get", "(Ljava/lang/Object;)V"); ctx.visitInsn(ACONST_NULL); } }; } boolean flagop(int fl) { return (fl & (ASSIGN | DIRECT_BIND)) != 0; } } class IsNullPtr extends StaticRef { private String libName; boolean normalIf; IsNullPtr(YetiType.Type type, String fun, int line) { super("yeti/lang/std$" + fun, "_", type, null, true, line); } Code apply(final Code arg, final YetiType.Type res, final int line) { return new Code() { { type = res; } void gen(Ctx ctx) { IsNullPtr.this.gen(ctx, arg, line); } void genIf(Ctx ctx, Label to, boolean ifTrue) { if (normalIf) { super.genIf(ctx, to, ifTrue); } else { IsNullPtr.this.genIf(ctx, arg, to, ifTrue, line); } } }; } void gen(Ctx ctx, Code arg, int line) { Label label = new Label(); genIf(ctx, arg, label, false, line); ctx.genBoolean(label); } void genIf(Ctx ctx, Code arg, Label to, boolean ifTrue, int line) { arg.gen(ctx); ctx.visitJumpInsn(ifTrue ? IFNULL : IFNONNULL, to); } } final class IsDefined extends IsNullPtr { IsDefined(int line) { super(YetiType.A_TO_BOOL, "defined$q", line); } void genIf(Ctx ctx, Code arg, Label to, boolean ifTrue, int line) { Label isNull = new Label(), end = new Label(); arg.gen(ctx); ctx.visitInsn(DUP); ctx.visitJumpInsn(IFNULL, isNull); ctx.visitFieldInsn(GETSTATIC, "yeti/lang/Core", "UNDEF_STR", "Ljava/lang/String;"); ctx.visitJumpInsn(IF_ACMPEQ, ifTrue ? end : to); ctx.visitJumpInsn(GOTO, ifTrue ? to : end); ctx.visitLabel(isNull); ctx.visitInsn(POP); if (!ifTrue) { ctx.visitJumpInsn(GOTO, to); } ctx.visitLabel(end); } } final class IsEmpty extends IsNullPtr { IsEmpty(int line) { super(YetiType.MAP_TO_BOOL, "empty$q", line); } void genIf(Ctx ctx, Code arg, Label to, boolean ifTrue, int line) { Label isNull = new Label(), end = new Label(); arg.gen(ctx); ctx.visitLine(line); ctx.visitInsn(DUP); ctx.visitJumpInsn(IFNULL, isNull); if (ctx.compilation.isGCJ) ctx.visitTypeInsn(CHECKCAST, "yeti/lang/Coll"); ctx.visitMethodInsn(INVOKEINTERFACE, "yeti/lang/Coll", "isEmpty", "()Z"); ctx.visitJumpInsn(IFNE, ifTrue ? to : end); ctx.visitJumpInsn(GOTO, ifTrue ? end : to); ctx.visitLabel(isNull); ctx.visitInsn(POP); if (ifTrue) { ctx.visitJumpInsn(GOTO, to); } ctx.visitLabel(end); } } final class Head extends IsNullPtr { Head(int line) { super(YetiType.LIST_TO_A, "head", line); } void gen(Ctx ctx, Code arg, int line) { arg.gen(ctx); ctx.visitLine(line); ctx.visitTypeInsn(CHECKCAST, "yeti/lang/AList"); ctx.visitMethodInsn(INVOKEVIRTUAL, "yeti/lang/AList", "first", "()Ljava/lang/Object;"); } } final class Tail extends IsNullPtr { Tail(int line) { super(YetiType.LIST_TO_LIST, "tail", line); } void gen(Ctx ctx, Code arg, int line) { arg.gen(ctx); ctx.visitLine(line); ctx.visitTypeInsn(CHECKCAST, "yeti/lang/AList"); ctx.visitInsn(DUP); Label end = new Label(); ctx.visitJumpInsn(IFNULL, end); ctx.visitMethodInsn(INVOKEVIRTUAL, "yeti/lang/AList", "rest", "()Lyeti/lang/AList;"); ctx.visitLabel(end); ctx.forceType("yeti/lang/AList"); } } final class Escape extends IsNullPtr { Escape(int line) { super(YetiType.WITH_EXIT_TYPE, "withExit", line); normalIf = true; } void gen(Ctx ctx, Code block, int line) { block.gen(ctx); ctx.visitTypeInsn(CHECKCAST, "yeti/lang/Fun"); ctx.visitMethodInsn(INVOKESTATIC, "yeti/lang/EscapeFun", "with", "(Lyeti/lang/Fun;)Ljava/lang/Object;"); } } final class Negate extends StaticRef { Negate() { super("yeti/lang/std$negate", "_", YetiType.NUM_TO_NUM, null, false, 0); } Code apply(final Code arg1, final YetiType.Type res1, final int line) { if (arg1 instanceof NumericConstant) { return new NumericConstant(((NumericConstant) arg1) .num.subFrom(0)); } return new Code() { { type = YetiType.NUM_TYPE; } void gen(Ctx ctx) { arg1.gen(ctx); ctx.visitLine(line); ctx.visitTypeInsn(CHECKCAST, "yeti/lang/Num"); ctx.visitLdcInsn(new Long(0)); ctx.visitMethodInsn(INVOKEVIRTUAL, "yeti/lang/Num", "subFrom", "(J)Lyeti/lang/Num;"); ctx.forceType("yeti/lang/Num"); } }; } } abstract class Core2 extends StaticRef { boolean derivePolymorph; Core2(String coreFun, YetiType.Type type, int line) { super("yeti/lang/std$" + coreFun, "_", type, null, true, line); } Code apply(final Code arg1, YetiType.Type res, int line1) { return new Apply(res, this, arg1, line1) { Code apply(final Code arg2, final YetiType.Type res, final int line2) { return new Code() { { type = res; polymorph = derivePolymorph && arg1.polymorph && arg2.polymorph; } void gen(Ctx ctx) { genApply2(ctx, arg1, arg2, line2); } }; } }; } abstract void genApply2(Ctx ctx, Code arg1, Code arg2, int line); } final class For extends Core2 { For(int line) { super("for", YetiType.FOR_TYPE, line); } void genApply2(Ctx ctx, Code list, Code fun, int line) { Function f; LoadVar arg = new LoadVar(); if (!list.flagop(LIST_RANGE) && fun instanceof Function && (f = (Function) fun).uncapture(arg)) { Label retry = new Label(), end = new Label(); list.gen(ctx); ctx.visitLine(line); ctx.visitTypeInsn(CHECKCAST, "yeti/lang/AList"); ctx.visitInsn(DUP); ctx.visitJumpInsn(IFNULL, end); ctx.visitInsn(DUP); ctx.visitMethodInsn(INVOKEVIRTUAL, "yeti/lang/AList", "isEmpty", "()Z"); ctx.visitJumpInsn(IFNE, end); // start of loop ctx.visitLabel(retry); ctx.visitInsn(DUP); ctx.visitMethodInsn(INVOKEVIRTUAL, "yeti/lang/AIter", "first", "()Ljava/lang/Object;"); // invoke body block ctx.visitVarInsn(ASTORE, arg.var = ctx.localVarCount++); ++ctx.tainted; // disable argument-nulling - we're in cycle f.body.gen(ctx); --ctx.tainted; ctx.visitLine(line); ctx.visitInsn(POP); // ignore return value // next ctx.visitMethodInsn(INVOKEVIRTUAL, "yeti/lang/AIter", "next", "()Lyeti/lang/AIter;"); ctx.visitInsn(DUP); ctx.visitJumpInsn(IFNONNULL, retry); ctx.visitLabel(end); } else { Label nop = new Label(), end = new Label(); list.gen(ctx); fun.gen(ctx); ctx.visitLine(line); ctx.visitInsn(SWAP); ctx.visitTypeInsn(CHECKCAST, "yeti/lang/AList"); ctx.visitInsn(DUP_X1); ctx.visitJumpInsn(IFNULL, nop); ctx.visitMethodInsn(INVOKEVIRTUAL, "yeti/lang/AList", "forEach", "(Ljava/lang/Object;)V"); ctx.visitJumpInsn(GOTO, end); ctx.visitLabel(nop); ctx.visitInsn(POP2); ctx.visitLabel(end); ctx.visitInsn(ACONST_NULL); } } } final class Compose extends Core2 { Compose(int line) { super("$d", YetiType.COMPOSE_TYPE, line); derivePolymorph = true; } void genApply2(Ctx ctx, Code arg1, Code arg2, int line) { ctx.visitTypeInsn(NEW, "yeti/lang/Compose"); ctx.visitInsn(DUP); arg1.gen(ctx); arg2.gen(ctx); ctx.visitLine(line); ctx.visitInit("yeti/lang/Compose", "(Ljava/lang/Object;Ljava/lang/Object;)V"); } } final class Synchronized extends Core2 { Synchronized(int line) { super("synchronized", YetiType.SYNCHRONIZED_TYPE, line); } void genApply2(Ctx ctx, Code monitor, Code block, int line) { monitor.gen(ctx); int monitorVar = ctx.localVarCount++; ctx.visitLine(line); ctx.visitInsn(DUP); ctx.visitVarInsn(ASTORE, monitorVar); ctx.visitInsn(MONITORENTER); Label startBlock = new Label(), endBlock = new Label(); ctx.visitLabel(startBlock); new Apply(type, block, new UnitConstant(null), line).gen(ctx); ctx.visitLine(line); ctx.visitVarInsn(ALOAD, monitorVar); ctx.visitInsn(MONITOREXIT); ctx.visitLabel(endBlock); Label end = new Label(); ctx.visitJumpInsn(GOTO, end); Label startCleanup = new Label(), endCleanup = new Label(); ctx.visitTryCatchBlock(startBlock, endBlock, startCleanup, null); // I have no fucking idea, what this second catch is supposed // to be doing. javac generates it, so it has to be good. // yeah, sure... ctx.visitTryCatchBlock(startCleanup, endCleanup, startCleanup, null); int exceptionVar = ctx.localVarCount++; ctx.visitLabel(startCleanup); ctx.visitVarInsn(ASTORE, exceptionVar); ctx.visitVarInsn(ALOAD, monitorVar); ctx.visitInsn(MONITOREXIT); ctx.visitLabel(endCleanup); ctx.visitVarInsn(ALOAD, exceptionVar); ctx.visitInsn(ATHROW); ctx.visitLabel(end); } } abstract class BinOpRef extends BindRef { boolean markTail2; String coreFun; class Result extends Code { private Code arg1; private Code arg2; Result(Code arg1, Code arg2, YetiType.Type res) { type = res; this.arg1 = arg1; this.arg2 = arg2; } void gen(Ctx ctx) { binGen(ctx, arg1, arg2); } void genIf(Ctx ctx, Label to, boolean ifTrue) { binGenIf(ctx, arg1, arg2, to, ifTrue); } void markTail() { if (markTail2) { arg2.markTail(); } } } Code apply(final Code arg1, final YetiType.Type res1, final int line) { return new Code() { { type = res1; } Code apply(Code arg2, YetiType.Type res, int line) { return new Result(arg1, arg2, res); } void gen(Ctx ctx) { BinOpRef.this.gen(ctx); ctx.visitApply(arg1, line); } }; } void gen(Ctx ctx) { ctx.visitFieldInsn(GETSTATIC, "yeti/lang/std$" + coreFun, "_", "Lyeti/lang/Fun;"); } abstract void binGen(Ctx ctx, Code arg1, Code arg2); void binGenIf(Ctx ctx, Code arg1, Code arg2, Label to, boolean ifTrue) { throw new UnsupportedOperationException("binGenIf"); } boolean flagop(int fl) { return (fl & STD_CONST) != 0; } } final class ArithOpFun extends BinOpRef { private String method; private int line; public ArithOpFun(String fun, String method, YetiType.Type type, Binder binder, int line) { this.type = type; this.method = method; coreFun = fun; this.binder = binder; this.line = line; } public BindRef getRef(int line) { return this; // XXX should copy for type? } void binGen(Ctx ctx, Code arg1, Code arg2) { if (method == "and" && arg2 instanceof NumericConstant && ((NumericConstant) arg2).flagop(INT_NUM)) { ctx.visitTypeInsn(NEW, "yeti/lang/IntNum"); ctx.visitInsn(DUP); arg1.gen(ctx); ctx.visitLine(line); ctx.visitTypeInsn(CHECKCAST, "yeti/lang/Num"); ctx.visitMethodInsn(INVOKEVIRTUAL, "yeti/lang/Num", "longValue", "()J"); ((NumericConstant) arg2).genInt(ctx, false); ctx.visitInsn(LAND); ctx.visitInit("yeti/lang/IntNum", "(J)V"); ctx.forceType("yeti/lang/Num"); return; } arg1.gen(ctx); ctx.visitLine(line); ctx.visitTypeInsn(CHECKCAST, "yeti/lang/Num"); boolean ii = method == "intDiv" || method == "rem"; if (method == "shl" || method == "shr") { ctx.genInt(arg2, line); if (method == "shr") ctx.visitInsn(INEG); ctx.visitMethodInsn(INVOKEVIRTUAL, "yeti/lang/Num", "shl", "(I)Lyeti/lang/Num;"); } else if (arg2 instanceof NumericConstant && ((NumericConstant) arg2).genInt(ctx, ii)) { ctx.visitLine(line); ctx.visitMethodInsn(INVOKEVIRTUAL, "yeti/lang/Num", method, ii ? "(I)Lyeti/lang/Num;" : "(J)Lyeti/lang/Num;"); ctx.forceType("yeti/lang/Num"); } else { arg2.gen(ctx); ctx.visitLine(line); ctx.visitTypeInsn(CHECKCAST, "yeti/lang/Num"); ctx.visitMethodInsn(INVOKEVIRTUAL, "yeti/lang/Num", method, "(Lyeti/lang/Num;)Lyeti/lang/Num;"); } ctx.forceType("yeti/lang/Num"); } } final class ArithOp implements Binder { private String fun; private String method; private YetiType.Type type; ArithOp(String op, String method, YetiType.Type type) { fun = op == "+" ? "plus" : Code.mangle(op); this.method = method; this.type = type; } public BindRef getRef(int line) { return new ArithOpFun(fun, method, type, this, line); } } abstract class BoolBinOp extends BinOpRef { void binGen(Ctx ctx, Code arg1, Code arg2) { Label label = new Label(); binGenIf(ctx, arg1, arg2, label, false); ctx.genBoolean(label); } } final class CompareFun extends BoolBinOp { static final int COND_EQ = 0; static final int COND_NOT = 1; static final int COND_LT = 2; static final int COND_GT = 4; static final int COND_LE = COND_NOT | COND_GT; static final int COND_GE = COND_NOT | COND_LT; static final int[] OPS = { IFEQ, IFNE, IFLT, IFGE, IFGT, IFLE }; static final int[] ROP = { IFEQ, IFNE, IFGT, IFLE, IFLT, IFGE }; int op; int line; void binGenIf(Ctx ctx, Code arg1, Code arg2, Label to, boolean ifTrue) { YetiType.Type t = arg1.type.deref(); int op = this.op; boolean eq = (op & (COND_LT | COND_GT)) == 0; if (!ifTrue) { op ^= COND_NOT; } Label nojmp = null; if (t.type == YetiType.VAR || t.type == YetiType.MAP && t.param[2] == YetiType.LIST_TYPE && t.param[1].type != YetiType.NUM) { Label nonull = new Label(); nojmp = new Label(); arg2.gen(ctx); arg1.gen(ctx); // 2-1 ctx.visitLine(line); ctx.visitInsn(DUP); // 2-1-1 ctx.visitJumpInsn(IFNONNULL, nonull); // 2-1 // reach here, when 1 was null if (op == COND_GT || op == COND_LE || arg2.flagop(EMPTY_LIST) && (op == COND_EQ || op == COND_NOT)) { // null is never greater and always less or equal ctx.visitInsn(POP2); ctx.visitJumpInsn(GOTO, op == COND_LE || op == COND_EQ ? to : nojmp); } else { ctx.visitInsn(POP); // 2 ctx.visitJumpInsn(op == COND_EQ || op == COND_GE ? IFNULL : IFNONNULL, to); ctx.visitJumpInsn(GOTO, nojmp); } ctx.visitLabel(nonull); if (!eq && ctx.compilation.isGCJ) ctx.visitTypeInsn(CHECKCAST, "java/lang/Comparable"); ctx.visitInsn(SWAP); // 1-2 } else { arg1.gen(ctx); ctx.visitLine(line); if (arg2.flagop(INT_NUM)) { ctx.visitTypeInsn(CHECKCAST, "yeti/lang/Num"); ((NumericConstant) arg2).genInt(ctx, false); ctx.visitLine(line); ctx.visitMethodInsn(INVOKEVIRTUAL, "yeti/lang/Num", "rCompare", "(J)I"); ctx.visitJumpInsn(ROP[op], to); return; } if (!eq && ctx.compilation.isGCJ) ctx.visitTypeInsn(CHECKCAST, "java/lang/Comparable"); arg2.gen(ctx); ctx.visitLine(line); } if (eq) { op ^= COND_NOT; ctx.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z"); } else { ctx.visitMethodInsn(INVOKEINTERFACE, "java/lang/Comparable", "compareTo", "(Ljava/lang/Object;)I"); } ctx.visitJumpInsn(OPS[op], to); if (nojmp != null) { ctx.visitLabel(nojmp); } } } final class Compare implements Binder { YetiType.Type type; int op; String fun; public Compare(YetiType.Type type, int op, String fun) { this.op = op; this.type = type; this.fun = Code.mangle(fun); } public BindRef getRef(int line) { CompareFun c = new CompareFun(); c.binder = this; c.type = type; c.op = op; c.polymorph = true; c.line = line; c.coreFun = fun; return c; } } final class Same extends BoolBinOp { Same() { type = YetiType.EQ_TYPE; polymorph = true; coreFun = "same$q"; } void binGenIf(Ctx ctx, Code arg1, Code arg2, Label to, boolean ifTrue) { arg1.gen(ctx); arg2.gen(ctx); ctx.visitJumpInsn(ifTrue ? IF_ACMPEQ : IF_ACMPNE, to); } } final class InOpFun extends BoolBinOp { int line; InOpFun(int line) { type = YetiType.IN_TYPE; this.line = line; polymorph = true; coreFun = "in"; } void binGenIf(Ctx ctx, Code arg1, Code arg2, Label to, boolean ifTrue) { arg2.gen(ctx); ctx.visitLine(line); if (ctx.compilation.isGCJ) { ctx.visitTypeInsn(CHECKCAST, "yeti/lang/ByKey"); } arg1.gen(ctx); ctx.visitLine(line); ctx.visitMethodInsn(INVOKEINTERFACE, "yeti/lang/ByKey", "containsKey", "(Ljava/lang/Object;)Z"); ctx.visitJumpInsn(ifTrue ? IFNE : IFEQ, to); } } final class NotOp extends StaticRef { NotOp(int line) { super("yeti/lang/std$not", "_", YetiType.BOOL_TO_BOOL, null, false, line); } Code apply(final Code arg, YetiType.Type res, int line) { return new Code() { { type = YetiType.BOOL_TYPE; } void genIf(Ctx ctx, Label to, boolean ifTrue) { arg.genIf(ctx, to, !ifTrue); } void gen(Ctx ctx) { Label label = new Label(); arg.genIf(ctx, label, true); ctx.genBoolean(label); } }; } } final class BoolOpFun extends BoolBinOp implements Binder { boolean orOp; BoolOpFun(boolean orOp) { this.type = YetiType.BOOLOP_TYPE; this.orOp = orOp; this.binder = this; markTail2 = true; coreFun = orOp ? "or" : "and"; } public BindRef getRef(int line) { return this; } void binGen(Ctx ctx, Code arg1, Code arg2) { if (arg2 instanceof CompareFun) { super.binGen(ctx, arg1, arg2); } else { Label label = new Label(), end = new Label(); arg1.genIf(ctx, label, orOp); arg2.gen(ctx); ctx.visitJumpInsn(GOTO, end); ctx.visitLabel(label); ctx.visitFieldInsn(GETSTATIC, "java/lang/Boolean", orOp ? "TRUE" : "FALSE", "Ljava/lang/Boolean;"); ctx.visitLabel(end); } } void binGenIf(Ctx ctx, Code arg1, Code arg2, Label to, boolean ifTrue) { if (orOp == ifTrue) { arg1.genIf(ctx, to, orOp); arg2.genIf(ctx, to, orOp); } else { Label noJmp = new Label(); arg1.genIf(ctx, noJmp, orOp); arg2.genIf(ctx, to, !orOp); ctx.visitLabel(noJmp); } } } final class Cons extends BinOpRef { private int line; Cons(int line) { type = YetiType.CONS_TYPE; coreFun = "$c$c"; polymorph = true; this.line = line; } void binGen(Ctx ctx, Code arg1, Code arg2) { String lclass = "yeti/lang/LList"; if (arg2.type.deref().param[1].deref() != YetiType.NO_TYPE) { lclass = "yeti/lang/LMList"; } ctx.visitLine(line); ctx.visitTypeInsn(NEW, lclass); ctx.visitInsn(DUP); arg1.gen(ctx); arg2.gen(ctx); ctx.visitLine(line); ctx.visitTypeInsn(CHECKCAST, "yeti/lang/AList"); ctx.visitInit(lclass, "(Ljava/lang/Object;Lyeti/lang/AList;)V"); ctx.forceType("yeti/lang/AList"); } } final class LazyCons extends BinOpRef { private int line; LazyCons(int line) { type = YetiType.LAZYCONS_TYPE; coreFun = "$c$d"; polymorph = true; this.line = line; } void binGen(Ctx ctx, Code arg1, Code arg2) { ctx.visitLine(line); ctx.visitTypeInsn(NEW, "yeti/lang/LazyList"); ctx.visitInsn(DUP); arg1.gen(ctx); arg2.gen(ctx); ctx.visitLine(line); ctx.visitTypeInsn(CHECKCAST, "yeti/lang/Fun"); ctx.visitInit("yeti/lang/LazyList", "(Ljava/lang/Object;Lyeti/lang/Fun;)V"); ctx.forceType("yeti/lang/AList"); } } final class MatchOpFun extends BinOpRef { private int line; private boolean yes; MatchOpFun(int line, boolean yes) { type = YetiType.STR2_PRED_TYPE; coreFun = mangle(yes ? "=~" : "!~"); this.line = line; this.yes = yes; } void binGen(Ctx ctx, Code arg1, final Code arg2) { apply2nd(arg2, YetiType.STR2_PRED_TYPE, line).gen(ctx); ctx.visitApply(arg1, line); } Code apply2nd(final Code arg2, final YetiType.Type t, final int line) { if (line == 0) { throw new NullPointerException(); } final Code matcher = new Code() { { type = t; } void gen(Ctx ctx) { ctx.visitTypeInsn(NEW, "yeti/lang/Match"); ctx.visitInsn(DUP); arg2.gen(ctx); ctx.intConst(yes ? 1 : 0); ctx.visitLine(line); ctx.visitInit("yeti/lang/Match", "(Ljava/lang/Object;Z)V"); } }; if (!(arg2 instanceof StringConstant)) return matcher; try { Pattern.compile(((StringConstant) arg2).str, Pattern.DOTALL); } catch (PatternSyntaxException ex) { throw new CompileException(line, 0, "Bad pattern syntax: " + ex.getMessage()); } return new Code() { { type = t; } void gen(Ctx ctx) { ctx.constant((yes ? "MATCH-FUN:" : "MATCH!FUN:") .concat(((StringConstant) arg2).str), matcher); } }; } void binGenIf(Ctx ctx, Code arg1, Code arg2, Label to, boolean ifTrue) { binGen(ctx, arg1, arg2); ctx.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;"); ctx.visitJumpInsn(ifTrue ? IF_ACMPEQ : IF_ACMPNE, to); } } final class RegexFun extends StaticRef { private String impl; private String funName; RegexFun(String fun, String impl, YetiType.Type type, Binder binder, int line) { super("yeti/lang/std$" + fun, "_", type, null, false, line); this.funName = fun; this.binder = binder; this.impl = impl; } Code apply(final Code arg, final YetiType.Type t, final int line) { final Code f = new Code() { { type = t; } void gen(Ctx ctx) { ctx.visitTypeInsn(NEW, impl); ctx.visitInsn(DUP); arg.gen(ctx); ctx.visitLine(line); ctx.visitInit(impl, "(Ljava/lang/Object;)V"); } }; if (!(arg instanceof StringConstant)) return f; try { Pattern.compile(((StringConstant) arg).str, Pattern.DOTALL); } catch (PatternSyntaxException ex) { throw new CompileException(line, 0, "Bad pattern syntax: " + ex.getMessage()); } return new Code() { { type = t; } void gen(Ctx ctx) { ctx.constant(funName + ":regex:" + ((StringConstant) arg).str, f); } }; } } final class Regex implements Binder { private String fun, impl; private YetiType.Type type; Regex(String fun, String impl, YetiType.Type type) { this.fun = fun; this.impl = impl; this.type = type; } public BindRef getRef(int line) { return new RegexFun(fun, impl, type, this, line); } } final class ClassOfExpr extends Code { String className; ClassOfExpr(JavaType what, int array) { type = YetiType.CLASS_TYPE; String cn = what.dottedName(); if (array != 0) { cn = 'L' + cn + ';'; do { cn = "[".concat(cn); } while (--array > 0); } className = cn; } void gen(Ctx ctx) { ctx.constant("CLASS-OF:".concat(className), new Code() { { type = YetiType.CLASS_TYPE; } void gen(Ctx ctx) { ctx.visitLdcInsn(className); ctx.visitMethodInsn(INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); ctx.forceType("java/lang/Class"); } }); } boolean flagop(int fl) { return (fl & STD_CONST) != 0; } } final class InstanceOfExpr extends Code { Code expr; String className; InstanceOfExpr(Code expr, JavaType what) { type = YetiType.BOOL_TYPE; this.expr = expr; className = what.className(); } void genIf(Ctx ctx, Label to, boolean ifTrue) { expr.gen(ctx); ctx.visitTypeInsn(INSTANCEOF, className); ctx.visitJumpInsn(ifTrue ? IFNE : IFEQ, to); } void gen(Ctx ctx) { Label label = new Label(); genIf(ctx, label, false); ctx.genBoolean(label); } } final class JavaArrayRef extends Code { Code value, index; YetiType.Type elementType; int line; JavaArrayRef(YetiType.Type _type, Code _value, Code _index, int _line) { type = JavaType.convertValueType(elementType = _type); value = _value; index = _index; line = _line; } private void _gen(Ctx ctx, Code store) { value.gen(ctx); ctx.visitTypeInsn(CHECKCAST, JavaType.descriptionOf(value.type)); ctx.genInt(index, line); String resDescr = elementType.javaType == null ? JavaType.descriptionOf(elementType) : elementType.javaType.description; int insn = BALOAD; switch (resDescr.charAt(0)) { case 'C': insn = CALOAD; break; case 'D': insn = DALOAD; break; case 'F': insn = FALOAD; break; case 'I': insn = IALOAD; break; case 'J': insn = LALOAD; break; case 'S': insn = SALOAD; break; case 'L': resDescr = resDescr.substring(1, resDescr.length() - 1); case '[': insn = AALOAD; break; } if (store != null) { insn += 33; JavaExpr.genValue(ctx, store, elementType, line); if (insn == AASTORE) ctx.visitTypeInsn(CHECKCAST, resDescr); } ctx.visitInsn(insn); if (insn == AALOAD) { ctx.forceType(resDescr); } } void gen(Ctx ctx) { _gen(ctx, null); JavaExpr.convertValue(ctx, elementType); } Code assign(final Code setValue) { return new Code() { void gen(Ctx ctx) { _gen(ctx, setValue); ctx.visitInsn(ACONST_NULL); } }; } } final class StrOp extends StaticRef implements Binder { final static Code NOP_CODE = new Code() { void gen(Ctx ctx) { } }; String method; String sig; YetiType.Type argTypes[]; final class StrApply extends Apply { StrApply prev; StrApply(Code arg, YetiType.Type type, StrApply prev, int line) { super(type, NOP_CODE, arg, line); this.prev = prev; } Code apply(Code arg, YetiType.Type res, int line) { return new StrApply(arg, res, this, line); } void genApply(Ctx ctx) { super.gen(ctx); } void gen(Ctx ctx) { List argv = new ArrayList(); for (StrApply a = this; a != null; a = a.prev) { argv.add(a); } if (argv.size() != argTypes.length) { StrOp.this.gen(ctx); for (int i = argv.size() - 1; --i >= 0;) ((StrApply) argv.get(i)).genApply(ctx); return; } ((StrApply) argv.get(argv.size() - 1)).arg.gen(ctx); ctx.visitLine(line); ctx.visitTypeInsn(CHECKCAST, "java/lang/String"); for (int i = 0, last = argv.size() - 2; i <= last; ++i) { StrApply a = (StrApply) argv.get(last - i); if (a.arg.type.deref().type == YetiType.STR) { a.arg.gen(ctx); ctx.visitTypeInsn(CHECKCAST, "java/lang/String"); } else { JavaExpr.convertedArg(ctx, a.arg, argTypes[i], a.line); } } ctx.visitLine(line); ctx.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", method, sig); if (type.deref().type == YetiType.STR) { ctx.forceType("java/lang/String;"); } else { JavaExpr.convertValue(ctx, argTypes[argTypes.length - 1]); } } } StrOp(String fun, String method, String sig, YetiType.Type type) { super("yeti/lang/std$" + mangle(fun), "_", type, null, false, 0); this.method = method; this.sig = sig; binder = this; argTypes = JavaTypeReader.parseSig1(1, sig); } public BindRef getRef(int line) { return this; } Code apply(final Code arg, final YetiType.Type res, final int line) { return new StrApply(arg, res, null, line); } boolean flagop(int fl) { return (fl & STD_CONST) != 0; } } final class StrChar extends BinOpRef { private int line; StrChar(int line) { coreFun = "strChar"; type = YetiType.STR_TO_NUM_TO_STR; this.line = line; } void binGen(Ctx ctx, Code arg1, Code arg2) { arg1.gen(ctx); ctx.visitTypeInsn(CHECKCAST, "java/lang/String"); ctx.genInt(arg2, line); ctx.visitInsn(DUP); ctx.intConst(1); ctx.visitInsn(IADD); ctx.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "substring", "(II)Ljava/lang/String;"); ctx.forceType("java/lang/String"); } }
true
true
public BindRef getRef(int line) { BindRef r = null; switch (op) { case 1: r = new Argv(); r.type = YetiType.STRING_ARRAY; break; case 2: r = new InOpFun(line); break; case 3: r = new Cons(line); break; case 4: r = new LazyCons(line); break; case 5: r = new For(line); break; case 6: r = new Compose(line); break; case 7: r = new Synchronized(line); break; case 8: r = new IsNullPtr(YetiType.A_TO_BOOL, "nullptr?", line); break; case 9: r = new IsDefined(line); break; case 10: r = new IsEmpty(line); break; case 11: r = new Head(line); break; case 12: r = new Tail(line); break; case 13: r = new MatchOpFun(line, true); break; case 14: r = new MatchOpFun(line, false); break; case 15: r = new NotOp(line); break; case 16: r = new StrChar(line); break; case 17: r = new UnitConstant(YetiType.BOOL_TYPE); break; case 18: r = new BooleanConstant(false); break; case 19: r = new BooleanConstant(true); break; case 20: r = new Negate(); break; case 21: r = new Same(); break; case 22: r = new StaticRef("yeti/lang/Core", "RANDINT", YetiType.NUM_TO_NUM, this, true, line); break; case 23: r = new StaticRef("yeti/lang/Core", "UNDEF_STR", YetiType.STR_TYPE, this, true, line); break; case 24: r = new Escape(line); break; } r.binder = this; return r; }
public BindRef getRef(int line) { BindRef r = null; switch (op) { case 1: r = new Argv(); r.type = YetiType.STRING_ARRAY; break; case 2: r = new InOpFun(line); break; case 3: r = new Cons(line); break; case 4: r = new LazyCons(line); break; case 5: r = new For(line); break; case 6: r = new Compose(line); break; case 7: r = new Synchronized(line); break; case 8: r = new IsNullPtr(YetiType.A_TO_BOOL, "nullptr$q", line); break; case 9: r = new IsDefined(line); break; case 10: r = new IsEmpty(line); break; case 11: r = new Head(line); break; case 12: r = new Tail(line); break; case 13: r = new MatchOpFun(line, true); break; case 14: r = new MatchOpFun(line, false); break; case 15: r = new NotOp(line); break; case 16: r = new StrChar(line); break; case 17: r = new UnitConstant(YetiType.BOOL_TYPE); break; case 18: r = new BooleanConstant(false); break; case 19: r = new BooleanConstant(true); break; case 20: r = new Negate(); break; case 21: r = new Same(); break; case 22: r = new StaticRef("yeti/lang/Core", "RANDINT", YetiType.NUM_TO_NUM, this, true, line); break; case 23: r = new StaticRef("yeti/lang/Core", "UNDEF_STR", YetiType.STR_TYPE, this, true, line); break; case 24: r = new Escape(line); break; } r.binder = this; return r; }
diff --git a/core/src/classes/org/jdesktop/wonderland/server/cell/CellEditConnectionHandler.java b/core/src/classes/org/jdesktop/wonderland/server/cell/CellEditConnectionHandler.java index 0caac318a..e10c1543c 100644 --- a/core/src/classes/org/jdesktop/wonderland/server/cell/CellEditConnectionHandler.java +++ b/core/src/classes/org/jdesktop/wonderland/server/cell/CellEditConnectionHandler.java @@ -1,496 +1,496 @@ /** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ package org.jdesktop.wonderland.server.cell; import com.jme.math.Vector3f; import com.sun.sgs.app.AppContext; import com.sun.sgs.kernel.ComponentRegistry; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.util.Properties; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.jdesktop.wonderland.common.auth.WonderlandIdentity; import org.jdesktop.wonderland.common.cell.CellEditConnectionType; import org.jdesktop.wonderland.common.cell.CellID; import org.jdesktop.wonderland.common.cell.CellTransform; import org.jdesktop.wonderland.common.cell.MultipleParentException; import org.jdesktop.wonderland.common.cell.messages.CellCreateMessage; import org.jdesktop.wonderland.common.cell.messages.CellDeleteMessage; import org.jdesktop.wonderland.common.cell.messages.CellDuplicateMessage; import org.jdesktop.wonderland.common.cell.messages.CellEditMessage; import org.jdesktop.wonderland.common.cell.messages.CellEditMessage.EditType; import org.jdesktop.wonderland.common.cell.messages.CellReparentMessage; import org.jdesktop.wonderland.common.cell.security.ChildrenAction; import org.jdesktop.wonderland.common.cell.state.CellServerState; import org.jdesktop.wonderland.common.cell.state.PositionComponentServerState; import org.jdesktop.wonderland.common.comms.ConnectionType; import org.jdesktop.wonderland.common.messages.Message; import org.jdesktop.wonderland.common.security.Action; import org.jdesktop.wonderland.common.wfs.CellPath; import org.jdesktop.wonderland.server.WonderlandContext; import org.jdesktop.wonderland.server.comms.SecureClientConnectionHandler; import org.jdesktop.wonderland.server.comms.WonderlandClientID; import org.jdesktop.wonderland.server.comms.WonderlandClientSender; import org.jdesktop.wonderland.server.security.Resource; import org.jdesktop.wonderland.server.spatial.UniverseManagerFactory; /** * Handles CellEditMessages sent by the Wonderland client * * @author Jordan Slott <[email protected]> */ class CellEditConnectionHandler implements SecureClientConnectionHandler, Serializable { public ConnectionType getConnectionType() { return CellEditConnectionType.CLIENT_TYPE; } public void registered(WonderlandClientSender sender) { // ignore } public Resource checkConnect(WonderlandClientID clientID, Properties properties) { return null; } public void clientConnected(WonderlandClientSender sender, WonderlandClientID clientID, Properties properties) { // ignore } public void connectionRejected(WonderlandClientID clientID) { // ignore } public void clientDisconnected(WonderlandClientSender sender, WonderlandClientID clientID) { // ignore } public Resource checkMessage(WonderlandClientID clientID, Message message) { CellResourceManager crm = AppContext.getManager(CellResourceManager.class); Resource out = null; // for each cell being modified, check that the caller has // permissions to modify the children of the parent cell CellEditMessage editMessage = (CellEditMessage) message; switch (editMessage.getEditType()) { case CREATE_CELL: CellCreateMessage ccm = (CellCreateMessage) editMessage; if (ccm.getParentCellID() != null) { out = crm.getCellResource(ccm.getParentCellID()); } break; case DELETE_CELL: { // delete requires permission from both the cell being // deleted and the parent cell CellDeleteMessage cdm = (CellDeleteMessage) editMessage; CellMO deleteMO = CellManagerMO.getCell(cdm.getCellID()); if (deleteMO == null) { break; } Resource child = crm.getCellResource(cdm.getCellID()); Resource parent = null; // get the cell's parent, if any CellMO parentMO = deleteMO.getParent(); if (parentMO != null) { parent = crm.getCellResource(parentMO.getCellID()); } // now create a delete resource with child & parent if (child != null || parent != null) { out = new DeleteCellResource(cdm.getCellID().toString(), child, parent); } } break; case DUPLICATE_CELL: CellDuplicateMessage cnm = (CellDuplicateMessage) editMessage; CellMO dupMO = CellManagerMO.getCell(cnm.getCellID()); if (dupMO != null && dupMO.getParent() != null) { out = crm.getCellResource(dupMO.getParent().getCellID()); } break; case REPARENT_CELL: { CellReparentMessage msg = (CellReparentMessage) editMessage; CellMO childMO = CellManagerMO.getCell(msg.getCellID()); if (childMO==null) break; Resource child = crm.getCellResource(msg.getCellID()); Resource oldParent = null; Resource newParent = null; CellMO oldParentMO = childMO.getParent(); if (oldParentMO!=null) oldParent = crm.getCellResource(oldParentMO.getCellID()); CellMO newParentMO = CellManagerMO.getCell(msg.getParentCellID()); if (newParentMO!=null) newParent = crm.getCellResource(msg.getParentCellID()); if (child!=null || oldParent!=null || newParent!=null) out = new ReparentCellResource(msg.getCellID().toString(), child, oldParent, newParent); } break; } return out; } public void messageReceived(WonderlandClientSender sender, WonderlandClientID clientID, Message message) { Logger logger = Logger.getLogger(CellEditConnectionHandler.class.getName()); CellEditMessage editMessage = (CellEditMessage)message; if (editMessage.getEditType() == EditType.CREATE_CELL) { // The create message contains a setup class of the cell setup // information. Simply parse this stream, which will result in a // setup class of the property type. CellServerState setup = ((CellCreateMessage)editMessage).getCellSetup(); // Fetch the server-side cell class name and create the cell String className = setup.getServerClassName(); logger.fine("Attempting to load cell mo: " + className); CellMO cellMO = CellMOFactory.loadCellMO(className); if (cellMO == null) { /* Log a warning and move onto the next cell */ logger.warning("Unable to load cell MO: " + className ); return; } // Find the parent cell (if any) CellMO parent = null; CellID parentCellID = ((CellCreateMessage)editMessage).getParentCellID(); if (parentCellID != null) { parent = CellManagerMO.getCell(parentCellID); } /* Call the cell's setup method */ try { cellMO.setServerState(setup); if (parent == null) { WonderlandContext.getCellManager().insertCellInWorld(cellMO); } else { parent.addChild(cellMO); } } catch (ClassCastException cce) { logger.log(Level.WARNING, "Error setting up new cell " + cellMO.getName() + " of type " + cellMO.getClass() + ", it does not implement " + "BeanSetupMO.", cce); return; } catch (MultipleParentException excp) { logger.log(Level.WARNING, "Error adding new cell " + cellMO.getName() + " of type " + cellMO.getClass() + ", has multiple parents", excp); } } else if (editMessage.getEditType() == EditType.DELETE_CELL) { // Find the cell object given the ID of the cell. If the ID is // invalid, we just log an error and return. CellID cellID = ((CellDeleteMessage)editMessage).getCellID(); CellMO cellMO = CellManagerMO.getCell(cellID); if (cellMO == null) { logger.warning("No cell found to delete with cell id " + cellID); return; } // Find out the parent of the cell. This may be null if the cell is // at the world root. This determines from where to remove the cell CellMO parentMO = cellMO.getParent(); if (parentMO != null) { parentMO.removeChild(cellMO); } else { CellManagerMO.getCellManager().removeCellFromWorld(cellMO); } } else if (editMessage.getEditType() == EditType.DUPLICATE_CELL) { // Find the cell object given the ID of the cell. If the ID is // invalid, we just log an error and return. CellID cellID = ((CellDuplicateMessage)editMessage).getCellID(); CellMO cellMO = CellManagerMO.getCell(cellID); if (cellMO == null) { logger.warning("No cell found to duplicate with cell id " + cellID); return; } CellMO parentCellMO = cellMO.getParent(); // We need to fetch the current state of the cell from the cell we // wish to duplicate. We also need the name of the server-side cell // class CellServerState state = cellMO.getServerState(null); String className = state.getServerClassName(); // Attempt to create the cell using the cell factory and the class // name of the server-side cell. CellMO newCellMO = CellMOFactory.loadCellMO(className); if (newCellMO == null) { /* Log a warning and move onto the next cell */ logger.warning("Unable to duplicate cell MO: " + className); return; } // We want to modify the position of the new cell slight, so we // offset the position by (1, 1, 1). PositionComponentServerState position = (PositionComponentServerState)state.getComponentServerState(PositionComponentServerState.class); if (position == null) { logger.warning("Unable to determine the position of the cell " + "to duplicate with id " + cellID); return; } - Vector3f offset = new Vector3f(1, 1, 1); + Vector3f offset = new Vector3f(1, 0, 1); Vector3f origin = position.getTranslation(); position.setTranslation(offset.add(origin)); state.addComponentServerState(position); // Set the desired name of the cell contained within the message state.setName(((CellDuplicateMessage)editMessage).getCellName()); // Set the state of the new cell and add it to the same parent as // the old cell. If the old parent cell is null, we just insert it // as root. newCellMO.setServerState(state); try { if (parentCellMO == null) { WonderlandContext.getCellManager().insertCellInWorld(newCellMO); } else { parentCellMO.addChild(newCellMO); } } catch (MultipleParentException excp) { logger.log(Level.WARNING, "Error duplicating cell " + newCellMO.getName() + " of type " + newCellMO.getClass() + ", has multiple parents", excp); } } else if (editMessage.getEditType() == EditType.REPARENT_CELL) { // Find the cell id to move and the new parent id CellID cellID = ((CellReparentMessage)editMessage).getCellID(); CellID newParentID = ((CellReparentMessage)editMessage).getParentCellID(); // logger.warning("REPARENT CELL " + cellID + " " + newParentID); // Figure out the new local coordinates of the cell wrt the new // parent // Change the parent cell CellMO child = CellManagerMO.getCell(cellID); CellMO oldParent = child.getParent(); CellMO newParent = CellManagerMO.getCell(newParentID); // System.err.println("ORIGINAL LOC "+child.getWorldTransform(null).getTranslation(null)); // // System.err.println("NEW PARENT "+newParent); // System.err.println("OLD PARENT "+oldParent); if (oldParent==null) { CellManagerMO.getCellManager().removeCellFromWorld(child); } else { oldParent.removeChild(child); } CellTransform childTransform = ((CellReparentMessage)editMessage).getChildCellTransform(); if (childTransform!=null) child.setLocalTransform(childTransform); if (newParent==null) { try { CellManagerMO.getCellManager().insertCellInWorld(child); } catch (MultipleParentException ex) { Logger.getLogger(CellEditConnectionHandler.class.getName()).log(Level.SEVERE, null, ex); } } else { try { newParent.addChild(child); } catch (MultipleParentException ex) { Logger.getLogger(CellEditConnectionHandler.class.getName()).log(Level.SEVERE, null, ex); } } // System.err.println("REPARENTED LOC "+child.getWorldTransform(null).getTranslation(null)); } } public boolean messageRejected(WonderlandClientSender sender, WonderlandClientID clientID, Message message, Set<Action> requested, Set<Action> granted) { Logger logger = Logger.getLogger(CellEditConnectionHandler.class.getName()); logger.warning("Message " + message + " rejected from " + clientID); return true; } /** * Returns the base URL of the web server. */ private static URL getWebServerURL() throws MalformedURLException { return new URL(System.getProperty("wonderland.web.server.url")); } /** * Given a base URL of the server (e.g. http://localhost:8080) returns * the server name and port as a string (e.g. localhost:8080). Returns null * if the host name is not present. * * @return <server name>:<port> * @throw MalformedURLException If the given string URL is invalid */ private static String getServerFromURL(URL serverURL) { String host = serverURL.getHost(); int port = serverURL.getPort(); if (host == null) { return null; } else if (port == -1) { return host; } return host + ":" + port; } /** * Deleting requires permission to modify the cell being deleted as well * as permission to modify the children of the parent cell, if any. This * resource provides that mapping. All request are mapped to the child * except requests for the ModifyChildren which are mapped to the parent. */ private static class DeleteCellResource implements Resource { private String cellID; private Resource child; private Resource parent; public DeleteCellResource(String cellID, Resource child, Resource parent) { this.cellID = cellID; this.child = child; this.parent = parent; } public String getId() { return "DeleteCell_" + cellID; } public Result request(WonderlandIdentity identity, Action action) { if (action instanceof ChildrenAction && parent != null) { // route to parent (if any) return parent.request(identity, action); } else if (!(action instanceof ChildrenAction) && child != null) { // route to child (if any) return child.request(identity, action); } // if we got here, there is no-one to route to -- just grant the // request return Result.GRANT; } public boolean request(WonderlandIdentity identity, Action action, ComponentRegistry registry) { if (action instanceof ChildrenAction && parent != null) { // route to parent (if any) return parent.request(identity, action, registry); } else if (!(action instanceof ChildrenAction) && child != null) { // route to child (if any) return child.request(identity, action, registry); } // if we got here, there is no-one to route to -- just grant the // request return true; } } private static class ReparentCellResource implements Resource { private String cellID; private Resource child; private Resource oldParent; private Resource newParent; public ReparentCellResource(String cellID, Resource child, Resource oldParent, Resource newParent) { this.cellID = cellID; this.child = child; this.oldParent = oldParent; this.newParent = newParent; } public String getId() { return "ReparentCell_" + cellID; } public Result request(WonderlandIdentity identity, Action action) { if (action instanceof ChildrenAction && oldParent != null) { Result tmp = Result.GRANT; if (oldParent!=null ) tmp = oldParent.request(identity, action); Result tmp2 = Result.GRANT; if (newParent!=null) tmp2 = newParent.request(identity, action); return Result.combine(tmp, tmp2); } else if (!(action instanceof ChildrenAction) && child != null) { // route to child (if any) return child.request(identity, action); } // if we got here, there is no-one to route to -- just grant the // request return Result.GRANT; } public boolean request(WonderlandIdentity identity, Action action, ComponentRegistry registry) { if (action instanceof ChildrenAction) { boolean tmp = true; if (oldParent!=null) tmp = oldParent.request(identity, action, registry); boolean tmp2 = true; if (newParent!=null) tmp2 = newParent.request(identity, action, registry); return (tmp && tmp2); } else if (!(action instanceof ChildrenAction) && child != null) { // route to child (if any) return child.request(identity, action, registry); } // if we got here, there is no-one to route to -- just grant the // request return true; } } }
true
true
public void messageReceived(WonderlandClientSender sender, WonderlandClientID clientID, Message message) { Logger logger = Logger.getLogger(CellEditConnectionHandler.class.getName()); CellEditMessage editMessage = (CellEditMessage)message; if (editMessage.getEditType() == EditType.CREATE_CELL) { // The create message contains a setup class of the cell setup // information. Simply parse this stream, which will result in a // setup class of the property type. CellServerState setup = ((CellCreateMessage)editMessage).getCellSetup(); // Fetch the server-side cell class name and create the cell String className = setup.getServerClassName(); logger.fine("Attempting to load cell mo: " + className); CellMO cellMO = CellMOFactory.loadCellMO(className); if (cellMO == null) { /* Log a warning and move onto the next cell */ logger.warning("Unable to load cell MO: " + className ); return; } // Find the parent cell (if any) CellMO parent = null; CellID parentCellID = ((CellCreateMessage)editMessage).getParentCellID(); if (parentCellID != null) { parent = CellManagerMO.getCell(parentCellID); } /* Call the cell's setup method */ try { cellMO.setServerState(setup); if (parent == null) { WonderlandContext.getCellManager().insertCellInWorld(cellMO); } else { parent.addChild(cellMO); } } catch (ClassCastException cce) { logger.log(Level.WARNING, "Error setting up new cell " + cellMO.getName() + " of type " + cellMO.getClass() + ", it does not implement " + "BeanSetupMO.", cce); return; } catch (MultipleParentException excp) { logger.log(Level.WARNING, "Error adding new cell " + cellMO.getName() + " of type " + cellMO.getClass() + ", has multiple parents", excp); } } else if (editMessage.getEditType() == EditType.DELETE_CELL) { // Find the cell object given the ID of the cell. If the ID is // invalid, we just log an error and return. CellID cellID = ((CellDeleteMessage)editMessage).getCellID(); CellMO cellMO = CellManagerMO.getCell(cellID); if (cellMO == null) { logger.warning("No cell found to delete with cell id " + cellID); return; } // Find out the parent of the cell. This may be null if the cell is // at the world root. This determines from where to remove the cell CellMO parentMO = cellMO.getParent(); if (parentMO != null) { parentMO.removeChild(cellMO); } else { CellManagerMO.getCellManager().removeCellFromWorld(cellMO); } } else if (editMessage.getEditType() == EditType.DUPLICATE_CELL) { // Find the cell object given the ID of the cell. If the ID is // invalid, we just log an error and return. CellID cellID = ((CellDuplicateMessage)editMessage).getCellID(); CellMO cellMO = CellManagerMO.getCell(cellID); if (cellMO == null) { logger.warning("No cell found to duplicate with cell id " + cellID); return; } CellMO parentCellMO = cellMO.getParent(); // We need to fetch the current state of the cell from the cell we // wish to duplicate. We also need the name of the server-side cell // class CellServerState state = cellMO.getServerState(null); String className = state.getServerClassName(); // Attempt to create the cell using the cell factory and the class // name of the server-side cell. CellMO newCellMO = CellMOFactory.loadCellMO(className); if (newCellMO == null) { /* Log a warning and move onto the next cell */ logger.warning("Unable to duplicate cell MO: " + className); return; } // We want to modify the position of the new cell slight, so we // offset the position by (1, 1, 1). PositionComponentServerState position = (PositionComponentServerState)state.getComponentServerState(PositionComponentServerState.class); if (position == null) { logger.warning("Unable to determine the position of the cell " + "to duplicate with id " + cellID); return; } Vector3f offset = new Vector3f(1, 1, 1); Vector3f origin = position.getTranslation(); position.setTranslation(offset.add(origin)); state.addComponentServerState(position); // Set the desired name of the cell contained within the message state.setName(((CellDuplicateMessage)editMessage).getCellName()); // Set the state of the new cell and add it to the same parent as // the old cell. If the old parent cell is null, we just insert it // as root. newCellMO.setServerState(state); try { if (parentCellMO == null) { WonderlandContext.getCellManager().insertCellInWorld(newCellMO); } else { parentCellMO.addChild(newCellMO); } } catch (MultipleParentException excp) { logger.log(Level.WARNING, "Error duplicating cell " + newCellMO.getName() + " of type " + newCellMO.getClass() + ", has multiple parents", excp); } } else if (editMessage.getEditType() == EditType.REPARENT_CELL) { // Find the cell id to move and the new parent id CellID cellID = ((CellReparentMessage)editMessage).getCellID(); CellID newParentID = ((CellReparentMessage)editMessage).getParentCellID(); // logger.warning("REPARENT CELL " + cellID + " " + newParentID); // Figure out the new local coordinates of the cell wrt the new // parent // Change the parent cell CellMO child = CellManagerMO.getCell(cellID); CellMO oldParent = child.getParent(); CellMO newParent = CellManagerMO.getCell(newParentID); // System.err.println("ORIGINAL LOC "+child.getWorldTransform(null).getTranslation(null)); // // System.err.println("NEW PARENT "+newParent); // System.err.println("OLD PARENT "+oldParent); if (oldParent==null) { CellManagerMO.getCellManager().removeCellFromWorld(child); } else { oldParent.removeChild(child); } CellTransform childTransform = ((CellReparentMessage)editMessage).getChildCellTransform(); if (childTransform!=null) child.setLocalTransform(childTransform); if (newParent==null) { try { CellManagerMO.getCellManager().insertCellInWorld(child); } catch (MultipleParentException ex) { Logger.getLogger(CellEditConnectionHandler.class.getName()).log(Level.SEVERE, null, ex); } } else { try { newParent.addChild(child); } catch (MultipleParentException ex) { Logger.getLogger(CellEditConnectionHandler.class.getName()).log(Level.SEVERE, null, ex); } } // System.err.println("REPARENTED LOC "+child.getWorldTransform(null).getTranslation(null)); } }
public void messageReceived(WonderlandClientSender sender, WonderlandClientID clientID, Message message) { Logger logger = Logger.getLogger(CellEditConnectionHandler.class.getName()); CellEditMessage editMessage = (CellEditMessage)message; if (editMessage.getEditType() == EditType.CREATE_CELL) { // The create message contains a setup class of the cell setup // information. Simply parse this stream, which will result in a // setup class of the property type. CellServerState setup = ((CellCreateMessage)editMessage).getCellSetup(); // Fetch the server-side cell class name and create the cell String className = setup.getServerClassName(); logger.fine("Attempting to load cell mo: " + className); CellMO cellMO = CellMOFactory.loadCellMO(className); if (cellMO == null) { /* Log a warning and move onto the next cell */ logger.warning("Unable to load cell MO: " + className ); return; } // Find the parent cell (if any) CellMO parent = null; CellID parentCellID = ((CellCreateMessage)editMessage).getParentCellID(); if (parentCellID != null) { parent = CellManagerMO.getCell(parentCellID); } /* Call the cell's setup method */ try { cellMO.setServerState(setup); if (parent == null) { WonderlandContext.getCellManager().insertCellInWorld(cellMO); } else { parent.addChild(cellMO); } } catch (ClassCastException cce) { logger.log(Level.WARNING, "Error setting up new cell " + cellMO.getName() + " of type " + cellMO.getClass() + ", it does not implement " + "BeanSetupMO.", cce); return; } catch (MultipleParentException excp) { logger.log(Level.WARNING, "Error adding new cell " + cellMO.getName() + " of type " + cellMO.getClass() + ", has multiple parents", excp); } } else if (editMessage.getEditType() == EditType.DELETE_CELL) { // Find the cell object given the ID of the cell. If the ID is // invalid, we just log an error and return. CellID cellID = ((CellDeleteMessage)editMessage).getCellID(); CellMO cellMO = CellManagerMO.getCell(cellID); if (cellMO == null) { logger.warning("No cell found to delete with cell id " + cellID); return; } // Find out the parent of the cell. This may be null if the cell is // at the world root. This determines from where to remove the cell CellMO parentMO = cellMO.getParent(); if (parentMO != null) { parentMO.removeChild(cellMO); } else { CellManagerMO.getCellManager().removeCellFromWorld(cellMO); } } else if (editMessage.getEditType() == EditType.DUPLICATE_CELL) { // Find the cell object given the ID of the cell. If the ID is // invalid, we just log an error and return. CellID cellID = ((CellDuplicateMessage)editMessage).getCellID(); CellMO cellMO = CellManagerMO.getCell(cellID); if (cellMO == null) { logger.warning("No cell found to duplicate with cell id " + cellID); return; } CellMO parentCellMO = cellMO.getParent(); // We need to fetch the current state of the cell from the cell we // wish to duplicate. We also need the name of the server-side cell // class CellServerState state = cellMO.getServerState(null); String className = state.getServerClassName(); // Attempt to create the cell using the cell factory and the class // name of the server-side cell. CellMO newCellMO = CellMOFactory.loadCellMO(className); if (newCellMO == null) { /* Log a warning and move onto the next cell */ logger.warning("Unable to duplicate cell MO: " + className); return; } // We want to modify the position of the new cell slight, so we // offset the position by (1, 1, 1). PositionComponentServerState position = (PositionComponentServerState)state.getComponentServerState(PositionComponentServerState.class); if (position == null) { logger.warning("Unable to determine the position of the cell " + "to duplicate with id " + cellID); return; } Vector3f offset = new Vector3f(1, 0, 1); Vector3f origin = position.getTranslation(); position.setTranslation(offset.add(origin)); state.addComponentServerState(position); // Set the desired name of the cell contained within the message state.setName(((CellDuplicateMessage)editMessage).getCellName()); // Set the state of the new cell and add it to the same parent as // the old cell. If the old parent cell is null, we just insert it // as root. newCellMO.setServerState(state); try { if (parentCellMO == null) { WonderlandContext.getCellManager().insertCellInWorld(newCellMO); } else { parentCellMO.addChild(newCellMO); } } catch (MultipleParentException excp) { logger.log(Level.WARNING, "Error duplicating cell " + newCellMO.getName() + " of type " + newCellMO.getClass() + ", has multiple parents", excp); } } else if (editMessage.getEditType() == EditType.REPARENT_CELL) { // Find the cell id to move and the new parent id CellID cellID = ((CellReparentMessage)editMessage).getCellID(); CellID newParentID = ((CellReparentMessage)editMessage).getParentCellID(); // logger.warning("REPARENT CELL " + cellID + " " + newParentID); // Figure out the new local coordinates of the cell wrt the new // parent // Change the parent cell CellMO child = CellManagerMO.getCell(cellID); CellMO oldParent = child.getParent(); CellMO newParent = CellManagerMO.getCell(newParentID); // System.err.println("ORIGINAL LOC "+child.getWorldTransform(null).getTranslation(null)); // // System.err.println("NEW PARENT "+newParent); // System.err.println("OLD PARENT "+oldParent); if (oldParent==null) { CellManagerMO.getCellManager().removeCellFromWorld(child); } else { oldParent.removeChild(child); } CellTransform childTransform = ((CellReparentMessage)editMessage).getChildCellTransform(); if (childTransform!=null) child.setLocalTransform(childTransform); if (newParent==null) { try { CellManagerMO.getCellManager().insertCellInWorld(child); } catch (MultipleParentException ex) { Logger.getLogger(CellEditConnectionHandler.class.getName()).log(Level.SEVERE, null, ex); } } else { try { newParent.addChild(child); } catch (MultipleParentException ex) { Logger.getLogger(CellEditConnectionHandler.class.getName()).log(Level.SEVERE, null, ex); } } // System.err.println("REPARENTED LOC "+child.getWorldTransform(null).getTranslation(null)); } }
diff --git a/src/org/apache/xalan/xslt/Process.java b/src/org/apache/xalan/xslt/Process.java index 0f1e59d5..2c2f5e63 100644 --- a/src/org/apache/xalan/xslt/Process.java +++ b/src/org/apache/xalan/xslt/Process.java @@ -1,997 +1,1002 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xalan.xslt; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.InputStream; import java.io.BufferedInputStream; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.FileNotFoundException; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Constructor; import java.util.TooManyListenersException; import java.util.Vector; import java.util.Properties; import java.util.Enumeration; import java.util.Date; // Needed Xalan classes import org.apache.xalan.res.XSLMessages; import org.apache.xalan.processor.XSLProcessorVersion; import org.apache.xalan.res.XSLTErrorResources; import org.apache.xalan.templates.Constants; import org.apache.xalan.templates.ElemTemplateElement; import org.apache.xalan.templates.StylesheetRoot; import org.apache.xalan.transformer.TransformerImpl; import org.apache.xalan.transformer.XalanProperties; import org.apache.xalan.processor.TransformerFactoryImpl; import org.apache.xalan.trace.PrintTraceListener; import org.apache.xalan.trace.TraceListener; import org.apache.xalan.trace.TraceManager; import org.apache.xml.utils.DefaultErrorHandler; // Needed TRaX classes import javax.xml.transform.Result; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.Transformer; import javax.xml.transform.Templates; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.dom.*; import javax.xml.transform.sax.*; import javax.xml.parsers.*; import org.w3c.dom.Node; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.EntityResolver; import org.xml.sax.ContentHandler; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; // Needed Serializer classes import org.apache.xalan.serialize.Serializer; import org.apache.xalan.serialize.SerializerFactory; /** * <meta name="usage" content="general"/> * The main() method handles the Xalan command-line interface. */ public class Process { /** * Prints argument options. * * @param resbundle Resource bundle */ protected static void printArgOptions(XSLTErrorResources resbundle) { System.out.println(resbundle.getString("xslProc_option")); //"xslproc options: "); System.out.println(resbundle.getString("optionIN")); //" -IN inputXMLURL"); System.out.println(resbundle.getString("optionXSL")); //" [-XSL XSLTransformationURL]"); System.out.println(resbundle.getString("optionOUT")); //" [-OUT outputFileName]"); // System.out.println(resbundle.getString("optionE")); //" [-E (Do not expand entity refs)]"); System.out.println(resbundle.getString("optionV")); //" [-V (Version info)]"); System.out.println(resbundle.getString("optionQC")); //" [-QC (Quiet Pattern Conflicts Warnings)]"); // System.out.println(resbundle.getString("optionQ")); //" [-Q (Quiet Mode)]"); // sc 28-Feb-01 commented out System.out.println(resbundle.getString("optionTT")); //" [-TT (Trace the templates as they are being called.)]"); System.out.println(resbundle.getString("optionTG")); //" [-TG (Trace each generation event.)]"); System.out.println(resbundle.getString("optionTS")); //" [-TS (Trace each selection event.)]"); System.out.println(resbundle.getString("optionTTC")); //" [-TTC (Trace the template children as they are being processed.)]"); System.out.println(resbundle.getString("optionTCLASS")); //" [-TCLASS (TraceListener class for trace extensions.)]"); // System.out.println(resbundle.getString("optionVALIDATE")); //" [-VALIDATE (Set whether validation occurs. Validation is off by default.)]"); System.out.println(resbundle.getString("optionEDUMP")); //" [-EDUMP {optional filename} (Do stackdump on error.)]"); System.out.println(resbundle.getString("optionXML")); //" [-XML (Use XML formatter and add XML header.)]"); System.out.println(resbundle.getString("optionTEXT")); //" [-TEXT (Use simple Text formatter.)]"); System.out.println(resbundle.getString("optionHTML")); //" [-HTML (Use HTML formatter.)]"); System.out.println(resbundle.getString("optionPARAM")); //" [-PARAM name expression (Set a stylesheet parameter)]"); System.out.println(resbundle.getString("optionLINENUMBERS")); //" [-L use line numbers]" // sc 28-Feb-01 these below should really be added as resources System.out.println( " [-MEDIA mediaType (use media attribute to find stylesheet associated with a document.)]"); System.out.println( " [-FLAVOR flavorName (Explicitly use s2s=SAX or d2d=DOM to do transform.)]"); // Added by sboag/scurcuru; experimental System.out.println( " [-DIAG (Print overall milliseconds transform took.)]"); System.out.println(resbundle.getString("optionURIRESOLVER")); //" [-URIRESOLVER full class name (URIResolver to be used to resolve URIs)]"); System.out.println(resbundle.getString("optionENTITYRESOLVER")); //" [-ENTITYRESOLVER full class name (EntityResolver to be used to resolve entities)]"); System.out.println(resbundle.getString("optionCONTENTHANDLER")); //" [-CONTENTHANDLER full class name (ContentHandler to be used to serialize output)]"); // jk 11/27/01 these below should really be added as resources System.out.println( " [-INCREMENTAL (request incremental DTM construction by setting http://xml.apache.org/xalan/features/incremental true.)]"); System.out.println( " [-NOOPTIMIMIZE (request no stylesheet optimization proccessing by setting http://xml.apache.org/xalan/features/optimize false.)]"); System.out.println( " [-RL recursionlimit (assert numeric limit on stylesheet recursion depth.)]"); } /** * Command line interface to transform an XML document according to * the instructions found in an XSL stylesheet. * <p>The Process class provides basic functionality for * performing transformations from the command line. To see a * list of arguments supported, call with zero arguments.</p> * <p>To set stylesheet parameters from the command line, use * <code>-PARAM name expression</code>. If you want to set the * parameter to a string value, simply pass the string value * as-is, and it will be interpreted as a string. (Note: if * the value has spaces in it, you may need to quote it depending * on your shell environment).</p> * * @param argv Input parameters from command line */ public static void main(String argv[]) { // Runtime.getRuntime().traceMethodCalls(false); // turns Java tracing off boolean doStackDumpOnError = false; boolean setQuietMode = false; boolean doDiag = false; // Runtime.getRuntime().traceMethodCalls(false); // Runtime.getRuntime().traceInstructions(false); /** * The default diagnostic writer... */ java.io.PrintWriter diagnosticsWriter = new PrintWriter(System.err, true); java.io.PrintWriter dumpWriter = diagnosticsWriter; XSLTErrorResources resbundle = (XSLTErrorResources) (XSLMessages.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.ERROR_RESOURCES)); String flavor = "s2s"; if (argv.length < 1) { printArgOptions(resbundle); } else { TransformerFactory tfactory; try { tfactory = TransformerFactory.newInstance(); } catch (TransformerFactoryConfigurationError pfe) { pfe.printStackTrace(dumpWriter); diagnosticsWriter.println( XSLMessages.createMessage( XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful."); tfactory = null; // shut up compiler doExit(-1); } boolean formatOutput = false; boolean useSourceLocation = false; String inFileName = null; String outFileName = null; String dumpFileName = null; String xslFileName = null; String treedumpFileName = null; PrintTraceListener tracer = null; String outputType = null; String media = null; Vector params = new Vector(); boolean quietConflictWarnings = false; URIResolver uriResolver = null; EntityResolver entityResolver = null; ContentHandler contentHandler = null; int recursionLimit=-1; for (int i = 0; i < argv.length; i++) { if ("-TT".equalsIgnoreCase(argv[i])) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceTemplates = true; // tfactory.setTraceTemplates(true); } else if ("-TG".equalsIgnoreCase(argv[i])) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceGeneration = true; // tfactory.setTraceSelect(true); } else if ("-TS".equalsIgnoreCase(argv[i])) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceSelection = true; // tfactory.setTraceTemplates(true); } else if ("-TTC".equalsIgnoreCase(argv[i])) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceElements = true; // tfactory.setTraceTemplateChildren(true); } else if ("-INDENT".equalsIgnoreCase(argv[i])) { int indentAmount; if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) { indentAmount = Integer.parseInt(argv[++i]); } else { indentAmount = 0; } // TBD: // xmlProcessorLiaison.setIndent(indentAmount); } else if ("-IN".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) inFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-IN" })); //"Missing argument for); } else if ("-MEDIA".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) media = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-MEDIA" })); //"Missing argument for); } else if ("-OUT".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) outFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-OUT" })); //"Missing argument for); } else if ("-XSL".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) xslFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-XSL" })); //"Missing argument for); } else if ("-FLAVOR".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { flavor = argv[++i]; } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-FLAVOR" })); //"Missing argument for); } else if ("-PARAM".equalsIgnoreCase(argv[i])) { if (i + 2 < argv.length) { String name = argv[++i]; params.addElement(name); String expression = argv[++i]; params.addElement(expression); } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-PARAM" })); //"Missing argument for); } else if ("-TREEDUMP".equalsIgnoreCase(argv[i])) // sc 28-Feb-01 appears to be unused; can we remove? { if (i + 1 < argv.length) treedumpFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-treedump" })); //"Missing argument for); } else if ("-F".equalsIgnoreCase(argv[i])) // sc 28-Feb-01 appears to be unused; can we remove? { formatOutput = true; } else if ("-E".equalsIgnoreCase(argv[i])) { // TBD: // xmlProcessorLiaison.setShouldExpandEntityRefs(false); } else if ("-V".equalsIgnoreCase(argv[i])) { diagnosticsWriter.println(resbundle.getString("version") //">>>>>>> Xalan Version " + XSLProcessorVersion.S_VERSION + ", " + /* xmlProcessorLiaison.getParserDescription()+ */ resbundle.getString("version2")); // "<<<<<<<"); } else if ("-QC".equalsIgnoreCase(argv[i])) { quietConflictWarnings = true; } else if ("-Q".equalsIgnoreCase(argv[i])) { setQuietMode = true; } /* else if("-VALIDATE".equalsIgnoreCase(argv[i])) { String shouldValidate; if(((i+1) < argv.length) && (argv[i+1].charAt(0) != '-')) { shouldValidate = argv[++i]; } else { shouldValidate = "yes"; } // xmlProcessorLiaison.setUseValidation(shouldValidate.equalsIgnoreCase("yes")); } */ else if ("-DIAG".equalsIgnoreCase(argv[i])) { doDiag = true; } else if ("-XML".equalsIgnoreCase(argv[i])) { outputType = "xml"; } else if ("-TEXT".equalsIgnoreCase(argv[i])) { outputType = "text"; } else if ("-HTML".equalsIgnoreCase(argv[i])) { outputType = "html"; } else if ("-EDUMP".equalsIgnoreCase(argv[i])) { doStackDumpOnError = true; if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) { dumpFileName = argv[++i]; } } else if ("-URIRESOLVER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { uriResolver = (URIResolver) Class.forName(argv[++i]).newInstance(); tfactory.setURIResolver(uriResolver); } catch (Exception cnfe) { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[]{ "-URIResolver" })); doExit(-1); } } else { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-URIResolver" })); //"Missing argument for); doExit(-1); } } else if ("-ENTITYRESOLVER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { entityResolver = (EntityResolver) Class.forName(argv[++i]).newInstance(); } catch (Exception cnfe) { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[]{ "-EntityResolver" })); doExit(-1); } } else { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-EntityResolver" })); //"Missing argument for); doExit(-1); } } else if ("-CONTENTHANDLER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { contentHandler = (ContentHandler) Class.forName(argv[++i]).newInstance(); } catch (Exception cnfe) { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[]{ "-ContentHandler" })); doExit(-1); } } else { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-ContentHandler" })); //"Missing argument for); doExit(-1); } } else if ("-L".equalsIgnoreCase(argv[i])) useSourceLocation = true; else if ("-INCREMENTAL".equalsIgnoreCase(argv[i])) { tfactory.setAttribute ("http://xml.apache.org/xalan/features/incremental", java.lang.Boolean.TRUE); } else if ("-NOOPTIMIZE".equalsIgnoreCase(argv[i])) { // Default is true. // // %REVIEW% We should have a generalized syntax for negative // switches... and probably should accept the inverse even // if it is the default. tfactory.setAttribute ("http://xml.apache.org/xalan/features/optimize", java.lang.Boolean.FALSE); } else if ("-RL".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) recursionLimit = Integer.parseInt(argv[++i]); else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-rl" })); //"Missing argument for); } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_INVALID_OPTION, new Object[]{ argv[i] })); //"Invalid argument:); } // Note that there are usage cases for calling us without a -IN arg // The main XSL transformation occurs here! try { long start = System.currentTimeMillis(); if (null != dumpFileName) { dumpWriter = new PrintWriter(new FileWriter(dumpFileName)); } Templates stylesheet = null; if (null != xslFileName) { if (flavor.equals("d2d")) { // Parse in the xml data into a DOM DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); Node xslDOM = docBuilder.parse(new InputSource(xslFileName)); stylesheet = tfactory.newTemplates(new DOMSource(xslDOM, xslFileName)); } else { // System.out.println("Calling newTemplates: "+xslFileName); stylesheet = tfactory.newTemplates(new StreamSource(xslFileName)); // System.out.println("Done calling newTemplates: "+xslFileName); } } PrintWriter resultWriter; StreamResult strResult; if (null != outFileName) { strResult = new StreamResult(new FileOutputStream(outFileName)); + // One possible improvement might be to ensure this is + // a valid URI before setting the systemId, but that + // might have subtle changes that pre-existing users + // might notice; we can think about that later -sc r1.46 + strResult.setSystemId(outFileName); } else { strResult = new StreamResult(System.out); // We used to default to incremental mode in this case. // We've since decided that since the -INCREMENTAL switch is // available, that default is probably not necessary nor // necessarily a good idea. } SAXTransformerFactory stf = (SAXTransformerFactory) tfactory; // Did they pass in a stylesheet, or should we get it from the // document? if (null == stylesheet) { Source source = stf.getAssociatedStylesheet(new StreamSource(inFileName), media, null, null); if (null != source) stylesheet = tfactory.newTemplates(source); else { if (null != media) throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_IN_MEDIA, new Object[]{inFileName, media})); //"No stylesheet found in: " // + inFileName + ", media=" // + media); else throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_PI, new Object[]{inFileName})); //"No xml-stylesheet PI found in: " //+ inFileName); } } if (null != stylesheet) { Transformer transformer = flavor.equals("th") ? null : stylesheet.newTransformer(); // Override the output format? if (null != outputType) { transformer.setOutputProperty(OutputKeys.METHOD, outputType); } if (transformer instanceof TransformerImpl) { TransformerImpl impl = ((TransformerImpl) transformer); TraceManager tm = impl.getTraceManager(); if (null != tracer) tm.addTraceListener(tracer); impl.setQuietConflictWarnings(quietConflictWarnings); if (useSourceLocation) impl.setProperty(XalanProperties.SOURCE_LOCATION, Boolean.TRUE); if(recursionLimit>0) impl.setRecursionLimit(recursionLimit); // sc 28-Feb-01 if we re-implement this, please uncomment helpmsg in printArgOptions // impl.setDiagnosticsOutput( setQuietMode ? null : diagnosticsWriter ); } int nParams = params.size(); for (int i = 0; i < nParams; i += 2) { transformer.setParameter((String) params.elementAt(i), (String) params.elementAt(i + 1)); } if (uriResolver != null) transformer.setURIResolver(uriResolver); if (null != inFileName) { if (flavor.equals("d2d")) { // Parse in the xml data into a DOM DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setCoalescing(true); dfactory.setNamespaceAware(true); DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); if (entityResolver != null) docBuilder.setEntityResolver(entityResolver); Node xmlDoc = docBuilder.parse(new InputSource(inFileName)); Document doc = docBuilder.newDocument(); org.w3c.dom.DocumentFragment outNode = doc.createDocumentFragment(); transformer.transform(new DOMSource(xmlDoc, inFileName), new DOMResult(outNode)); // Now serialize output to disk with identity transformer Transformer serializer = stf.newTransformer(); Properties serializationProps = stylesheet.getOutputProperties(); serializer.setOutputProperties(serializationProps); if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); serializer.transform(new DOMSource(outNode), result); } else serializer.transform(new DOMSource(outNode), strResult); } else if (flavor.equals("th")) { for (int i = 0; i < 1; i++) // Loop for diagnosing bugs with inconsistent behavior { // System.out.println("Testing the TransformerHandler..."); // =============== XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2){} catch (AbstractMethodError ame){} if (null == reader) { reader = XMLReaderFactory.createXMLReader(); } stf.setAttribute(org.apache.xalan.processor.TransformerFactoryImpl.FEATURE_INCREMENTAL, Boolean.TRUE); TransformerHandler th = stf.newTransformerHandler(stylesheet); reader.setContentHandler(th); reader.setDTDHandler(th); if(th instanceof org.xml.sax.ErrorHandler) reader.setErrorHandler((org.xml.sax.ErrorHandler)th); try { reader.setProperty( "http://xml.org/sax/properties/lexical-handler", th); } catch (org.xml.sax.SAXNotRecognizedException e){} catch (org.xml.sax.SAXNotSupportedException e){} try { reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); } catch (org.xml.sax.SAXException se) {} try { reader.setFeature("http://apache.org/xml/features/validation/dynamic", true); } catch (org.xml.sax.SAXException se) {} th.setResult(strResult); // System.out.println("sending parse events to the handler..."); // for (int i = 0; i < 50; i++) { // System.out.print("."); // if((i % 50) == 0) // System.out.println(""); reader.parse(new InputSource(inFileName)); // Transformer t = ((org.apache.xalan.transformer.TransformerHandlerImpl)th).getTransformer(); // System.err.println("Calling reset"); // ((TransformerImpl)t).reset(); } // if (contentHandler != null) // { // SAXResult result = new SAXResult(contentHandler); // // transformer.transform( // new SAXSource(reader, new InputSource(inFileName)), result); // } // else // { // transformer.transform( // new SAXSource(reader, new InputSource(inFileName)), // strResult); // } // =============== } } else { if (entityResolver != null) { XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2){} catch (AbstractMethodError ame){} if (null == reader) { reader = XMLReaderFactory.createXMLReader(); } reader.setEntityResolver(entityResolver); if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); transformer.transform( new SAXSource(reader, new InputSource(inFileName)), result); } else { transformer.transform( new SAXSource(reader, new InputSource(inFileName)), strResult); } } else if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); transformer.transform(new StreamSource(inFileName), result); } else { // System.out.println("Starting transform"); transformer.transform(new StreamSource(inFileName), strResult); // System.out.println("Done with transform"); } } } else { StringReader reader = new StringReader("<?xml version=\"1.0\"?> <doc/>"); transformer.transform(new StreamSource(reader), strResult); } } else { diagnosticsWriter.println( XSLMessages.createMessage( XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful."); doExit(-1); } long stop = System.currentTimeMillis(); long millisecondsDuration = stop - start; if (doDiag) diagnosticsWriter.println("\n\n========\nTransform of " + inFileName + " via " + xslFileName + " took " + millisecondsDuration + " ms"); } catch (Throwable throwable) { while (throwable instanceof org.apache.xml.utils.WrappedRuntimeException) { throwable = ((org.apache.xml.utils.WrappedRuntimeException) throwable).getException(); } if ((throwable instanceof NullPointerException) || (throwable instanceof ClassCastException)) doStackDumpOnError = true; diagnosticsWriter.println(); if (doStackDumpOnError) throwable.printStackTrace(dumpWriter); else { DefaultErrorHandler.printLocation(diagnosticsWriter, throwable); diagnosticsWriter.println( XSLMessages.createMessage(XSLTErrorResources.ER_XSLT_ERROR, null) + " (" + throwable.getClass().getName() + "): " + throwable.getMessage()); } // diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful."); if (null != dumpFileName) { dumpWriter.close(); } doExit(-1); } if (null != dumpFileName) { dumpWriter.close(); } if (null != diagnosticsWriter) { // diagnosticsWriter.close(); } // if(!setQuietMode) // diagnosticsWriter.println(resbundle.getString("xsldone")); //"Xalan: done"); // else diagnosticsWriter.println(""); //"Xalan: done"); } } /** It is _much_ easier to debug under VJ++ if I can set a single breakpoint * before this blows itself out of the water... * (I keep checking this in, it keeps vanishing. Grr!) * */ static void doExit(int i) { System.exit(i); } }
true
true
public static void main(String argv[]) { // Runtime.getRuntime().traceMethodCalls(false); // turns Java tracing off boolean doStackDumpOnError = false; boolean setQuietMode = false; boolean doDiag = false; // Runtime.getRuntime().traceMethodCalls(false); // Runtime.getRuntime().traceInstructions(false); /** * The default diagnostic writer... */ java.io.PrintWriter diagnosticsWriter = new PrintWriter(System.err, true); java.io.PrintWriter dumpWriter = diagnosticsWriter; XSLTErrorResources resbundle = (XSLTErrorResources) (XSLMessages.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.ERROR_RESOURCES)); String flavor = "s2s"; if (argv.length < 1) { printArgOptions(resbundle); } else { TransformerFactory tfactory; try { tfactory = TransformerFactory.newInstance(); } catch (TransformerFactoryConfigurationError pfe) { pfe.printStackTrace(dumpWriter); diagnosticsWriter.println( XSLMessages.createMessage( XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful."); tfactory = null; // shut up compiler doExit(-1); } boolean formatOutput = false; boolean useSourceLocation = false; String inFileName = null; String outFileName = null; String dumpFileName = null; String xslFileName = null; String treedumpFileName = null; PrintTraceListener tracer = null; String outputType = null; String media = null; Vector params = new Vector(); boolean quietConflictWarnings = false; URIResolver uriResolver = null; EntityResolver entityResolver = null; ContentHandler contentHandler = null; int recursionLimit=-1; for (int i = 0; i < argv.length; i++) { if ("-TT".equalsIgnoreCase(argv[i])) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceTemplates = true; // tfactory.setTraceTemplates(true); } else if ("-TG".equalsIgnoreCase(argv[i])) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceGeneration = true; // tfactory.setTraceSelect(true); } else if ("-TS".equalsIgnoreCase(argv[i])) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceSelection = true; // tfactory.setTraceTemplates(true); } else if ("-TTC".equalsIgnoreCase(argv[i])) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceElements = true; // tfactory.setTraceTemplateChildren(true); } else if ("-INDENT".equalsIgnoreCase(argv[i])) { int indentAmount; if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) { indentAmount = Integer.parseInt(argv[++i]); } else { indentAmount = 0; } // TBD: // xmlProcessorLiaison.setIndent(indentAmount); } else if ("-IN".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) inFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-IN" })); //"Missing argument for); } else if ("-MEDIA".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) media = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-MEDIA" })); //"Missing argument for); } else if ("-OUT".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) outFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-OUT" })); //"Missing argument for); } else if ("-XSL".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) xslFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-XSL" })); //"Missing argument for); } else if ("-FLAVOR".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { flavor = argv[++i]; } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-FLAVOR" })); //"Missing argument for); } else if ("-PARAM".equalsIgnoreCase(argv[i])) { if (i + 2 < argv.length) { String name = argv[++i]; params.addElement(name); String expression = argv[++i]; params.addElement(expression); } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-PARAM" })); //"Missing argument for); } else if ("-TREEDUMP".equalsIgnoreCase(argv[i])) // sc 28-Feb-01 appears to be unused; can we remove? { if (i + 1 < argv.length) treedumpFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-treedump" })); //"Missing argument for); } else if ("-F".equalsIgnoreCase(argv[i])) // sc 28-Feb-01 appears to be unused; can we remove? { formatOutput = true; } else if ("-E".equalsIgnoreCase(argv[i])) { // TBD: // xmlProcessorLiaison.setShouldExpandEntityRefs(false); } else if ("-V".equalsIgnoreCase(argv[i])) { diagnosticsWriter.println(resbundle.getString("version") //">>>>>>> Xalan Version " + XSLProcessorVersion.S_VERSION + ", " + /* xmlProcessorLiaison.getParserDescription()+ */ resbundle.getString("version2")); // "<<<<<<<"); } else if ("-QC".equalsIgnoreCase(argv[i])) { quietConflictWarnings = true; } else if ("-Q".equalsIgnoreCase(argv[i])) { setQuietMode = true; } /* else if("-VALIDATE".equalsIgnoreCase(argv[i])) { String shouldValidate; if(((i+1) < argv.length) && (argv[i+1].charAt(0) != '-')) { shouldValidate = argv[++i]; } else { shouldValidate = "yes"; } // xmlProcessorLiaison.setUseValidation(shouldValidate.equalsIgnoreCase("yes")); } */ else if ("-DIAG".equalsIgnoreCase(argv[i])) { doDiag = true; } else if ("-XML".equalsIgnoreCase(argv[i])) { outputType = "xml"; } else if ("-TEXT".equalsIgnoreCase(argv[i])) { outputType = "text"; } else if ("-HTML".equalsIgnoreCase(argv[i])) { outputType = "html"; } else if ("-EDUMP".equalsIgnoreCase(argv[i])) { doStackDumpOnError = true; if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) { dumpFileName = argv[++i]; } } else if ("-URIRESOLVER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { uriResolver = (URIResolver) Class.forName(argv[++i]).newInstance(); tfactory.setURIResolver(uriResolver); } catch (Exception cnfe) { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[]{ "-URIResolver" })); doExit(-1); } } else { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-URIResolver" })); //"Missing argument for); doExit(-1); } } else if ("-ENTITYRESOLVER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { entityResolver = (EntityResolver) Class.forName(argv[++i]).newInstance(); } catch (Exception cnfe) { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[]{ "-EntityResolver" })); doExit(-1); } } else { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-EntityResolver" })); //"Missing argument for); doExit(-1); } } else if ("-CONTENTHANDLER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { contentHandler = (ContentHandler) Class.forName(argv[++i]).newInstance(); } catch (Exception cnfe) { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[]{ "-ContentHandler" })); doExit(-1); } } else { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-ContentHandler" })); //"Missing argument for); doExit(-1); } } else if ("-L".equalsIgnoreCase(argv[i])) useSourceLocation = true; else if ("-INCREMENTAL".equalsIgnoreCase(argv[i])) { tfactory.setAttribute ("http://xml.apache.org/xalan/features/incremental", java.lang.Boolean.TRUE); } else if ("-NOOPTIMIZE".equalsIgnoreCase(argv[i])) { // Default is true. // // %REVIEW% We should have a generalized syntax for negative // switches... and probably should accept the inverse even // if it is the default. tfactory.setAttribute ("http://xml.apache.org/xalan/features/optimize", java.lang.Boolean.FALSE); } else if ("-RL".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) recursionLimit = Integer.parseInt(argv[++i]); else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-rl" })); //"Missing argument for); } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_INVALID_OPTION, new Object[]{ argv[i] })); //"Invalid argument:); } // Note that there are usage cases for calling us without a -IN arg // The main XSL transformation occurs here! try { long start = System.currentTimeMillis(); if (null != dumpFileName) { dumpWriter = new PrintWriter(new FileWriter(dumpFileName)); } Templates stylesheet = null; if (null != xslFileName) { if (flavor.equals("d2d")) { // Parse in the xml data into a DOM DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); Node xslDOM = docBuilder.parse(new InputSource(xslFileName)); stylesheet = tfactory.newTemplates(new DOMSource(xslDOM, xslFileName)); } else { // System.out.println("Calling newTemplates: "+xslFileName); stylesheet = tfactory.newTemplates(new StreamSource(xslFileName)); // System.out.println("Done calling newTemplates: "+xslFileName); } } PrintWriter resultWriter; StreamResult strResult; if (null != outFileName) { strResult = new StreamResult(new FileOutputStream(outFileName)); } else { strResult = new StreamResult(System.out); // We used to default to incremental mode in this case. // We've since decided that since the -INCREMENTAL switch is // available, that default is probably not necessary nor // necessarily a good idea. } SAXTransformerFactory stf = (SAXTransformerFactory) tfactory; // Did they pass in a stylesheet, or should we get it from the // document? if (null == stylesheet) { Source source = stf.getAssociatedStylesheet(new StreamSource(inFileName), media, null, null); if (null != source) stylesheet = tfactory.newTemplates(source); else { if (null != media) throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_IN_MEDIA, new Object[]{inFileName, media})); //"No stylesheet found in: " // + inFileName + ", media=" // + media); else throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_PI, new Object[]{inFileName})); //"No xml-stylesheet PI found in: " //+ inFileName); } } if (null != stylesheet) { Transformer transformer = flavor.equals("th") ? null : stylesheet.newTransformer(); // Override the output format? if (null != outputType) { transformer.setOutputProperty(OutputKeys.METHOD, outputType); } if (transformer instanceof TransformerImpl) { TransformerImpl impl = ((TransformerImpl) transformer); TraceManager tm = impl.getTraceManager(); if (null != tracer) tm.addTraceListener(tracer); impl.setQuietConflictWarnings(quietConflictWarnings); if (useSourceLocation) impl.setProperty(XalanProperties.SOURCE_LOCATION, Boolean.TRUE); if(recursionLimit>0) impl.setRecursionLimit(recursionLimit); // sc 28-Feb-01 if we re-implement this, please uncomment helpmsg in printArgOptions // impl.setDiagnosticsOutput( setQuietMode ? null : diagnosticsWriter ); } int nParams = params.size(); for (int i = 0; i < nParams; i += 2) { transformer.setParameter((String) params.elementAt(i), (String) params.elementAt(i + 1)); } if (uriResolver != null) transformer.setURIResolver(uriResolver); if (null != inFileName) { if (flavor.equals("d2d")) { // Parse in the xml data into a DOM DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setCoalescing(true); dfactory.setNamespaceAware(true); DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); if (entityResolver != null) docBuilder.setEntityResolver(entityResolver); Node xmlDoc = docBuilder.parse(new InputSource(inFileName)); Document doc = docBuilder.newDocument(); org.w3c.dom.DocumentFragment outNode = doc.createDocumentFragment(); transformer.transform(new DOMSource(xmlDoc, inFileName), new DOMResult(outNode)); // Now serialize output to disk with identity transformer Transformer serializer = stf.newTransformer(); Properties serializationProps = stylesheet.getOutputProperties(); serializer.setOutputProperties(serializationProps); if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); serializer.transform(new DOMSource(outNode), result); } else serializer.transform(new DOMSource(outNode), strResult); } else if (flavor.equals("th")) { for (int i = 0; i < 1; i++) // Loop for diagnosing bugs with inconsistent behavior { // System.out.println("Testing the TransformerHandler..."); // =============== XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2){} catch (AbstractMethodError ame){} if (null == reader) { reader = XMLReaderFactory.createXMLReader(); } stf.setAttribute(org.apache.xalan.processor.TransformerFactoryImpl.FEATURE_INCREMENTAL, Boolean.TRUE); TransformerHandler th = stf.newTransformerHandler(stylesheet); reader.setContentHandler(th); reader.setDTDHandler(th); if(th instanceof org.xml.sax.ErrorHandler) reader.setErrorHandler((org.xml.sax.ErrorHandler)th); try { reader.setProperty( "http://xml.org/sax/properties/lexical-handler", th); } catch (org.xml.sax.SAXNotRecognizedException e){} catch (org.xml.sax.SAXNotSupportedException e){} try { reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); } catch (org.xml.sax.SAXException se) {} try { reader.setFeature("http://apache.org/xml/features/validation/dynamic", true); } catch (org.xml.sax.SAXException se) {} th.setResult(strResult); // System.out.println("sending parse events to the handler..."); // for (int i = 0; i < 50; i++) { // System.out.print("."); // if((i % 50) == 0) // System.out.println(""); reader.parse(new InputSource(inFileName)); // Transformer t = ((org.apache.xalan.transformer.TransformerHandlerImpl)th).getTransformer(); // System.err.println("Calling reset"); // ((TransformerImpl)t).reset(); } // if (contentHandler != null) // { // SAXResult result = new SAXResult(contentHandler); // // transformer.transform( // new SAXSource(reader, new InputSource(inFileName)), result); // } // else // { // transformer.transform( // new SAXSource(reader, new InputSource(inFileName)), // strResult); // } // =============== } } else { if (entityResolver != null) { XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2){} catch (AbstractMethodError ame){} if (null == reader) { reader = XMLReaderFactory.createXMLReader(); } reader.setEntityResolver(entityResolver); if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); transformer.transform( new SAXSource(reader, new InputSource(inFileName)), result); } else { transformer.transform( new SAXSource(reader, new InputSource(inFileName)), strResult); } } else if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); transformer.transform(new StreamSource(inFileName), result); } else { // System.out.println("Starting transform"); transformer.transform(new StreamSource(inFileName), strResult); // System.out.println("Done with transform"); } } } else { StringReader reader = new StringReader("<?xml version=\"1.0\"?> <doc/>"); transformer.transform(new StreamSource(reader), strResult); } } else { diagnosticsWriter.println( XSLMessages.createMessage( XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful."); doExit(-1); } long stop = System.currentTimeMillis(); long millisecondsDuration = stop - start; if (doDiag) diagnosticsWriter.println("\n\n========\nTransform of " + inFileName + " via " + xslFileName + " took " + millisecondsDuration + " ms"); } catch (Throwable throwable) { while (throwable instanceof org.apache.xml.utils.WrappedRuntimeException) { throwable = ((org.apache.xml.utils.WrappedRuntimeException) throwable).getException(); } if ((throwable instanceof NullPointerException) || (throwable instanceof ClassCastException)) doStackDumpOnError = true; diagnosticsWriter.println(); if (doStackDumpOnError) throwable.printStackTrace(dumpWriter); else { DefaultErrorHandler.printLocation(diagnosticsWriter, throwable); diagnosticsWriter.println( XSLMessages.createMessage(XSLTErrorResources.ER_XSLT_ERROR, null) + " (" + throwable.getClass().getName() + "): " + throwable.getMessage()); } // diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful."); if (null != dumpFileName) { dumpWriter.close(); } doExit(-1); } if (null != dumpFileName) { dumpWriter.close(); } if (null != diagnosticsWriter) { // diagnosticsWriter.close(); } // if(!setQuietMode) // diagnosticsWriter.println(resbundle.getString("xsldone")); //"Xalan: done"); // else diagnosticsWriter.println(""); //"Xalan: done"); } } /** It is _much_ easier to debug under VJ++ if I can set a single breakpoint * before this blows itself out of the water... * (I keep checking this in, it keeps vanishing. Grr!) * */ static void doExit(int i) { System.exit(i); } }
public static void main(String argv[]) { // Runtime.getRuntime().traceMethodCalls(false); // turns Java tracing off boolean doStackDumpOnError = false; boolean setQuietMode = false; boolean doDiag = false; // Runtime.getRuntime().traceMethodCalls(false); // Runtime.getRuntime().traceInstructions(false); /** * The default diagnostic writer... */ java.io.PrintWriter diagnosticsWriter = new PrintWriter(System.err, true); java.io.PrintWriter dumpWriter = diagnosticsWriter; XSLTErrorResources resbundle = (XSLTErrorResources) (XSLMessages.loadResourceBundle( org.apache.xml.utils.res.XResourceBundle.ERROR_RESOURCES)); String flavor = "s2s"; if (argv.length < 1) { printArgOptions(resbundle); } else { TransformerFactory tfactory; try { tfactory = TransformerFactory.newInstance(); } catch (TransformerFactoryConfigurationError pfe) { pfe.printStackTrace(dumpWriter); diagnosticsWriter.println( XSLMessages.createMessage( XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful."); tfactory = null; // shut up compiler doExit(-1); } boolean formatOutput = false; boolean useSourceLocation = false; String inFileName = null; String outFileName = null; String dumpFileName = null; String xslFileName = null; String treedumpFileName = null; PrintTraceListener tracer = null; String outputType = null; String media = null; Vector params = new Vector(); boolean quietConflictWarnings = false; URIResolver uriResolver = null; EntityResolver entityResolver = null; ContentHandler contentHandler = null; int recursionLimit=-1; for (int i = 0; i < argv.length; i++) { if ("-TT".equalsIgnoreCase(argv[i])) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceTemplates = true; // tfactory.setTraceTemplates(true); } else if ("-TG".equalsIgnoreCase(argv[i])) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceGeneration = true; // tfactory.setTraceSelect(true); } else if ("-TS".equalsIgnoreCase(argv[i])) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceSelection = true; // tfactory.setTraceTemplates(true); } else if ("-TTC".equalsIgnoreCase(argv[i])) { if (null == tracer) tracer = new PrintTraceListener(diagnosticsWriter); tracer.m_traceElements = true; // tfactory.setTraceTemplateChildren(true); } else if ("-INDENT".equalsIgnoreCase(argv[i])) { int indentAmount; if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) { indentAmount = Integer.parseInt(argv[++i]); } else { indentAmount = 0; } // TBD: // xmlProcessorLiaison.setIndent(indentAmount); } else if ("-IN".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) inFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-IN" })); //"Missing argument for); } else if ("-MEDIA".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) media = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-MEDIA" })); //"Missing argument for); } else if ("-OUT".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) outFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-OUT" })); //"Missing argument for); } else if ("-XSL".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) xslFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-XSL" })); //"Missing argument for); } else if ("-FLAVOR".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { flavor = argv[++i]; } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-FLAVOR" })); //"Missing argument for); } else if ("-PARAM".equalsIgnoreCase(argv[i])) { if (i + 2 < argv.length) { String name = argv[++i]; params.addElement(name); String expression = argv[++i]; params.addElement(expression); } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-PARAM" })); //"Missing argument for); } else if ("-TREEDUMP".equalsIgnoreCase(argv[i])) // sc 28-Feb-01 appears to be unused; can we remove? { if (i + 1 < argv.length) treedumpFileName = argv[++i]; else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-treedump" })); //"Missing argument for); } else if ("-F".equalsIgnoreCase(argv[i])) // sc 28-Feb-01 appears to be unused; can we remove? { formatOutput = true; } else if ("-E".equalsIgnoreCase(argv[i])) { // TBD: // xmlProcessorLiaison.setShouldExpandEntityRefs(false); } else if ("-V".equalsIgnoreCase(argv[i])) { diagnosticsWriter.println(resbundle.getString("version") //">>>>>>> Xalan Version " + XSLProcessorVersion.S_VERSION + ", " + /* xmlProcessorLiaison.getParserDescription()+ */ resbundle.getString("version2")); // "<<<<<<<"); } else if ("-QC".equalsIgnoreCase(argv[i])) { quietConflictWarnings = true; } else if ("-Q".equalsIgnoreCase(argv[i])) { setQuietMode = true; } /* else if("-VALIDATE".equalsIgnoreCase(argv[i])) { String shouldValidate; if(((i+1) < argv.length) && (argv[i+1].charAt(0) != '-')) { shouldValidate = argv[++i]; } else { shouldValidate = "yes"; } // xmlProcessorLiaison.setUseValidation(shouldValidate.equalsIgnoreCase("yes")); } */ else if ("-DIAG".equalsIgnoreCase(argv[i])) { doDiag = true; } else if ("-XML".equalsIgnoreCase(argv[i])) { outputType = "xml"; } else if ("-TEXT".equalsIgnoreCase(argv[i])) { outputType = "text"; } else if ("-HTML".equalsIgnoreCase(argv[i])) { outputType = "html"; } else if ("-EDUMP".equalsIgnoreCase(argv[i])) { doStackDumpOnError = true; if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) { dumpFileName = argv[++i]; } } else if ("-URIRESOLVER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { uriResolver = (URIResolver) Class.forName(argv[++i]).newInstance(); tfactory.setURIResolver(uriResolver); } catch (Exception cnfe) { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[]{ "-URIResolver" })); doExit(-1); } } else { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-URIResolver" })); //"Missing argument for); doExit(-1); } } else if ("-ENTITYRESOLVER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { entityResolver = (EntityResolver) Class.forName(argv[++i]).newInstance(); } catch (Exception cnfe) { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[]{ "-EntityResolver" })); doExit(-1); } } else { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-EntityResolver" })); //"Missing argument for); doExit(-1); } } else if ("-CONTENTHANDLER".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) { try { contentHandler = (ContentHandler) Class.forName(argv[++i]).newInstance(); } catch (Exception cnfe) { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION, new Object[]{ "-ContentHandler" })); doExit(-1); } } else { System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-ContentHandler" })); //"Missing argument for); doExit(-1); } } else if ("-L".equalsIgnoreCase(argv[i])) useSourceLocation = true; else if ("-INCREMENTAL".equalsIgnoreCase(argv[i])) { tfactory.setAttribute ("http://xml.apache.org/xalan/features/incremental", java.lang.Boolean.TRUE); } else if ("-NOOPTIMIZE".equalsIgnoreCase(argv[i])) { // Default is true. // // %REVIEW% We should have a generalized syntax for negative // switches... and probably should accept the inverse even // if it is the default. tfactory.setAttribute ("http://xml.apache.org/xalan/features/optimize", java.lang.Boolean.FALSE); } else if ("-RL".equalsIgnoreCase(argv[i])) { if (i + 1 < argv.length) recursionLimit = Integer.parseInt(argv[++i]); else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[]{ "-rl" })); //"Missing argument for); } else System.err.println( XSLMessages.createMessage( XSLTErrorResources.ER_INVALID_OPTION, new Object[]{ argv[i] })); //"Invalid argument:); } // Note that there are usage cases for calling us without a -IN arg // The main XSL transformation occurs here! try { long start = System.currentTimeMillis(); if (null != dumpFileName) { dumpWriter = new PrintWriter(new FileWriter(dumpFileName)); } Templates stylesheet = null; if (null != xslFileName) { if (flavor.equals("d2d")) { // Parse in the xml data into a DOM DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); Node xslDOM = docBuilder.parse(new InputSource(xslFileName)); stylesheet = tfactory.newTemplates(new DOMSource(xslDOM, xslFileName)); } else { // System.out.println("Calling newTemplates: "+xslFileName); stylesheet = tfactory.newTemplates(new StreamSource(xslFileName)); // System.out.println("Done calling newTemplates: "+xslFileName); } } PrintWriter resultWriter; StreamResult strResult; if (null != outFileName) { strResult = new StreamResult(new FileOutputStream(outFileName)); // One possible improvement might be to ensure this is // a valid URI before setting the systemId, but that // might have subtle changes that pre-existing users // might notice; we can think about that later -sc r1.46 strResult.setSystemId(outFileName); } else { strResult = new StreamResult(System.out); // We used to default to incremental mode in this case. // We've since decided that since the -INCREMENTAL switch is // available, that default is probably not necessary nor // necessarily a good idea. } SAXTransformerFactory stf = (SAXTransformerFactory) tfactory; // Did they pass in a stylesheet, or should we get it from the // document? if (null == stylesheet) { Source source = stf.getAssociatedStylesheet(new StreamSource(inFileName), media, null, null); if (null != source) stylesheet = tfactory.newTemplates(source); else { if (null != media) throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_IN_MEDIA, new Object[]{inFileName, media})); //"No stylesheet found in: " // + inFileName + ", media=" // + media); else throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_PI, new Object[]{inFileName})); //"No xml-stylesheet PI found in: " //+ inFileName); } } if (null != stylesheet) { Transformer transformer = flavor.equals("th") ? null : stylesheet.newTransformer(); // Override the output format? if (null != outputType) { transformer.setOutputProperty(OutputKeys.METHOD, outputType); } if (transformer instanceof TransformerImpl) { TransformerImpl impl = ((TransformerImpl) transformer); TraceManager tm = impl.getTraceManager(); if (null != tracer) tm.addTraceListener(tracer); impl.setQuietConflictWarnings(quietConflictWarnings); if (useSourceLocation) impl.setProperty(XalanProperties.SOURCE_LOCATION, Boolean.TRUE); if(recursionLimit>0) impl.setRecursionLimit(recursionLimit); // sc 28-Feb-01 if we re-implement this, please uncomment helpmsg in printArgOptions // impl.setDiagnosticsOutput( setQuietMode ? null : diagnosticsWriter ); } int nParams = params.size(); for (int i = 0; i < nParams; i += 2) { transformer.setParameter((String) params.elementAt(i), (String) params.elementAt(i + 1)); } if (uriResolver != null) transformer.setURIResolver(uriResolver); if (null != inFileName) { if (flavor.equals("d2d")) { // Parse in the xml data into a DOM DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setCoalescing(true); dfactory.setNamespaceAware(true); DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); if (entityResolver != null) docBuilder.setEntityResolver(entityResolver); Node xmlDoc = docBuilder.parse(new InputSource(inFileName)); Document doc = docBuilder.newDocument(); org.w3c.dom.DocumentFragment outNode = doc.createDocumentFragment(); transformer.transform(new DOMSource(xmlDoc, inFileName), new DOMResult(outNode)); // Now serialize output to disk with identity transformer Transformer serializer = stf.newTransformer(); Properties serializationProps = stylesheet.getOutputProperties(); serializer.setOutputProperties(serializationProps); if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); serializer.transform(new DOMSource(outNode), result); } else serializer.transform(new DOMSource(outNode), strResult); } else if (flavor.equals("th")) { for (int i = 0; i < 1; i++) // Loop for diagnosing bugs with inconsistent behavior { // System.out.println("Testing the TransformerHandler..."); // =============== XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2){} catch (AbstractMethodError ame){} if (null == reader) { reader = XMLReaderFactory.createXMLReader(); } stf.setAttribute(org.apache.xalan.processor.TransformerFactoryImpl.FEATURE_INCREMENTAL, Boolean.TRUE); TransformerHandler th = stf.newTransformerHandler(stylesheet); reader.setContentHandler(th); reader.setDTDHandler(th); if(th instanceof org.xml.sax.ErrorHandler) reader.setErrorHandler((org.xml.sax.ErrorHandler)th); try { reader.setProperty( "http://xml.org/sax/properties/lexical-handler", th); } catch (org.xml.sax.SAXNotRecognizedException e){} catch (org.xml.sax.SAXNotSupportedException e){} try { reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); } catch (org.xml.sax.SAXException se) {} try { reader.setFeature("http://apache.org/xml/features/validation/dynamic", true); } catch (org.xml.sax.SAXException se) {} th.setResult(strResult); // System.out.println("sending parse events to the handler..."); // for (int i = 0; i < 50; i++) { // System.out.print("."); // if((i % 50) == 0) // System.out.println(""); reader.parse(new InputSource(inFileName)); // Transformer t = ((org.apache.xalan.transformer.TransformerHandlerImpl)th).getTransformer(); // System.err.println("Calling reset"); // ((TransformerImpl)t).reset(); } // if (contentHandler != null) // { // SAXResult result = new SAXResult(contentHandler); // // transformer.transform( // new SAXSource(reader, new InputSource(inFileName)), result); // } // else // { // transformer.transform( // new SAXSource(reader, new InputSource(inFileName)), // strResult); // } // =============== } } else { if (entityResolver != null) { XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2){} catch (AbstractMethodError ame){} if (null == reader) { reader = XMLReaderFactory.createXMLReader(); } reader.setEntityResolver(entityResolver); if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); transformer.transform( new SAXSource(reader, new InputSource(inFileName)), result); } else { transformer.transform( new SAXSource(reader, new InputSource(inFileName)), strResult); } } else if (contentHandler != null) { SAXResult result = new SAXResult(contentHandler); transformer.transform(new StreamSource(inFileName), result); } else { // System.out.println("Starting transform"); transformer.transform(new StreamSource(inFileName), strResult); // System.out.println("Done with transform"); } } } else { StringReader reader = new StringReader("<?xml version=\"1.0\"?> <doc/>"); transformer.transform(new StreamSource(reader), strResult); } } else { diagnosticsWriter.println( XSLMessages.createMessage( XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful."); doExit(-1); } long stop = System.currentTimeMillis(); long millisecondsDuration = stop - start; if (doDiag) diagnosticsWriter.println("\n\n========\nTransform of " + inFileName + " via " + xslFileName + " took " + millisecondsDuration + " ms"); } catch (Throwable throwable) { while (throwable instanceof org.apache.xml.utils.WrappedRuntimeException) { throwable = ((org.apache.xml.utils.WrappedRuntimeException) throwable).getException(); } if ((throwable instanceof NullPointerException) || (throwable instanceof ClassCastException)) doStackDumpOnError = true; diagnosticsWriter.println(); if (doStackDumpOnError) throwable.printStackTrace(dumpWriter); else { DefaultErrorHandler.printLocation(diagnosticsWriter, throwable); diagnosticsWriter.println( XSLMessages.createMessage(XSLTErrorResources.ER_XSLT_ERROR, null) + " (" + throwable.getClass().getName() + "): " + throwable.getMessage()); } // diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful."); if (null != dumpFileName) { dumpWriter.close(); } doExit(-1); } if (null != dumpFileName) { dumpWriter.close(); } if (null != diagnosticsWriter) { // diagnosticsWriter.close(); } // if(!setQuietMode) // diagnosticsWriter.println(resbundle.getString("xsldone")); //"Xalan: done"); // else diagnosticsWriter.println(""); //"Xalan: done"); } } /** It is _much_ easier to debug under VJ++ if I can set a single breakpoint * before this blows itself out of the water... * (I keep checking this in, it keeps vanishing. Grr!) * */ static void doExit(int i) { System.exit(i); } }
diff --git a/src/main/java/hudson/plugins/nunit/NUnitReportTransformer.java b/src/main/java/hudson/plugins/nunit/NUnitReportTransformer.java index a475196..d37250e 100644 --- a/src/main/java/hudson/plugins/nunit/NUnitReportTransformer.java +++ b/src/main/java/hudson/plugins/nunit/NUnitReportTransformer.java @@ -1,117 +1,117 @@ package hudson.plugins.nunit; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Transforms a NUnit report into seperate JUnit reports. The NUnit report can contain several test cases and the JUnit * report that is read by Jenkins should only contain one. This class will split up one NUnit report into several JUnit * files. * */ public class NUnitReportTransformer implements TestReportTransformer, Serializable { private static final String ILLEGAL_FILE_CHARS_REGEX = "[\\*/:<>\\?\\|\\\\\";]+"; private static final long serialVersionUID = 1L; public static final String JUNIT_FILE_POSTFIX = ".xml"; public static final String JUNIT_FILE_PREFIX = "TEST-"; private static final String TEMP_JUNIT_FILE_STR = "temp-junit.xml"; public static final String NUNIT_TO_JUNIT_XSLFILE_STR = "nunit-to-junit.xsl"; private transient boolean xslIsInitialized; private transient Transformer nunitTransformer; private transient Transformer writerTransformer; private transient DocumentBuilder xmlDocumentBuilder; /** * Transform the nunit file into several junit files in the output path * * @param nunitFileStream the nunit file stream to transform * @param junitOutputPath the output path to put all junit files * @throws IOException thrown if there was any problem with the transform. * @throws TransformerException * @throws SAXException * @throws ParserConfigurationException */ public void transform(InputStream nunitFileStream, File junitOutputPath) throws IOException, TransformerException, SAXException, ParserConfigurationException { initialize(); File junitTargetFile = new File(junitOutputPath, TEMP_JUNIT_FILE_STR); FileOutputStream fileOutputStream = new FileOutputStream(junitTargetFile); try { nunitTransformer.transform(new StreamSource(nunitFileStream), new StreamResult(fileOutputStream)); } finally { fileOutputStream.close(); } splitJUnitFile(junitTargetFile, junitOutputPath); junitTargetFile.delete(); } private void initialize() throws TransformerFactoryConfigurationError, TransformerConfigurationException, ParserConfigurationException { if (!xslIsInitialized) { TransformerFactory transformerFactory = TransformerFactory.newInstance(); nunitTransformer = transformerFactory.newTransformer(new StreamSource(this.getClass().getResourceAsStream(NUNIT_TO_JUNIT_XSLFILE_STR))); writerTransformer = transformerFactory.newTransformer(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); xmlDocumentBuilder = factory.newDocumentBuilder(); xslIsInitialized = true; } } /** * Splits the junit file into several junit files in the output path * * @param junitFile report containing one or more junit test suite tags * @param junitOutputPath the path to put all junit files * @throws IOException * @throws SAXException * @throws TransformerException */ private void splitJUnitFile(File junitFile, File junitOutputPath) throws SAXException, IOException, TransformerException { Document document = xmlDocumentBuilder.parse(junitFile); NodeList elementsByTagName = ((Element) document.getElementsByTagName("testsuites").item(0)).getElementsByTagName("testsuite"); for (int i = 0; i < elementsByTagName.getLength(); i++) { Element element = (Element) elementsByTagName.item(i); DOMSource source = new DOMSource(element); - String filename = JUNIT_FILE_PREFIX + element.getAttribute("name").replaceAll(ILLEGAL_FILE_CHARS_REGEX, "_") + System.currentTimeMillis() + JUNIT_FILE_POSTFIX; + String filename = JUNIT_FILE_PREFIX + element.getAttribute("name").replaceAll(ILLEGAL_FILE_CHARS_REGEX, "_") + "_" + i + JUNIT_FILE_POSTFIX; File junitOutputFile = new File(junitOutputPath, filename); FileOutputStream fileOutputStream = new FileOutputStream(junitOutputFile); try { StreamResult result = new StreamResult(fileOutputStream); writerTransformer.transform(source, result); } finally { fileOutputStream.close(); } } } }
true
true
private void splitJUnitFile(File junitFile, File junitOutputPath) throws SAXException, IOException, TransformerException { Document document = xmlDocumentBuilder.parse(junitFile); NodeList elementsByTagName = ((Element) document.getElementsByTagName("testsuites").item(0)).getElementsByTagName("testsuite"); for (int i = 0; i < elementsByTagName.getLength(); i++) { Element element = (Element) elementsByTagName.item(i); DOMSource source = new DOMSource(element); String filename = JUNIT_FILE_PREFIX + element.getAttribute("name").replaceAll(ILLEGAL_FILE_CHARS_REGEX, "_") + System.currentTimeMillis() + JUNIT_FILE_POSTFIX; File junitOutputFile = new File(junitOutputPath, filename); FileOutputStream fileOutputStream = new FileOutputStream(junitOutputFile); try { StreamResult result = new StreamResult(fileOutputStream); writerTransformer.transform(source, result); } finally { fileOutputStream.close(); } } }
private void splitJUnitFile(File junitFile, File junitOutputPath) throws SAXException, IOException, TransformerException { Document document = xmlDocumentBuilder.parse(junitFile); NodeList elementsByTagName = ((Element) document.getElementsByTagName("testsuites").item(0)).getElementsByTagName("testsuite"); for (int i = 0; i < elementsByTagName.getLength(); i++) { Element element = (Element) elementsByTagName.item(i); DOMSource source = new DOMSource(element); String filename = JUNIT_FILE_PREFIX + element.getAttribute("name").replaceAll(ILLEGAL_FILE_CHARS_REGEX, "_") + "_" + i + JUNIT_FILE_POSTFIX; File junitOutputFile = new File(junitOutputPath, filename); FileOutputStream fileOutputStream = new FileOutputStream(junitOutputFile); try { StreamResult result = new StreamResult(fileOutputStream); writerTransformer.transform(source, result); } finally { fileOutputStream.close(); } } }
diff --git a/src/main/java/com/greatmancode/craftconomy3/utils/VersionChecker.java b/src/main/java/com/greatmancode/craftconomy3/utils/VersionChecker.java index 6372a1f..19ae57c 100644 --- a/src/main/java/com/greatmancode/craftconomy3/utils/VersionChecker.java +++ b/src/main/java/com/greatmancode/craftconomy3/utils/VersionChecker.java @@ -1,69 +1,73 @@ /* * This file is part of Craftconomy3. * * Copyright (c) 2011-2012, Greatman <http://github.com/greatman/> * * Craftconomy3 is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Craftconomy3 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 Craftconomy3. If not, see <http://www.gnu.org/licenses/>. */ package com.greatmancode.craftconomy3.utils; import java.net.URL; import java.util.logging.Level; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.greatmancode.craftconomy3.Common; public class VersionChecker { private boolean oldVersion = false; private String newVersion = ""; public VersionChecker(String currentVersion) { + if (Common.getInstance().getServerCaller().getPluginVersion().contains("SNAPSHOT")) { + Common.getInstance().sendConsoleMessage(Level.WARNING, "You are running a dev-build! Be sure that you check on the website if there's a new version!"); + return; + } String pluginUrlString = "http://dev.bukkit.org/server-mods/craftconomy/files.rss"; try { URL url = new URL(pluginUrlString); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openConnection().getInputStream()); doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("item"); Node firstNode = nodes.item(0); if (firstNode.getNodeType() == 1) { Element firstElement = (Element) firstNode; NodeList firstElementTagName = firstElement.getElementsByTagName("title"); Element firstNameElement = (Element) firstElementTagName.item(0); NodeList firstNodes = firstNameElement.getChildNodes(); if (!currentVersion.contains(firstNodes.item(0).getNodeValue())) { oldVersion = true; newVersion = firstNodes.item(0).getNodeValue(); } } } catch (Exception e) { Common.getInstance().sendConsoleMessage(Level.SEVERE, "Error while trying to check for the latest version. The error is: " + e.getMessage()); } } public boolean isOld() { return oldVersion; } public String getNewVersion() { return newVersion; } }
true
true
public VersionChecker(String currentVersion) { String pluginUrlString = "http://dev.bukkit.org/server-mods/craftconomy/files.rss"; try { URL url = new URL(pluginUrlString); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openConnection().getInputStream()); doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("item"); Node firstNode = nodes.item(0); if (firstNode.getNodeType() == 1) { Element firstElement = (Element) firstNode; NodeList firstElementTagName = firstElement.getElementsByTagName("title"); Element firstNameElement = (Element) firstElementTagName.item(0); NodeList firstNodes = firstNameElement.getChildNodes(); if (!currentVersion.contains(firstNodes.item(0).getNodeValue())) { oldVersion = true; newVersion = firstNodes.item(0).getNodeValue(); } } } catch (Exception e) { Common.getInstance().sendConsoleMessage(Level.SEVERE, "Error while trying to check for the latest version. The error is: " + e.getMessage()); } }
public VersionChecker(String currentVersion) { if (Common.getInstance().getServerCaller().getPluginVersion().contains("SNAPSHOT")) { Common.getInstance().sendConsoleMessage(Level.WARNING, "You are running a dev-build! Be sure that you check on the website if there's a new version!"); return; } String pluginUrlString = "http://dev.bukkit.org/server-mods/craftconomy/files.rss"; try { URL url = new URL(pluginUrlString); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openConnection().getInputStream()); doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("item"); Node firstNode = nodes.item(0); if (firstNode.getNodeType() == 1) { Element firstElement = (Element) firstNode; NodeList firstElementTagName = firstElement.getElementsByTagName("title"); Element firstNameElement = (Element) firstElementTagName.item(0); NodeList firstNodes = firstNameElement.getChildNodes(); if (!currentVersion.contains(firstNodes.item(0).getNodeValue())) { oldVersion = true; newVersion = firstNodes.item(0).getNodeValue(); } } } catch (Exception e) { Common.getInstance().sendConsoleMessage(Level.SEVERE, "Error while trying to check for the latest version. The error is: " + e.getMessage()); } }
diff --git a/AuctionHouse/src/webServiceClient/WebServiceClientThread.java b/AuctionHouse/src/webServiceClient/WebServiceClientThread.java index f94daa4..c9e6db6 100644 --- a/AuctionHouse/src/webServiceClient/WebServiceClientThread.java +++ b/AuctionHouse/src/webServiceClient/WebServiceClientThread.java @@ -1,162 +1,162 @@ package webServiceClient; import interfaces.MediatorWeb; import java.util.ArrayList; import java.util.Date; import java.util.Hashtable; import java.util.Map; import java.util.Random; import data.LoginCred; import data.Service; import data.UserEntry; import data.UserProfile; import data.Service.Status; import data.UserEntry.Offer; import data.UserProfile.UserRole; public class WebServiceClientThread extends Thread { private boolean running; private Random random; private Date date; private MediatorWeb med; private Hashtable<String, Service> offers; private Hashtable<String, UserProfile> users; public WebServiceClientThread(MediatorWeb med) { this.med = med; random = new Random(); date = new Date(); users = new Hashtable<String, UserProfile>(); offers = new Hashtable<String, Service>(); users.put("pvlase", new UserProfile("pvlase","Paul", "Vlase", UserRole.BUYER, "parola")); users.put("unix140", new UserProfile("unix140","Ghennadi", "Procopciuc", UserRole.BUYER, "marmota")); } public void run() { int timeLimit = 2500; running = true; try { while (isRunning()) { int sleepTime = 1000 + random.nextInt(timeLimit); Thread.sleep(sleepTime); for (Map.Entry<String, Service> offer: offers.entrySet()) { Service service = offer.getValue(); int event = random.nextInt(1000); System.out.println("event = " + event); if (event < 200) { String username = getRandomString(5 + Math.abs(random.nextInt(16))); - Long time = date.getTime() + Math.abs(random.nextInt(100000)); + Long time = date.getTime() + Math.abs(random.nextInt(10000)); Double price = Math.abs(random.nextInt(10000)) / 100.0; UserEntry user = new UserEntry(username, Offer.NO_OFFER, time, price); service.addUserEntry(user); med.newUserNotify(service); } } } } catch (InterruptedException e) { e.printStackTrace(); } } private String getRandomString(int len) { char[] str = new char[len]; for (int i = 0; i < len; i++) { int c; do { c = 48 + random.nextInt(123 - 48); } while((c >= 91 && c <= 96) || (c >= 58 && c <= 64)); str[i] = (char) c; } System.out.println(new String(str)); return new String(str); } public synchronized void stopThread() { running = false; } public synchronized boolean isRunning() { return running; } public UserProfile logIn(LoginCred cred) { UserProfile profile; profile = getUserProfile(cred.getUsername()); if (profile == null) { return null; } if (!profile.getPassword().equals(cred.getPassword())) { return null; } return profile; } public void logOut() { System.out.println("[WebServiceClientThread:logOut()] Bye bye"); } public synchronized UserProfile getUserProfile(String username) { return users.get(username); } public synchronized boolean setUserProfile(UserProfile profile) { users.put(profile.getUsername(), profile); return true; } /* Common */ public synchronized boolean launchOffer(Service service) { service.setStatus(Status.ACTIVE); offers.put(service.getName(), service); System.out.println("[WebServiceClientMockup:addOffer] " + service.getName()); return true; } public synchronized boolean launchOffers(ArrayList<Service> services) { for (Service service: services) { service.setStatus(Status.ACTIVE); offers.put(service.getName(), service); System.out.println("[WebServiceClientMockup:addOffers] " + service.getName()); } return true; } public synchronized boolean dropOffer(Service service) { service.setStatus(Status.INACTIVE); offers.remove(service.getName()); System.out.println("[WebServiceClientMockup:dropOffer] " + service.getName()); return true; } public synchronized boolean dropOffers(ArrayList<Service> services) { for (Service service: services) { service.setStatus(Status.INACTIVE); offers.remove(service.getName()); System.out.println("[WebServiceClientMockup:dropOffers] " + service.getName()); } return true; } }
true
true
public void run() { int timeLimit = 2500; running = true; try { while (isRunning()) { int sleepTime = 1000 + random.nextInt(timeLimit); Thread.sleep(sleepTime); for (Map.Entry<String, Service> offer: offers.entrySet()) { Service service = offer.getValue(); int event = random.nextInt(1000); System.out.println("event = " + event); if (event < 200) { String username = getRandomString(5 + Math.abs(random.nextInt(16))); Long time = date.getTime() + Math.abs(random.nextInt(100000)); Double price = Math.abs(random.nextInt(10000)) / 100.0; UserEntry user = new UserEntry(username, Offer.NO_OFFER, time, price); service.addUserEntry(user); med.newUserNotify(service); } } } } catch (InterruptedException e) { e.printStackTrace(); } }
public void run() { int timeLimit = 2500; running = true; try { while (isRunning()) { int sleepTime = 1000 + random.nextInt(timeLimit); Thread.sleep(sleepTime); for (Map.Entry<String, Service> offer: offers.entrySet()) { Service service = offer.getValue(); int event = random.nextInt(1000); System.out.println("event = " + event); if (event < 200) { String username = getRandomString(5 + Math.abs(random.nextInt(16))); Long time = date.getTime() + Math.abs(random.nextInt(10000)); Double price = Math.abs(random.nextInt(10000)) / 100.0; UserEntry user = new UserEntry(username, Offer.NO_OFFER, time, price); service.addUserEntry(user); med.newUserNotify(service); } } } } catch (InterruptedException e) { e.printStackTrace(); } }
diff --git a/com.alkacon.opencms.newsletter/src/com/alkacon/opencms/newsletter/CmsMailinglistSelectionList.java b/com.alkacon.opencms.newsletter/src/com/alkacon/opencms/newsletter/CmsMailinglistSelectionList.java index f33bcf2..59189ca 100644 --- a/com.alkacon.opencms.newsletter/src/com/alkacon/opencms/newsletter/CmsMailinglistSelectionList.java +++ b/com.alkacon.opencms.newsletter/src/com/alkacon/opencms/newsletter/CmsMailinglistSelectionList.java @@ -1,150 +1,150 @@ /* * File : $Source: /alkacon/cvs/alkacon/com.alkacon.opencms.newsletter/src/com/alkacon/opencms/newsletter/CmsMailinglistSelectionList.java,v $ * Date : $Date: 2007/11/30 11:57:27 $ * Version: $Revision: 1.6 $ * * This file is part of the Alkacon OpenCms Add-On Module Package * * Copyright (c) 2007 Alkacon Software GmbH (http://www.alkacon.com) * * The Alkacon OpenCms Add-On Module Package is free software: * you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The Alkacon OpenCms Add-On Module Package is distributed * in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the Alkacon OpenCms Add-On Module Package. * If not, see http://www.gnu.org/licenses/. * * For further information about Alkacon Software GmbH, please see the * company website: http://www.alkacon.com. * * For further information about OpenCms, please see the * project website: http://www.opencms.org. */ package com.alkacon.opencms.newsletter; import org.opencms.jsp.CmsJspActionElement; import org.opencms.main.CmsException; import org.opencms.main.OpenCms; import org.opencms.security.CmsOrganizationalUnit; import org.opencms.workplace.commons.CmsGroupSelectionList; import org.opencms.workplace.list.CmsListColumnDefinition; import org.opencms.workplace.list.CmsListDefaultAction; import org.opencms.workplace.list.CmsListMetadata; import org.opencms.workplace.list.I_CmsListDirectAction; import org.opencms.workplace.tools.CmsToolMacroResolver; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.PageContext; /** * Mailing list selection dialog called from the mailing list widget.<p> * * @author Andreas Zahner * * @version $Revision: 1.6 $ * * @since 7.0.3 */ public class CmsMailinglistSelectionList extends CmsGroupSelectionList { /** * Public constructor.<p> * * @param jsp an initialized JSP action element */ public CmsMailinglistSelectionList(CmsJspActionElement jsp) { super(jsp); getList().setName(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_NAME_0)); } /** * Public constructor with JSP variables.<p> * * @param context the JSP page context * @param req the JSP request * @param res the JSP response */ public CmsMailinglistSelectionList(PageContext context, HttpServletRequest req, HttpServletResponse res) { this(new CmsJspActionElement(context, req, res)); } /** * @see org.opencms.workplace.tools.CmsToolDialog#dialogTitle() */ public String dialogTitle() { // build title StringBuffer html = new StringBuffer(512); html.append("<div class='screenTitle'>\n"); html.append("\t<table width='100%' cellspacing='0'>\n"); html.append("\t\t<tr>\n"); html.append("\t\t\t<td>\n"); html.append(Messages.get().getBundle(getLocale()).key(Messages.GUI_ALK_MAILINGLISTSELECTION_INTRO_TITLE_0)); html.append("\n\t\t\t</td>"); html.append("\t\t</tr>\n"); html.append("\t</table>\n"); html.append("</div>\n"); return CmsToolMacroResolver.resolveMacros(html.toString(), this); } /** * Returns the mailing lists (groups) to show for selection.<p> * * @return A list of mailing lists (group objects) * * @throws CmsException if womething goes wrong */ protected List getGroups() throws CmsException { List ret = new ArrayList(); Iterator i = CmsNewsletterManager.getOrgUnits(getCms()).iterator(); while (i.hasNext()) { CmsOrganizationalUnit ou = (CmsOrganizationalUnit)i.next(); ret.addAll(OpenCms.getOrgUnitManager().getGroups(getCms(), ou.getName(), false)); } return ret; } /** * @see org.opencms.workplace.list.A_CmsListDialog#setColumns(org.opencms.workplace.list.CmsListMetadata) */ protected void setColumns(CmsListMetadata metadata) { super.setColumns(metadata); // create column for icon display CmsListColumnDefinition iconCol = metadata.getColumnDefinition(LIST_COLUMN_ICON); iconCol.setName(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_COLS_ICON_0)); iconCol.setHelpText(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_COLS_ICON_HELP_0)); // set icon action I_CmsListDirectAction iconAction = iconCol.getDirectAction(LIST_ACTION_ICON); iconAction.setName(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_ICON_NAME_0)); iconAction.setHelpText(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_ICON_HELP_0)); iconAction.setIconPath("buttons/mailinglist.png"); // create column for login - CmsListColumnDefinition nameCol = metadata.getColumnDefinition(LIST_COLUMN_NAME); + CmsListColumnDefinition nameCol = metadata.getColumnDefinition(LIST_COLUMN_DISPLAY); nameCol.setName(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_COLS_NAME_0)); CmsListDefaultAction selectAction = nameCol.getDefaultAction(LIST_ACTION_SELECT); selectAction.setName(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_ACTION_SELECT_NAME_0)); selectAction.setHelpText(Messages.get().container( Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_ACTION_SELECT_HELP_0)); } }
true
true
protected void setColumns(CmsListMetadata metadata) { super.setColumns(metadata); // create column for icon display CmsListColumnDefinition iconCol = metadata.getColumnDefinition(LIST_COLUMN_ICON); iconCol.setName(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_COLS_ICON_0)); iconCol.setHelpText(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_COLS_ICON_HELP_0)); // set icon action I_CmsListDirectAction iconAction = iconCol.getDirectAction(LIST_ACTION_ICON); iconAction.setName(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_ICON_NAME_0)); iconAction.setHelpText(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_ICON_HELP_0)); iconAction.setIconPath("buttons/mailinglist.png"); // create column for login CmsListColumnDefinition nameCol = metadata.getColumnDefinition(LIST_COLUMN_NAME); nameCol.setName(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_COLS_NAME_0)); CmsListDefaultAction selectAction = nameCol.getDefaultAction(LIST_ACTION_SELECT); selectAction.setName(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_ACTION_SELECT_NAME_0)); selectAction.setHelpText(Messages.get().container( Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_ACTION_SELECT_HELP_0)); }
protected void setColumns(CmsListMetadata metadata) { super.setColumns(metadata); // create column for icon display CmsListColumnDefinition iconCol = metadata.getColumnDefinition(LIST_COLUMN_ICON); iconCol.setName(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_COLS_ICON_0)); iconCol.setHelpText(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_COLS_ICON_HELP_0)); // set icon action I_CmsListDirectAction iconAction = iconCol.getDirectAction(LIST_ACTION_ICON); iconAction.setName(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_ICON_NAME_0)); iconAction.setHelpText(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_ICON_HELP_0)); iconAction.setIconPath("buttons/mailinglist.png"); // create column for login CmsListColumnDefinition nameCol = metadata.getColumnDefinition(LIST_COLUMN_DISPLAY); nameCol.setName(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_COLS_NAME_0)); CmsListDefaultAction selectAction = nameCol.getDefaultAction(LIST_ACTION_SELECT); selectAction.setName(Messages.get().container(Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_ACTION_SELECT_NAME_0)); selectAction.setHelpText(Messages.get().container( Messages.GUI_ALK_MAILINGLISTSELECTION_LIST_ACTION_SELECT_HELP_0)); }
diff --git a/Library/src/com/tonicartos/widget/stickygridheaders/StickyGridHeadersGridView.java b/Library/src/com/tonicartos/widget/stickygridheaders/StickyGridHeadersGridView.java index bc76da1..26722ef 100644 --- a/Library/src/com/tonicartos/widget/stickygridheaders/StickyGridHeadersGridView.java +++ b/Library/src/com/tonicartos/widget/stickygridheaders/StickyGridHeadersGridView.java @@ -1,356 +1,351 @@ /* Copyright 2013 Tonic Artos 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.tonicartos.widget.stickygridheaders; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.database.DataSetObserver; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.GridView; import android.widget.ListAdapter; import com.tonicartos.widget.stickygridheaders.StickyGridHeadersBaseAdapterWrapper.HeaderFillerView; import com.tonicartos.widget.stickygridheaders.StickyGridHeadersBaseAdapterWrapper.ReferenceView; /** * GridView that displays items in sections with headers that stick to the top * of the view. * * @author Tonic Artos, Emil Sjölander */ public class StickyGridHeadersGridView extends GridView implements OnScrollListener, OnItemClickListener, OnItemSelectedListener, OnItemLongClickListener { private StickyGridHeadersBaseAdapterWrapper mAdapter; private boolean mAreHeadersSticky = true; private final Rect mClippingRect = new Rect(); private boolean mClippingToPadding; private boolean mClipToPaddingHasBeenSet; private long mCurrentHeaderId = -1; private DataSetObserver mDataSetChangedObserver = new DataSetObserver() { @Override public void onChanged() { reset(); } @Override public void onInvalidated() { reset(); } }; private int mHeaderBottomPosition; private int mNumColumns; private OnItemClickListener mOnItemClickListener; private OnItemLongClickListener mOnItemLongClickListener; private OnItemSelectedListener mOnItemSelectedListener; private OnScrollListener mScrollListener; private View mStickiedHeader; public StickyGridHeadersGridView(Context context) { this(context, null); } public StickyGridHeadersGridView(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.gridViewStyle); } public StickyGridHeadersGridView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); super.setOnScrollListener(this); setVerticalFadingEdgeEnabled(false); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mOnItemClickListener.onItemClick(parent, view, mAdapter.translatePosition(position).mPosition, id); } @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { return mOnItemLongClickListener.onItemLongClick(parent, view, mAdapter.translatePosition(position).mPosition, id); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mOnItemSelectedListener.onItemSelected(parent, view, mAdapter.translatePosition(position).mPosition, id); } @Override public void onNothingSelected(AdapterView<?> parent) { mOnItemSelectedListener.onNothingSelected(parent); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (mScrollListener != null) { mScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { scrollChanged(firstVisibleItem); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (mScrollListener != null) { mScrollListener.onScrollStateChanged(view, scrollState); } } @Override public void setAdapter(ListAdapter adapter) { if (!mClipToPaddingHasBeenSet) { mClippingToPadding = true; } if (!(adapter instanceof StickyGridHeadersBaseAdapter || adapter instanceof StickyGridHeadersSimpleAdapter)) { throw new IllegalArgumentException("Adapter must implement either StickyGridHeadersSimpleAdapter or StickyGridHeadersBaseAdapter"); } // NOTE: There may be a problem with getNumColumns(), it could give -1 // which isn't useful. if (adapter instanceof StickyGridHeadersSimpleAdapter) { adapter = new StickyGridHeadersSimpleAdapterWrapper((StickyGridHeadersSimpleAdapter) adapter); } this.mAdapter = new StickyGridHeadersBaseAdapterWrapper(getContext(), this, (StickyGridHeadersBaseAdapter) adapter, mNumColumns); this.mAdapter.registerDataSetObserver(mDataSetChangedObserver); reset(); super.setAdapter(this.mAdapter); } @Override public void setClipToPadding(boolean clipToPadding) { super.setClipToPadding(clipToPadding); mClippingToPadding = clipToPadding; mClipToPaddingHasBeenSet = true; } @Override public void setNumColumns(int numColumns) { super.setNumColumns(numColumns); this.mNumColumns = numColumns; if (mAdapter != null) { mAdapter.setNumColumns(numColumns); } } @Override public void setOnItemClickListener(android.widget.AdapterView.OnItemClickListener listener) { this.mOnItemClickListener = listener; super.setOnItemClickListener(this); } @Override public void setOnItemLongClickListener(android.widget.AdapterView.OnItemLongClickListener listener) { this.mOnItemLongClickListener = listener; super.setOnItemLongClickListener(this); } @Override public void setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener listener) { this.mOnItemSelectedListener = listener; super.setOnItemSelectedListener(this); } private int getHeaderHeight() { if (mStickiedHeader != null) { return mStickiedHeader.getMeasuredHeight(); } return 0; } private void measureHeader() { int widthMeasureSpec = MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY); int heightMeasureSpec = 0; ViewGroup.LayoutParams params = mStickiedHeader.getLayoutParams(); if (params != null && params.height > 0) { heightMeasureSpec = MeasureSpec.makeMeasureSpec(params.height, MeasureSpec.EXACTLY); } else { heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } mStickiedHeader.measure(widthMeasureSpec, heightMeasureSpec); mStickiedHeader.layout(getLeft() + getPaddingLeft(), 0, getRight() - getPaddingRight(), mStickiedHeader.getMeasuredHeight()); } private void reset() { mHeaderBottomPosition = 0; mStickiedHeader = null; } private void scrollChanged(int firstVisibleItem) { if (mAdapter == null || mAdapter.getCount() == 0 || !mAreHeadersSticky) { return; } ReferenceView firstItem = (ReferenceView) getChildAt(0); if (firstItem == null) { return; } long newHeaderId = mAdapter.getHeaderId(firstVisibleItem); if (mCurrentHeaderId != newHeaderId) { mStickiedHeader = mAdapter.getHeaderView(firstVisibleItem, mStickiedHeader, this); measureHeader(); } mCurrentHeaderId = newHeaderId; final int childCount = getChildCount(); if (childCount != 0) { View viewToWatch = null; int watchingChildDistance = 99999; // Find the next header after the stickied one. for (int i = 0; i < childCount; i += mNumColumns) { ReferenceView child = (ReferenceView) super.getChildAt(i); int childDistance; if (mClippingToPadding) { childDistance = child.getTop() - getPaddingTop(); } else { childDistance = child.getTop(); } if (childDistance < 0) { continue; } if (child.getView() instanceof HeaderFillerView && childDistance < watchingChildDistance) { viewToWatch = child; watchingChildDistance = childDistance; } } int headerHeight = getHeaderHeight(); // Work out where to draw stickied header using synchronised // scrolling. if (viewToWatch != null) { if (firstVisibleItem == 0 && super.getChildAt(0).getTop() > 0 && !mClippingToPadding) { mHeaderBottomPosition = 0; } else { if (mClippingToPadding) { mHeaderBottomPosition = Math.min(viewToWatch.getTop(), headerHeight + getPaddingTop()); mHeaderBottomPosition = mHeaderBottomPosition < getPaddingTop() ? headerHeight + getPaddingTop() : mHeaderBottomPosition; } else { mHeaderBottomPosition = Math.min(viewToWatch.getTop(), headerHeight); mHeaderBottomPosition = mHeaderBottomPosition < 0 ? headerHeight : mHeaderBottomPosition; } } } else { mHeaderBottomPosition = headerHeight; if (mClippingToPadding) { mHeaderBottomPosition += getPaddingTop(); } } } } @Override protected void dispatchDraw(Canvas canvas) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { scrollChanged(getFirstVisiblePosition()); } // Mask the region where we will draw the header later... int headerHeight = getHeaderHeight(); int top = mHeaderBottomPosition - headerHeight; mClippingRect.left = getPaddingLeft(); mClippingRect.right = getWidth() - getPaddingRight(); - if (mClippingToPadding) { - mClippingRect.top = getPaddingTop() + mHeaderBottomPosition; - mClippingRect.bottom = getHeight() - getPaddingBottom(); - } else { - mClippingRect.top = mHeaderBottomPosition; - mClippingRect.bottom = getHeight(); - } + mClippingRect.top = mHeaderBottomPosition; + mClippingRect.bottom = getHeight(); canvas.save(); canvas.clipRect(mClippingRect); // ...and draw the grid view. super.dispatchDraw(canvas); // Find headers. List<Integer> headerPositions = new ArrayList<Integer>(); int vi = 0; for (int i = getFirstVisiblePosition(); i <= getLastVisiblePosition();) { long id = getItemIdAtPosition(i); if (id == StickyGridHeadersBaseAdapterWrapper.ID_HEADER) { headerPositions.add(vi); } i += mNumColumns; vi += mNumColumns; } // Draw headers in list. for (int i = 0; i < headerPositions.size(); i++) { View frame = getChildAt(headerPositions.get(i)); View header = (View) frame.getTag(); int widthMeasureSpec = MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY); int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); header.measure(widthMeasureSpec, heightMeasureSpec); header.layout(getLeft() + getPaddingLeft(), 0, getRight() - getPaddingRight(), frame.getHeight()); mClippingRect.left = getPaddingLeft(); mClippingRect.right = getWidth() - getPaddingRight(); mClippingRect.bottom = frame.getBottom(); mClippingRect.top = frame.getTop(); canvas.save(); canvas.clipRect(mClippingRect); canvas.translate(getPaddingLeft(), frame.getTop()); header.draw(canvas); canvas.restore(); } canvas.restore(); if (mStickiedHeader == null || !mAreHeadersSticky) { return; } // Draw stickied header. mClippingRect.left = getPaddingLeft(); mClippingRect.right = getWidth() - getPaddingRight(); mClippingRect.bottom = top + headerHeight; if (mClippingToPadding) { mClippingRect.top = getPaddingTop(); } else { mClippingRect.top = 0; } canvas.save(); canvas.clipRect(mClippingRect); canvas.translate(getPaddingLeft(), top); mStickiedHeader.draw(canvas); canvas.restore(); } }
true
true
protected void dispatchDraw(Canvas canvas) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { scrollChanged(getFirstVisiblePosition()); } // Mask the region where we will draw the header later... int headerHeight = getHeaderHeight(); int top = mHeaderBottomPosition - headerHeight; mClippingRect.left = getPaddingLeft(); mClippingRect.right = getWidth() - getPaddingRight(); if (mClippingToPadding) { mClippingRect.top = getPaddingTop() + mHeaderBottomPosition; mClippingRect.bottom = getHeight() - getPaddingBottom(); } else { mClippingRect.top = mHeaderBottomPosition; mClippingRect.bottom = getHeight(); } canvas.save(); canvas.clipRect(mClippingRect); // ...and draw the grid view. super.dispatchDraw(canvas); // Find headers. List<Integer> headerPositions = new ArrayList<Integer>(); int vi = 0; for (int i = getFirstVisiblePosition(); i <= getLastVisiblePosition();) { long id = getItemIdAtPosition(i); if (id == StickyGridHeadersBaseAdapterWrapper.ID_HEADER) { headerPositions.add(vi); } i += mNumColumns; vi += mNumColumns; } // Draw headers in list. for (int i = 0; i < headerPositions.size(); i++) { View frame = getChildAt(headerPositions.get(i)); View header = (View) frame.getTag(); int widthMeasureSpec = MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY); int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); header.measure(widthMeasureSpec, heightMeasureSpec); header.layout(getLeft() + getPaddingLeft(), 0, getRight() - getPaddingRight(), frame.getHeight()); mClippingRect.left = getPaddingLeft(); mClippingRect.right = getWidth() - getPaddingRight(); mClippingRect.bottom = frame.getBottom(); mClippingRect.top = frame.getTop(); canvas.save(); canvas.clipRect(mClippingRect); canvas.translate(getPaddingLeft(), frame.getTop()); header.draw(canvas); canvas.restore(); } canvas.restore(); if (mStickiedHeader == null || !mAreHeadersSticky) { return; } // Draw stickied header. mClippingRect.left = getPaddingLeft(); mClippingRect.right = getWidth() - getPaddingRight(); mClippingRect.bottom = top + headerHeight; if (mClippingToPadding) { mClippingRect.top = getPaddingTop(); } else { mClippingRect.top = 0; } canvas.save(); canvas.clipRect(mClippingRect); canvas.translate(getPaddingLeft(), top); mStickiedHeader.draw(canvas); canvas.restore(); }
protected void dispatchDraw(Canvas canvas) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { scrollChanged(getFirstVisiblePosition()); } // Mask the region where we will draw the header later... int headerHeight = getHeaderHeight(); int top = mHeaderBottomPosition - headerHeight; mClippingRect.left = getPaddingLeft(); mClippingRect.right = getWidth() - getPaddingRight(); mClippingRect.top = mHeaderBottomPosition; mClippingRect.bottom = getHeight(); canvas.save(); canvas.clipRect(mClippingRect); // ...and draw the grid view. super.dispatchDraw(canvas); // Find headers. List<Integer> headerPositions = new ArrayList<Integer>(); int vi = 0; for (int i = getFirstVisiblePosition(); i <= getLastVisiblePosition();) { long id = getItemIdAtPosition(i); if (id == StickyGridHeadersBaseAdapterWrapper.ID_HEADER) { headerPositions.add(vi); } i += mNumColumns; vi += mNumColumns; } // Draw headers in list. for (int i = 0; i < headerPositions.size(); i++) { View frame = getChildAt(headerPositions.get(i)); View header = (View) frame.getTag(); int widthMeasureSpec = MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY); int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); header.measure(widthMeasureSpec, heightMeasureSpec); header.layout(getLeft() + getPaddingLeft(), 0, getRight() - getPaddingRight(), frame.getHeight()); mClippingRect.left = getPaddingLeft(); mClippingRect.right = getWidth() - getPaddingRight(); mClippingRect.bottom = frame.getBottom(); mClippingRect.top = frame.getTop(); canvas.save(); canvas.clipRect(mClippingRect); canvas.translate(getPaddingLeft(), frame.getTop()); header.draw(canvas); canvas.restore(); } canvas.restore(); if (mStickiedHeader == null || !mAreHeadersSticky) { return; } // Draw stickied header. mClippingRect.left = getPaddingLeft(); mClippingRect.right = getWidth() - getPaddingRight(); mClippingRect.bottom = top + headerHeight; if (mClippingToPadding) { mClippingRect.top = getPaddingTop(); } else { mClippingRect.top = 0; } canvas.save(); canvas.clipRect(mClippingRect); canvas.translate(getPaddingLeft(), top); mStickiedHeader.draw(canvas); canvas.restore(); }
diff --git a/connectors/aleph/20/trunk/jar/src/main/java/org/extensiblecatalog/ncip/v2/aleph/restdlf/handlers/AlephItemHandler.java b/connectors/aleph/20/trunk/jar/src/main/java/org/extensiblecatalog/ncip/v2/aleph/restdlf/handlers/AlephItemHandler.java index a9d2741..01acc0f 100644 --- a/connectors/aleph/20/trunk/jar/src/main/java/org/extensiblecatalog/ncip/v2/aleph/restdlf/handlers/AlephItemHandler.java +++ b/connectors/aleph/20/trunk/jar/src/main/java/org/extensiblecatalog/ncip/v2/aleph/restdlf/handlers/AlephItemHandler.java @@ -1,635 +1,635 @@ package org.extensiblecatalog.ncip.v2.aleph.restdlf.handlers; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.TimeZone; import java.util.spi.TimeZoneNameProvider; import org.extensiblecatalog.ncip.v2.aleph.restdlf.AlephConstants; import org.extensiblecatalog.ncip.v2.aleph.restdlf.AlephException; import org.extensiblecatalog.ncip.v2.aleph.restdlf.item.AlephItem; import org.extensiblecatalog.ncip.v2.aleph.util.AlephUtil; import org.extensiblecatalog.ncip.v2.service.*; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * This class is constructed to parse XML outputs of Aleph RESTful APIs items (regular lookup, patron loans/holdRequests) * * * @author Jiří Kozlovský (MZK) * */ public class AlephItemHandler extends DefaultHandler { private List<AlephItem> listOfItems; private AlephItem currentAlephItem; // Required to build unique item id private String docNumber; private String itemSequence; private boolean itemIdNotFound; // Required to decide whether is set second call number the one we need private String secondCallNoType; // Desired services private boolean bibDescriptionDesired; private boolean circulationStatusDesired; private boolean holdQueueLengthDesired; private boolean itemDesrciptionDesired; // Regular item achievements private boolean circulationStatusReached = false; private boolean holdQueueLengthReached = false; private boolean itemDesrciptionReached = false; private boolean authorReached = false; private boolean isbnReached = false; private boolean titleReached = false; private boolean publisherReached = false; private boolean bibIdReached = false; private boolean docNoReached = false; private boolean locationReached = false; private boolean openDateReached = false; private boolean callNoReached = false; private boolean copyNoReached = false; private boolean materialReached = false; private boolean barcodeReached = false; private boolean itemSequenceReached = false; private boolean agencyReached = false; private boolean collectionReached = false; private boolean secondCallNoTypeReached = false; private boolean secondCallNoReached = false; // Variables for parsing loans & requests private BibliographicDescription bibliographicDescription; private TimeZone localTimeZone; private boolean parsingLoansOrRequests = false; private boolean loansHandling = false; private boolean holdRequestsHandling = false; private boolean hourPlacedReached = false; private boolean earliestDateNeededReached = false; private boolean needBeforeDateReached = false; private boolean datePlacedReached = false; private boolean pickupLocationReached = false; private boolean pickupExpiryDateReached = false; private boolean reminderLevelReached = false; private boolean requestIdReached = false; private boolean requestTypeReached = false; private boolean pickupDateReached = false; private boolean statusReached = false; private boolean dueDateReached = false; private boolean loanDateReached = false; private List<RequestedItem> requestedItems; private RequestedItem currentRequestedItem; private List<LoanedItem> loanedItems; private LoanedItem currentLoanedItem; public AlephItemHandler parseLoansOrRequests() { bibliographicDescription = new BibliographicDescription(); parsingLoansOrRequests = true; return this; } public void setLoansHandlingNow() { loansHandling = true; holdRequestsHandling = false; } public void setRequestsHandlingNow() { loansHandling = false; holdRequestsHandling = true; } /** * @return the listOfItems */ public List<AlephItem> getListOfItems() { return listOfItems; } public AlephItem getAlephItem() { return currentAlephItem; } /** * Constructor sets desired services. * * @param requireAtLeastOneService * - usually parsed from toolkit.properties * @param bibDescriptionDesired * - parsed from initData * @param circulationStatusDesired * - parsed from initData * @param holdQueueLengthDesired * - parsed from initData * @param itemDesrciptionDesired * - parsed from initData * @throws AlephException */ public AlephItemHandler(boolean requireAtLeastOneService, boolean bibDescriptionDesired, boolean circulationStatusDesired, boolean holdQueueLnegthDesired, boolean itemDesrciptionDesired) throws AlephException { if (bibDescriptionDesired || circulationStatusDesired || holdQueueLnegthDesired || itemDesrciptionDesired) { this.bibDescriptionDesired = bibDescriptionDesired; this.circulationStatusDesired = circulationStatusDesired; this.holdQueueLengthDesired = holdQueueLnegthDesired; this.itemDesrciptionDesired = itemDesrciptionDesired; } else if (requireAtLeastOneService) { throw new AlephException("No service desired. Please supply at least one service you wish to use."); } localTimeZone = TimeZone.getTimeZone("ECT"); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (!parsingLoansOrRequests) { if (qName.equalsIgnoreCase(AlephConstants.ITEM_NODE)) { secondCallNoType = null; currentAlephItem = new AlephItem(); currentAlephItem.setLink(attributes.getValue(AlephConstants.HREF_NODE_ATTR)); if (listOfItems == null) listOfItems = new ArrayList<AlephItem>(); } else if (qName.equalsIgnoreCase(AlephConstants.STATUS_NODE) && circulationStatusDesired) { circulationStatusReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_HOLD_DOC_NUMBER_NODE) && holdQueueLengthDesired) { holdQueueLengthReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_DESCRIPTION_NODE) && itemDesrciptionDesired) { itemDesrciptionReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_DOC_NUMBER_NODE)) { docNoReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_ITEM_SEQUENCE_NODE)) { itemSequenceReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_SUB_LIBRARY_NODE)) { locationReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_OPEN_DATE_NODE)) { openDateReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_CALL_NUMBER_NODE)) { callNoReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_CALL_NUMBER_2_TYPE_NODE)) { secondCallNoTypeReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_CALL_NUMBER_2_NODE)) { secondCallNoReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_COPY_ID_NODE)) { copyNoReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_BARCODE)) { barcodeReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_MATERIAL_NODE)) { materialReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.TRANSLATE_CHANGE_ACTIVE_LIBRARY_NODE)) { agencyReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_COLLECTION_NODE)) { collectionReached = true; } else if (bibDescriptionDesired) { if (qName.equalsIgnoreCase(AlephConstants.Z13_AUTHOR_NODE)) { authorReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_ISBN_NODE)) { isbnReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_TITLE_NODE)) { titleReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_PUBLISHER_NODE)) { publisherReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_BIB_ID_NODE)) { bibIdReached = true; } } } else { if (qName.equalsIgnoreCase(AlephConstants.Z13_AUTHOR_NODE)) { authorReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_ISBN_NODE)) { isbnReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_TITLE_NODE)) { titleReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_PUBLISHER_NODE)) { publisherReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_BIB_ID_NODE)) { bibIdReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_MATERIAL_NODE)) { materialReached = true; } else if (loansHandling) { // Handling loans XML output if (qName.equalsIgnoreCase(AlephConstants.LOAN_ITEM_NODE)) { currentLoanedItem = new LoanedItem(); if (loanedItems == null) loanedItems = new ArrayList<LoanedItem>(); } else if (qName.equalsIgnoreCase(AlephConstants.Z36_DUE_DATE_NODE)) { dueDateReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z36_LOAN_DATE_NODE)) { loanDateReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z36_ITEM_SEQUENCE_NODE)) { itemSequenceReached = true; } } else if (holdRequestsHandling) { // Handling requests XML output if (qName.equalsIgnoreCase(AlephConstants.HOLD_REQUEST_NODE)) { currentRequestedItem = new RequestedItem(); if (requestedItems == null) requestedItems = new ArrayList<RequestedItem>(); } else if (qName.equalsIgnoreCase(AlephConstants.Z37_OPEN_DATE_NODE)) { datePlacedReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_OPEN_HOUR_NODE)) { hourPlacedReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_REQUEST_DATE_NODE)) { earliestDateNeededReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_END_REQUEST_DATE_NODE)) { needBeforeDateReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_ITEM_SEQUENCE_NODE)) { itemSequenceReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_HOLD_SEQUENCE_NODE)) { holdQueueLengthReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_PICKUP_LOCATION_NODE)) { pickupLocationReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_END_HOLD_DATE_NODE)) { pickupExpiryDateReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_RECALL_TYPE_NODE)) { reminderLevelReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_REQUEST_NUMBER_NODE)) { requestIdReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_PRIORITY_NODE)) { requestTypeReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_HOLD_DATE_NODE)) { pickupDateReached = true; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_STATUS_NODE)) { statusReached = true; } } } } // END OF PARSING START ELEMENT @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (!parsingLoansOrRequests) { if (qName.equalsIgnoreCase(AlephConstants.ITEM_NODE)) { listOfItems.add(currentAlephItem); } else if (qName.equalsIgnoreCase(AlephConstants.STATUS_NODE) && circulationStatusReached) { // currentAlephItem.setCirculationStatus(AlephConstants.ERROR_CIRCULATION_STATUS_NOT_FOUND); circulationStatusReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_HOLD_DOC_NUMBER_NODE) && holdQueueLengthReached) { currentAlephItem.setHoldQueueLength(-1); // currentAlephItem.setholdQueue(AlephConstants.ERROR_HOLD_QUEUE_NOT_FOUND); holdQueueLengthReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_DESCRIPTION_NODE) && itemDesrciptionReached) { // currentAlephItem.setDescription(AlephConstants.ERROR_ITEM_DESCRIPTION_NOT_FOUND); itemDesrciptionReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_DOC_NUMBER_NODE) && docNoReached) { // currentAlephItem.setBibId(AlephConstants.ERROR_BIBLIOGRAPHIC_ID_NOT_FOUND); // currentAlephItem.setDocNumber(AlephConstants.ERROR_DOCUMENT_NUMBER_NOT_FOUND); docNoReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_ITEM_SEQUENCE_NODE) && itemSequenceReached) { // currentAlephItem.setSeqNumber(AlephConstants.ERROR_SEQUENCE_NUMBER_NOT_FOUND); itemSequenceReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_SUB_LIBRARY_NODE) && locationReached) { // currentAlephItem.setLocation(AlephConstants.ERROR_LOCATION_NOT_FOUND); locationReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_OPEN_DATE_NODE) && openDateReached) { // currentAlephItem.setPublicationDate(AlephConstants.ERROR_OPENDATE_NOT_FOUND); openDateReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_CALL_NUMBER_NODE) && callNoReached) { // currentAlephItem.setCallNumber(AlephConstants.ERROR_CALL_NO_NOT_FOUND); callNoReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_CALL_NUMBER_2_TYPE_NODE) && secondCallNoTypeReached) { secondCallNoTypeReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_CALL_NUMBER_2_NODE) && secondCallNoReached) { secondCallNoReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_COPY_ID_NODE) && copyNoReached) { // currentAlephItem.setCopyNumber(AlephConstants.ERROR_COPY_NO_NOT_FOUND); copyNoReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_BARCODE) && barcodeReached) { // currentAlephItem.setBarcode(AlephConstants.ERROR_BARCODE_NOT_FOUND); barcodeReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_MATERIAL_NODE) && materialReached) { // currentAlephItem.setMediumType(AlephConstants.ERROR_MATERIAL_NOT_FOUND); materialReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.TRANSLATE_CHANGE_ACTIVE_LIBRARY_NODE) && agencyReached) { // currentAlephItem.setAgency(AlephConstants.ERROR_AGENCY_NOT_FOUND); agencyReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_COLLECTION_NODE) && collectionReached) { // currentAlephItem.setCollection(AlephConstants.ERROR_COLLECTION_NOT_FOUND); collectionReached = false; } else if (bibDescriptionDesired) { if (qName.equalsIgnoreCase(AlephConstants.Z13_AUTHOR_NODE) && authorReached) { // currentAlephItem.setAuthor(AlephConstants.ERROR_AUTHOR_NOT_FOUND); authorReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_ISBN_NODE) && isbnReached) { // currentAlephItem.setIsbn(AlephConstants.ERROR_ISBN_NOT_FOUND); isbnReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_TITLE_NODE) && titleReached) { // currentAlephItem.setTitle(AlephConstants.ERROR_TITLE_NOT_FOUND); titleReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_PUBLISHER_NODE) && publisherReached) { // currentAlephItem.setPublisher(AlephConstants.ERROR_PUBLISHER_NOT_FOUND); publisherReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_BIB_ID_NODE) && bibIdReached) { // currentAlephItem.setBibId(AlephConstants.ERROR_BIBLIOGRAPHIC_ID_NOT_FOUND); bibIdReached = false; } } } else { if (qName.equalsIgnoreCase(AlephConstants.Z13_AUTHOR_NODE) && authorReached) { authorReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_ISBN_NODE) && isbnReached) { isbnReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_TITLE_NODE) && titleReached) { titleReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_PUBLISHER_NODE) && publisherReached) { publisherReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z13_BIB_ID_NODE) && bibIdReached) { itemIdNotFound = true; bibIdReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z30_MATERIAL_NODE) && materialReached) { materialReached = false; } else if (loansHandling) { if (qName.equalsIgnoreCase(AlephConstants.LOAN_ITEM_NODE)) { if (!itemIdNotFound) { ItemId itemId = new ItemId(); itemId.setItemIdentifierValue(docNumber.trim() + "-" + itemSequence.trim()); itemId.setItemIdentifierType(Version1ItemIdentifierType.ACCESSION_NUMBER); currentLoanedItem.setItemId(itemId); } currentLoanedItem.setBibliographicDescription(bibliographicDescription); loanedItems.add(currentLoanedItem); bibliographicDescription = new BibliographicDescription(); } else if (qName.equalsIgnoreCase(AlephConstants.Z36_DUE_DATE_NODE) && dueDateReached) { dueDateReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z36_LOAN_DATE_NODE) && loanDateReached) { loanDateReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z36_ITEM_SEQUENCE_NODE) && itemSequenceReached) { itemIdNotFound = true; itemSequenceReached = false; } } else if (holdRequestsHandling) { if (qName.equalsIgnoreCase(AlephConstants.HOLD_REQUEST_NODE)) { if (!itemIdNotFound) { ItemId itemId = new ItemId(); itemId.setItemIdentifierValue(docNumber.trim() + "-" + itemSequence.trim()); itemId.setItemIdentifierType(Version1ItemIdentifierType.ACCESSION_NUMBER); currentRequestedItem.setItemId(itemId); } currentRequestedItem.setBibliographicDescription(bibliographicDescription); requestedItems.add(currentRequestedItem); bibliographicDescription = new BibliographicDescription(); } else if (qName.equalsIgnoreCase(AlephConstants.Z37_OPEN_DATE_NODE) && datePlacedReached) { datePlacedReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_OPEN_HOUR_NODE) && hourPlacedReached) { hourPlacedReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_REQUEST_DATE_NODE) && earliestDateNeededReached) { earliestDateNeededReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_END_REQUEST_DATE_NODE) && needBeforeDateReached) { needBeforeDateReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_ITEM_SEQUENCE_NODE) && itemSequenceReached) { itemSequenceReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_HOLD_SEQUENCE_NODE) && holdQueueLengthReached) { holdQueueLengthReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_PICKUP_LOCATION_NODE) && pickupLocationReached) { pickupLocationReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_END_HOLD_DATE_NODE) && pickupExpiryDateReached) { pickupExpiryDateReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_RECALL_TYPE_NODE) && reminderLevelReached) { reminderLevelReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_REQUEST_NUMBER_NODE) && requestIdReached) { requestIdReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_PRIORITY_NODE) && requestTypeReached) { requestTypeReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_HOLD_DATE_NODE) && pickupDateReached) { pickupDateReached = false; } else if (qName.equalsIgnoreCase(AlephConstants.Z37_STATUS_NODE) && statusReached) { statusReached = false; } } } } // END OF PARSING END ELEMENT @Override public void characters(char ch[], int start, int length) throws SAXException { if (!parsingLoansOrRequests) { if (circulationStatusReached) { currentAlephItem.setCirculationStatus(new String(ch, start, length)); circulationStatusReached = false; } else if (holdQueueLengthReached) { currentAlephItem.setHoldQueueLength(Integer.parseInt(new String(ch, start, length))); holdQueueLengthReached = false; } else if (itemDesrciptionReached) { currentAlephItem.setDescription(new String(ch, start, length)); itemDesrciptionReached = false; } else if (docNoReached) { currentAlephItem.setDocNumber(new String(ch, start, length)); docNoReached = false; } else if (itemSequenceReached) { currentAlephItem.setItemSeqNumber(new String(ch, start, length)); itemSequenceReached = false; } else if (locationReached) { currentAlephItem.setLocation(new String(ch, start, length)); locationReached = false; } else if (openDateReached) { currentAlephItem.setPublicationDate(new String(ch, start, length)); openDateReached = false; } else if (callNoReached) { currentAlephItem.setCallNumber(new String(ch, start, length)); callNoReached = false; } else if (secondCallNoTypeReached) { secondCallNoType = new String(ch, start, length); secondCallNoTypeReached = false; } else if (secondCallNoReached) { if (secondCallNoType != null && !secondCallNoType.equalsIgnoreCase("9")) currentAlephItem.setCallNumber(new String(ch, start, length)); else if (secondCallNoType == null) currentAlephItem.setCallNumber(new String(ch, start, length)); secondCallNoReached = false; } else if (copyNoReached) { currentAlephItem.setCopyNumber(new String(ch, start, length)); copyNoReached = false; } else if (barcodeReached) { currentAlephItem.setBarcode(new String(ch, start, length)); barcodeReached = false; } else if (materialReached) { currentAlephItem.setMediumType(new String(ch, start, length)); materialReached = false; } else if (agencyReached) { currentAlephItem.setAgency(new String(ch, start, length)); agencyReached = false; } else if (collectionReached) { currentAlephItem.setCollection(new String(ch, start, length)); collectionReached = false; } else if (bibDescriptionDesired) { if (authorReached) { currentAlephItem.setAuthor(new String(ch, start, length)); authorReached = false; } else if (isbnReached) { currentAlephItem.setIsbn(new String(ch, start, length)); isbnReached = false; } else if (titleReached) { currentAlephItem.setTitle(new String(ch, start, length)); titleReached = false; } else if (publisherReached) { currentAlephItem.setPublisher(new String(ch, start, length)); publisherReached = false; } else if (bibIdReached) { currentAlephItem.setBibId(new String(ch, start, length)); bibIdReached = false; } } } else { if (materialReached) { String mediumTypeParsed = new String(ch, start, length); MediumType mediumType = AlephUtil.detectMediumType(mediumTypeParsed); bibliographicDescription.setMediumType(mediumType); materialReached = false; } else if (authorReached) { bibliographicDescription.setAuthor(new String(ch, start, length)); authorReached = false; } else if (isbnReached) { bibliographicDescription.setBibliographicLevel(null); isbnReached = false; } else if (titleReached) { bibliographicDescription.setTitle(new String(ch, start, length)); titleReached = false; } else if (publisherReached) { bibliographicDescription.setPublisher(new String(ch, start, length)); publisherReached = false; } else if (bibIdReached) { String parsedBibId = new String(ch, start, length); docNumber = parsedBibId; List<BibliographicItemId> bibliographicItemIds = new ArrayList<BibliographicItemId>(); BibliographicItemId bibId = new BibliographicItemId(); bibId.setBibliographicItemIdentifier(parsedBibId); bibId.setBibliographicItemIdentifierCode(Version1BibliographicItemIdentifierCode.URI); bibliographicItemIds.add(bibId); bibliographicDescription.setBibliographicItemIds(bibliographicItemIds); bibIdReached = false; } else if (itemSequenceReached) { itemSequence = new String(ch, start, length); itemSequenceReached = false; } else if (loansHandling) { if (dueDateReached) { String dateDueParsed = new String(ch, start, length); GregorianCalendar dateDue = AlephUtil.parseGregorianCalendarFromAlephDate(dateDueParsed); currentLoanedItem.setDateDue(dateDue); dueDateReached = false; } else if (loanDateReached) { String loanDateParsed = new String(ch, start, length); GregorianCalendar loanDate = AlephUtil.parseGregorianCalendarFromAlephDate(loanDateParsed); currentLoanedItem.setDateCheckedOut(loanDate); loanDateReached = false; } } else if (holdRequestsHandling) { if (datePlacedReached) { String datePlacedParsed = new String(ch, start, length); GregorianCalendar datePlaced = AlephUtil.parseGregorianCalendarFromAlephDate(datePlacedParsed); - currentLoanedItem.setDateCheckedOut(datePlaced); + currentRequestedItem.setDatePlaced(datePlaced); datePlacedReached = false; } else if (hourPlacedReached) { String hourPlacedParsed = new String(ch, start, length); if (!hourPlacedParsed.equalsIgnoreCase("00000000")) { GregorianCalendar datePlaced = currentRequestedItem.getDatePlaced(); GregorianCalendar hourPlaced = new GregorianCalendar(localTimeZone); try { hourPlaced.setTime(AlephConstants.ALEPH_HOUR_FORMATTER.parse(hourPlacedParsed)); } catch (ParseException e) { e.printStackTrace(); } datePlaced.add(Calendar.HOUR_OF_DAY, hourPlaced.get(Calendar.HOUR_OF_DAY) - 1); datePlaced.add(Calendar.MINUTE, hourPlaced.get(Calendar.MINUTE)); currentRequestedItem.setDatePlaced(datePlaced); } hourPlacedReached = false; } else if (earliestDateNeededReached) { String earliestDateNeededParsed = new String(ch, start, length); GregorianCalendar earliestDateNeeded = AlephUtil.parseGregorianCalendarFromAlephDate(earliestDateNeededParsed); - currentLoanedItem.setDateCheckedOut(earliestDateNeeded); + currentRequestedItem.setEarliestDateNeeded(earliestDateNeeded); earliestDateNeededReached = false; } else if (needBeforeDateReached) { String needBeforeDateParsed = new String(ch, start, length); GregorianCalendar needBeforeDate = AlephUtil.parseGregorianCalendarFromAlephDate(needBeforeDateParsed); - currentLoanedItem.setDateCheckedOut(needBeforeDate); + currentRequestedItem.setNeedBeforeDate(needBeforeDate); needBeforeDateReached = false; } else if (holdQueueLengthReached) { currentRequestedItem.setHoldQueueLength(new BigDecimal(new String(ch, start, length))); holdQueueLengthReached = false; } else if (pickupLocationReached) { PickupLocation pickupLocation = new PickupLocation(new String(ch, start, length)); currentRequestedItem.setPickupLocation(pickupLocation); pickupLocationReached = false; } else if (pickupExpiryDateReached) { String pickupExpiryDateParsed = new String(ch, start, length); GregorianCalendar pickupExpiryDate = AlephUtil.parseGregorianCalendarFromAlephDate(pickupExpiryDateParsed); - currentLoanedItem.setDateCheckedOut(pickupExpiryDate); + currentRequestedItem.setPickupExpiryDate(pickupExpiryDate); pickupExpiryDateReached = false; } else if (reminderLevelReached) { currentRequestedItem.setReminderLevel(new BigDecimal(new String(ch, start, length))); reminderLevelReached = false; } else if (requestIdReached) { RequestId requestId = new RequestId(); requestId.setRequestIdentifierValue(new String(ch, start, length)); currentRequestedItem.setRequestId(requestId); requestIdReached = false; } else if (requestTypeReached) { RequestType requestType = null; String parsedValue = new String(ch, start, length); if (parsedValue == "30") // TODO: Add remaining request types requestType = Version1RequestType.LOAN; else requestType = Version1RequestType.ESTIMATE; // FIXME: Put here better default value currentRequestedItem.setRequestType(requestType); requestTypeReached = false; } else if (pickupDateReached) { String pickupDateParsed = new String(ch, start, length); GregorianCalendar pickupDate = AlephUtil.parseGregorianCalendarFromAlephDate(pickupDateParsed); - currentLoanedItem.setDateCheckedOut(pickupDate); + currentRequestedItem.setPickupDate(pickupDate); pickupDateReached = false; } else if (statusReached) { String parsedStatus = new String(ch, start, length); RequestStatusType requestStatusType; if (parsedStatus == "S") requestStatusType = Version1RequestStatusType.AVAILABLE_FOR_PICKUP; else requestStatusType = Version1RequestStatusType.IN_PROCESS; currentRequestedItem.setRequestStatusType(requestStatusType); statusReached = false; } } } } // END OF PARSING CHARACTERS INSIDE ELEMENTS public List<RequestedItem> getListOfRequestedItems() { return requestedItems; } public List<LoanedItem> getListOfLoanedItems() { return loanedItems; } }
false
true
public void characters(char ch[], int start, int length) throws SAXException { if (!parsingLoansOrRequests) { if (circulationStatusReached) { currentAlephItem.setCirculationStatus(new String(ch, start, length)); circulationStatusReached = false; } else if (holdQueueLengthReached) { currentAlephItem.setHoldQueueLength(Integer.parseInt(new String(ch, start, length))); holdQueueLengthReached = false; } else if (itemDesrciptionReached) { currentAlephItem.setDescription(new String(ch, start, length)); itemDesrciptionReached = false; } else if (docNoReached) { currentAlephItem.setDocNumber(new String(ch, start, length)); docNoReached = false; } else if (itemSequenceReached) { currentAlephItem.setItemSeqNumber(new String(ch, start, length)); itemSequenceReached = false; } else if (locationReached) { currentAlephItem.setLocation(new String(ch, start, length)); locationReached = false; } else if (openDateReached) { currentAlephItem.setPublicationDate(new String(ch, start, length)); openDateReached = false; } else if (callNoReached) { currentAlephItem.setCallNumber(new String(ch, start, length)); callNoReached = false; } else if (secondCallNoTypeReached) { secondCallNoType = new String(ch, start, length); secondCallNoTypeReached = false; } else if (secondCallNoReached) { if (secondCallNoType != null && !secondCallNoType.equalsIgnoreCase("9")) currentAlephItem.setCallNumber(new String(ch, start, length)); else if (secondCallNoType == null) currentAlephItem.setCallNumber(new String(ch, start, length)); secondCallNoReached = false; } else if (copyNoReached) { currentAlephItem.setCopyNumber(new String(ch, start, length)); copyNoReached = false; } else if (barcodeReached) { currentAlephItem.setBarcode(new String(ch, start, length)); barcodeReached = false; } else if (materialReached) { currentAlephItem.setMediumType(new String(ch, start, length)); materialReached = false; } else if (agencyReached) { currentAlephItem.setAgency(new String(ch, start, length)); agencyReached = false; } else if (collectionReached) { currentAlephItem.setCollection(new String(ch, start, length)); collectionReached = false; } else if (bibDescriptionDesired) { if (authorReached) { currentAlephItem.setAuthor(new String(ch, start, length)); authorReached = false; } else if (isbnReached) { currentAlephItem.setIsbn(new String(ch, start, length)); isbnReached = false; } else if (titleReached) { currentAlephItem.setTitle(new String(ch, start, length)); titleReached = false; } else if (publisherReached) { currentAlephItem.setPublisher(new String(ch, start, length)); publisherReached = false; } else if (bibIdReached) { currentAlephItem.setBibId(new String(ch, start, length)); bibIdReached = false; } } } else { if (materialReached) { String mediumTypeParsed = new String(ch, start, length); MediumType mediumType = AlephUtil.detectMediumType(mediumTypeParsed); bibliographicDescription.setMediumType(mediumType); materialReached = false; } else if (authorReached) { bibliographicDescription.setAuthor(new String(ch, start, length)); authorReached = false; } else if (isbnReached) { bibliographicDescription.setBibliographicLevel(null); isbnReached = false; } else if (titleReached) { bibliographicDescription.setTitle(new String(ch, start, length)); titleReached = false; } else if (publisherReached) { bibliographicDescription.setPublisher(new String(ch, start, length)); publisherReached = false; } else if (bibIdReached) { String parsedBibId = new String(ch, start, length); docNumber = parsedBibId; List<BibliographicItemId> bibliographicItemIds = new ArrayList<BibliographicItemId>(); BibliographicItemId bibId = new BibliographicItemId(); bibId.setBibliographicItemIdentifier(parsedBibId); bibId.setBibliographicItemIdentifierCode(Version1BibliographicItemIdentifierCode.URI); bibliographicItemIds.add(bibId); bibliographicDescription.setBibliographicItemIds(bibliographicItemIds); bibIdReached = false; } else if (itemSequenceReached) { itemSequence = new String(ch, start, length); itemSequenceReached = false; } else if (loansHandling) { if (dueDateReached) { String dateDueParsed = new String(ch, start, length); GregorianCalendar dateDue = AlephUtil.parseGregorianCalendarFromAlephDate(dateDueParsed); currentLoanedItem.setDateDue(dateDue); dueDateReached = false; } else if (loanDateReached) { String loanDateParsed = new String(ch, start, length); GregorianCalendar loanDate = AlephUtil.parseGregorianCalendarFromAlephDate(loanDateParsed); currentLoanedItem.setDateCheckedOut(loanDate); loanDateReached = false; } } else if (holdRequestsHandling) { if (datePlacedReached) { String datePlacedParsed = new String(ch, start, length); GregorianCalendar datePlaced = AlephUtil.parseGregorianCalendarFromAlephDate(datePlacedParsed); currentLoanedItem.setDateCheckedOut(datePlaced); datePlacedReached = false; } else if (hourPlacedReached) { String hourPlacedParsed = new String(ch, start, length); if (!hourPlacedParsed.equalsIgnoreCase("00000000")) { GregorianCalendar datePlaced = currentRequestedItem.getDatePlaced(); GregorianCalendar hourPlaced = new GregorianCalendar(localTimeZone); try { hourPlaced.setTime(AlephConstants.ALEPH_HOUR_FORMATTER.parse(hourPlacedParsed)); } catch (ParseException e) { e.printStackTrace(); } datePlaced.add(Calendar.HOUR_OF_DAY, hourPlaced.get(Calendar.HOUR_OF_DAY) - 1); datePlaced.add(Calendar.MINUTE, hourPlaced.get(Calendar.MINUTE)); currentRequestedItem.setDatePlaced(datePlaced); } hourPlacedReached = false; } else if (earliestDateNeededReached) { String earliestDateNeededParsed = new String(ch, start, length); GregorianCalendar earliestDateNeeded = AlephUtil.parseGregorianCalendarFromAlephDate(earliestDateNeededParsed); currentLoanedItem.setDateCheckedOut(earliestDateNeeded); earliestDateNeededReached = false; } else if (needBeforeDateReached) { String needBeforeDateParsed = new String(ch, start, length); GregorianCalendar needBeforeDate = AlephUtil.parseGregorianCalendarFromAlephDate(needBeforeDateParsed); currentLoanedItem.setDateCheckedOut(needBeforeDate); needBeforeDateReached = false; } else if (holdQueueLengthReached) { currentRequestedItem.setHoldQueueLength(new BigDecimal(new String(ch, start, length))); holdQueueLengthReached = false; } else if (pickupLocationReached) { PickupLocation pickupLocation = new PickupLocation(new String(ch, start, length)); currentRequestedItem.setPickupLocation(pickupLocation); pickupLocationReached = false; } else if (pickupExpiryDateReached) { String pickupExpiryDateParsed = new String(ch, start, length); GregorianCalendar pickupExpiryDate = AlephUtil.parseGregorianCalendarFromAlephDate(pickupExpiryDateParsed); currentLoanedItem.setDateCheckedOut(pickupExpiryDate); pickupExpiryDateReached = false; } else if (reminderLevelReached) { currentRequestedItem.setReminderLevel(new BigDecimal(new String(ch, start, length))); reminderLevelReached = false; } else if (requestIdReached) { RequestId requestId = new RequestId(); requestId.setRequestIdentifierValue(new String(ch, start, length)); currentRequestedItem.setRequestId(requestId); requestIdReached = false; } else if (requestTypeReached) { RequestType requestType = null; String parsedValue = new String(ch, start, length); if (parsedValue == "30") // TODO: Add remaining request types requestType = Version1RequestType.LOAN; else requestType = Version1RequestType.ESTIMATE; // FIXME: Put here better default value currentRequestedItem.setRequestType(requestType); requestTypeReached = false; } else if (pickupDateReached) { String pickupDateParsed = new String(ch, start, length); GregorianCalendar pickupDate = AlephUtil.parseGregorianCalendarFromAlephDate(pickupDateParsed); currentLoanedItem.setDateCheckedOut(pickupDate); pickupDateReached = false; } else if (statusReached) { String parsedStatus = new String(ch, start, length); RequestStatusType requestStatusType; if (parsedStatus == "S") requestStatusType = Version1RequestStatusType.AVAILABLE_FOR_PICKUP; else requestStatusType = Version1RequestStatusType.IN_PROCESS; currentRequestedItem.setRequestStatusType(requestStatusType); statusReached = false; } } } }
public void characters(char ch[], int start, int length) throws SAXException { if (!parsingLoansOrRequests) { if (circulationStatusReached) { currentAlephItem.setCirculationStatus(new String(ch, start, length)); circulationStatusReached = false; } else if (holdQueueLengthReached) { currentAlephItem.setHoldQueueLength(Integer.parseInt(new String(ch, start, length))); holdQueueLengthReached = false; } else if (itemDesrciptionReached) { currentAlephItem.setDescription(new String(ch, start, length)); itemDesrciptionReached = false; } else if (docNoReached) { currentAlephItem.setDocNumber(new String(ch, start, length)); docNoReached = false; } else if (itemSequenceReached) { currentAlephItem.setItemSeqNumber(new String(ch, start, length)); itemSequenceReached = false; } else if (locationReached) { currentAlephItem.setLocation(new String(ch, start, length)); locationReached = false; } else if (openDateReached) { currentAlephItem.setPublicationDate(new String(ch, start, length)); openDateReached = false; } else if (callNoReached) { currentAlephItem.setCallNumber(new String(ch, start, length)); callNoReached = false; } else if (secondCallNoTypeReached) { secondCallNoType = new String(ch, start, length); secondCallNoTypeReached = false; } else if (secondCallNoReached) { if (secondCallNoType != null && !secondCallNoType.equalsIgnoreCase("9")) currentAlephItem.setCallNumber(new String(ch, start, length)); else if (secondCallNoType == null) currentAlephItem.setCallNumber(new String(ch, start, length)); secondCallNoReached = false; } else if (copyNoReached) { currentAlephItem.setCopyNumber(new String(ch, start, length)); copyNoReached = false; } else if (barcodeReached) { currentAlephItem.setBarcode(new String(ch, start, length)); barcodeReached = false; } else if (materialReached) { currentAlephItem.setMediumType(new String(ch, start, length)); materialReached = false; } else if (agencyReached) { currentAlephItem.setAgency(new String(ch, start, length)); agencyReached = false; } else if (collectionReached) { currentAlephItem.setCollection(new String(ch, start, length)); collectionReached = false; } else if (bibDescriptionDesired) { if (authorReached) { currentAlephItem.setAuthor(new String(ch, start, length)); authorReached = false; } else if (isbnReached) { currentAlephItem.setIsbn(new String(ch, start, length)); isbnReached = false; } else if (titleReached) { currentAlephItem.setTitle(new String(ch, start, length)); titleReached = false; } else if (publisherReached) { currentAlephItem.setPublisher(new String(ch, start, length)); publisherReached = false; } else if (bibIdReached) { currentAlephItem.setBibId(new String(ch, start, length)); bibIdReached = false; } } } else { if (materialReached) { String mediumTypeParsed = new String(ch, start, length); MediumType mediumType = AlephUtil.detectMediumType(mediumTypeParsed); bibliographicDescription.setMediumType(mediumType); materialReached = false; } else if (authorReached) { bibliographicDescription.setAuthor(new String(ch, start, length)); authorReached = false; } else if (isbnReached) { bibliographicDescription.setBibliographicLevel(null); isbnReached = false; } else if (titleReached) { bibliographicDescription.setTitle(new String(ch, start, length)); titleReached = false; } else if (publisherReached) { bibliographicDescription.setPublisher(new String(ch, start, length)); publisherReached = false; } else if (bibIdReached) { String parsedBibId = new String(ch, start, length); docNumber = parsedBibId; List<BibliographicItemId> bibliographicItemIds = new ArrayList<BibliographicItemId>(); BibliographicItemId bibId = new BibliographicItemId(); bibId.setBibliographicItemIdentifier(parsedBibId); bibId.setBibliographicItemIdentifierCode(Version1BibliographicItemIdentifierCode.URI); bibliographicItemIds.add(bibId); bibliographicDescription.setBibliographicItemIds(bibliographicItemIds); bibIdReached = false; } else if (itemSequenceReached) { itemSequence = new String(ch, start, length); itemSequenceReached = false; } else if (loansHandling) { if (dueDateReached) { String dateDueParsed = new String(ch, start, length); GregorianCalendar dateDue = AlephUtil.parseGregorianCalendarFromAlephDate(dateDueParsed); currentLoanedItem.setDateDue(dateDue); dueDateReached = false; } else if (loanDateReached) { String loanDateParsed = new String(ch, start, length); GregorianCalendar loanDate = AlephUtil.parseGregorianCalendarFromAlephDate(loanDateParsed); currentLoanedItem.setDateCheckedOut(loanDate); loanDateReached = false; } } else if (holdRequestsHandling) { if (datePlacedReached) { String datePlacedParsed = new String(ch, start, length); GregorianCalendar datePlaced = AlephUtil.parseGregorianCalendarFromAlephDate(datePlacedParsed); currentRequestedItem.setDatePlaced(datePlaced); datePlacedReached = false; } else if (hourPlacedReached) { String hourPlacedParsed = new String(ch, start, length); if (!hourPlacedParsed.equalsIgnoreCase("00000000")) { GregorianCalendar datePlaced = currentRequestedItem.getDatePlaced(); GregorianCalendar hourPlaced = new GregorianCalendar(localTimeZone); try { hourPlaced.setTime(AlephConstants.ALEPH_HOUR_FORMATTER.parse(hourPlacedParsed)); } catch (ParseException e) { e.printStackTrace(); } datePlaced.add(Calendar.HOUR_OF_DAY, hourPlaced.get(Calendar.HOUR_OF_DAY) - 1); datePlaced.add(Calendar.MINUTE, hourPlaced.get(Calendar.MINUTE)); currentRequestedItem.setDatePlaced(datePlaced); } hourPlacedReached = false; } else if (earliestDateNeededReached) { String earliestDateNeededParsed = new String(ch, start, length); GregorianCalendar earliestDateNeeded = AlephUtil.parseGregorianCalendarFromAlephDate(earliestDateNeededParsed); currentRequestedItem.setEarliestDateNeeded(earliestDateNeeded); earliestDateNeededReached = false; } else if (needBeforeDateReached) { String needBeforeDateParsed = new String(ch, start, length); GregorianCalendar needBeforeDate = AlephUtil.parseGregorianCalendarFromAlephDate(needBeforeDateParsed); currentRequestedItem.setNeedBeforeDate(needBeforeDate); needBeforeDateReached = false; } else if (holdQueueLengthReached) { currentRequestedItem.setHoldQueueLength(new BigDecimal(new String(ch, start, length))); holdQueueLengthReached = false; } else if (pickupLocationReached) { PickupLocation pickupLocation = new PickupLocation(new String(ch, start, length)); currentRequestedItem.setPickupLocation(pickupLocation); pickupLocationReached = false; } else if (pickupExpiryDateReached) { String pickupExpiryDateParsed = new String(ch, start, length); GregorianCalendar pickupExpiryDate = AlephUtil.parseGregorianCalendarFromAlephDate(pickupExpiryDateParsed); currentRequestedItem.setPickupExpiryDate(pickupExpiryDate); pickupExpiryDateReached = false; } else if (reminderLevelReached) { currentRequestedItem.setReminderLevel(new BigDecimal(new String(ch, start, length))); reminderLevelReached = false; } else if (requestIdReached) { RequestId requestId = new RequestId(); requestId.setRequestIdentifierValue(new String(ch, start, length)); currentRequestedItem.setRequestId(requestId); requestIdReached = false; } else if (requestTypeReached) { RequestType requestType = null; String parsedValue = new String(ch, start, length); if (parsedValue == "30") // TODO: Add remaining request types requestType = Version1RequestType.LOAN; else requestType = Version1RequestType.ESTIMATE; // FIXME: Put here better default value currentRequestedItem.setRequestType(requestType); requestTypeReached = false; } else if (pickupDateReached) { String pickupDateParsed = new String(ch, start, length); GregorianCalendar pickupDate = AlephUtil.parseGregorianCalendarFromAlephDate(pickupDateParsed); currentRequestedItem.setPickupDate(pickupDate); pickupDateReached = false; } else if (statusReached) { String parsedStatus = new String(ch, start, length); RequestStatusType requestStatusType; if (parsedStatus == "S") requestStatusType = Version1RequestStatusType.AVAILABLE_FOR_PICKUP; else requestStatusType = Version1RequestStatusType.IN_PROCESS; currentRequestedItem.setRequestStatusType(requestStatusType); statusReached = false; } } } }
diff --git a/src/com/rodcastro/karaokesonglist/models/SongRepository.java b/src/com/rodcastro/karaokesonglist/models/SongRepository.java index c59c9b3..a9d3c38 100644 --- a/src/com/rodcastro/karaokesonglist/models/SongRepository.java +++ b/src/com/rodcastro/karaokesonglist/models/SongRepository.java @@ -1,120 +1,120 @@ package com.rodcastro.karaokesonglist.models; import com.rodcastro.karaokesonglist.utils.Settings; import com.rodcastro.karaokesonglist.ui.LoadingBarListener; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.TreeSet; import com.rodcastro.karaokesonglist.visitors.SongLoaderVisitor; /** * * @author rodcastro */ public class SongRepository { private SongLoaderVisitor visitor; private TreeSet<Song> songs; private List<Song> invalidSongs; private TreeSet<Pack> packs; private LoadingBarListener listener; private String path; public SongRepository(String path) { this.path = path; songs = new TreeSet<Song>(); packs = new TreeSet<Pack>(); invalidSongs = new ArrayList<Song>(); } public void loadSongs() { if (songs.isEmpty()) { reloadSongs(); } } public void reloadSongs() { Thread loader = new Thread(new Runnable() { public void run() { SongRepository.this.visitor = new SongLoaderVisitor(Settings.getWorkingPath()); SongRepository.this.visitor.setListener(listener); SongRepository.this.visitor.loadSongs(); SongRepository.this.songs = visitor.getSongs(); SongRepository.this.packs = visitor.getPacks(); SongRepository.this.invalidSongs = visitor.getInvalidSongs(); if (listener != null) listener.onFinish(); } }); loader.start(); } public int getSongCount() { return songs.size(); } public Song findSong(int uniqueId) { Song mock = new Song(uniqueId); return songs.floor(mock); } public String[][] findSongs(String search, boolean searchName, boolean searchArtist, boolean searchPack) { Iterator<Song> iterator = songs.iterator(); List<Song> results = new ArrayList<Song>(); Song current; while (iterator.hasNext()) { current = iterator.next(); if (searchName && current.getFormattedSongName().toUpperCase().contains(search.toUpperCase())) { results.add(current); } else if (searchArtist && current.getFormattedArtist().toUpperCase().contains(search.toUpperCase())) { results.add(current); - } else if (searchPack && current.getPack().getFullName().toUpperCase().contains(search.toUpperCase())) { + } else if (current.getPack() != null && searchPack && current.getPack().getFullName().toUpperCase().contains(search.toUpperCase())) { results.add(current); } } String[][] array = new String[results.size()][]; for (int i = 0; i < results.size(); i++) { Song song = results.get(i); String[] row = new String[4]; if (song.getPack() != null) { row[2] = song.getPack().getFullName(); } else { row[2] = song.getFileName(); } row[0] = song.getFormattedSongName(); row[1] = song.getFormattedArtist(); row[3] = song.getUniqueId() + ""; array[i] = row; } return array; } public String[][] findInvalidSongs(String search) { List<Song> results = new ArrayList<Song>(); for (Song song : invalidSongs) { if (song.getFileName().toUpperCase().contains(search.toUpperCase())) { results.add(song); } } String[][] array = new String[results.size()][]; for (int i = 0; i < results.size(); i++) { Song song = results.get(i); String[] row = new String[1]; row[0] = song.getFileName(); array[i] = row; } return array; } public LoadingBarListener getListener() { return listener; } public void setListener(LoadingBarListener listener) { this.listener = listener; if (visitor != null) { visitor.setListener(listener); } } }
true
true
public String[][] findSongs(String search, boolean searchName, boolean searchArtist, boolean searchPack) { Iterator<Song> iterator = songs.iterator(); List<Song> results = new ArrayList<Song>(); Song current; while (iterator.hasNext()) { current = iterator.next(); if (searchName && current.getFormattedSongName().toUpperCase().contains(search.toUpperCase())) { results.add(current); } else if (searchArtist && current.getFormattedArtist().toUpperCase().contains(search.toUpperCase())) { results.add(current); } else if (searchPack && current.getPack().getFullName().toUpperCase().contains(search.toUpperCase())) { results.add(current); } } String[][] array = new String[results.size()][]; for (int i = 0; i < results.size(); i++) { Song song = results.get(i); String[] row = new String[4]; if (song.getPack() != null) { row[2] = song.getPack().getFullName(); } else { row[2] = song.getFileName(); } row[0] = song.getFormattedSongName(); row[1] = song.getFormattedArtist(); row[3] = song.getUniqueId() + ""; array[i] = row; } return array; }
public String[][] findSongs(String search, boolean searchName, boolean searchArtist, boolean searchPack) { Iterator<Song> iterator = songs.iterator(); List<Song> results = new ArrayList<Song>(); Song current; while (iterator.hasNext()) { current = iterator.next(); if (searchName && current.getFormattedSongName().toUpperCase().contains(search.toUpperCase())) { results.add(current); } else if (searchArtist && current.getFormattedArtist().toUpperCase().contains(search.toUpperCase())) { results.add(current); } else if (current.getPack() != null && searchPack && current.getPack().getFullName().toUpperCase().contains(search.toUpperCase())) { results.add(current); } } String[][] array = new String[results.size()][]; for (int i = 0; i < results.size(); i++) { Song song = results.get(i); String[] row = new String[4]; if (song.getPack() != null) { row[2] = song.getPack().getFullName(); } else { row[2] = song.getFileName(); } row[0] = song.getFormattedSongName(); row[1] = song.getFormattedArtist(); row[3] = song.getUniqueId() + ""; array[i] = row; } return array; }
diff --git a/src/modules/Poll.java b/src/modules/Poll.java index f2310b6..8e4ad78 100644 --- a/src/modules/Poll.java +++ b/src/modules/Poll.java @@ -1,189 +1,199 @@ package modules; import static org.jibble.pircbot.Colors.*; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.Vector; import debugging.Log; import au.com.bytecode.opencsv.CSVParser; import main.Message; import main.NoiseModule; import static panacea.Panacea.*; import static modules.Slap.slapUser; /** * Poll * * @author Michael Mrozek * Created Jun 16, 2009. */ public class Poll extends NoiseModule { private static final int WAIT_TIME = 180; private static final String COLOR_ERROR = RED; private static final String COLOR_SUCCESS = GREEN; private static final String COLOR_VOTE = PURPLE; private final CSVParser parser = new CSVParser(' '); private Timer pollTimer = null; private String pollText = ""; private String pollOwner = ""; private long startTime; private Map<String, String> votes; private List<String> validVotes; //@Command("\\.poll \\[((?:" + VOTE_CLASS_REGEX + "+,?)+)\\] ?(.*)") //@Command("\\.poll \\[(" + VOTE_CLASS_REGEX + "+)\\] ?(.*)") @Command("\\.poll (.*)") public void poll(Message message, String argLine) { if(this.pollTimer != null) { this.bot.reply(message, "A poll is in progress"); return; } this.pollOwner = message.getSender(); this.votes = new HashMap<String, String>(); try { final String[] args = this.parser.parseLine(argLine); this.pollText = args[0]; this.validVotes = new LinkedList<String>(); if(args.length > 1) { for(int i = 1; i < args.length; i++) { String option = args[i].trim(); if(!option.isEmpty() && !this.validVotes.contains(option)) this.validVotes.add(option); } } else { this.validVotes.addAll(Arrays.asList(new String[] {"yes", "no"})); } } catch(IOException e) { this.bot.sendMessage(COLOR_ERROR + "Exception attempting to parse vote options"); Log.e(e); return; } if(this.validVotes.size() < 2) { this.bot.reply(message, "Polls need at least two options"); return; } this.pollTimer = new Timer(); this.pollTimer.schedule(new TimerTask() { @Override public void run() { Poll.this.finished(); } }, WAIT_TIME * 1000); this.startTime = System.currentTimeMillis(); - this.bot.sendMessage(message.getSender() + " has started a poll (vote with ." + Help.COLOR_COMMAND + "vote" + NORMAL + " " + Help.COLOR_ARGUMENT + implode(this.validVotes.toArray(new String[0]), NORMAL + "/" + Help.COLOR_ARGUMENT) + NORMAL + " in the next " + WAIT_TIME + " seconds): " + this.pollText); + String msg = String.format("%s has started a poll (vote with .%svote%s {%s%s%s} in the next %d seconds): %s", + message.getSender(), + Help.COLOR_COMMAND, + NORMAL, + Help.COLOR_ARGUMENT, + implode(this.validVotes.toArray(new String[0]), + NORMAL + "|" + Help.COLOR_ARGUMENT), + NORMAL, + WAIT_TIME, + this.pollText); + this.bot.sendMessage(msg); } @Command("\\.vote *\\$([1-9][0-9]*) *") public void vote(Message message, int vote) { this.vote(message, this.validVotes != null ? this.validVotes.get(vote-1) : null); } @Command("\\.vote *(.+) *") public void vote(Message message, String vote) { if(this.pollText == "") { this.bot.reply(message, COLOR_ERROR + "There is no poll to vote on"); return; } vote = vote.replaceAll("\\\\\\$", "\\$"); if(!this.validVotes.contains(vote)) { this.bot.reply(message, COLOR_ERROR + "Invalid vote"); return; } this.votes.put(message.getSender(), vote); if (this.pollTimer == null) this.bot.sendAction(slapUser(message.getSender())); this.bot.reply(message, COLOR_SUCCESS + "Vote recorded" + NORMAL + ". Current standing: " + this.tabulate()); } @Command("\\.pollstats") public void stats(Message message) { if(this.pollTimer == null) { this.bot.reply(message, COLOR_ERROR + "There is no poll in progress to check"); } else { final int timeLeft = WAIT_TIME + (int)(this.startTime - System.currentTimeMillis()) / 1000; this.bot.reply(message, "(" + timeLeft + "s remain" + (timeLeft == 1 ? "s" : "") + "): " + this.tabulate()); } } @Command("\\.cancelpoll") public void cancel(Message message) { if(this.pollTimer == null) { this.bot.reply(message, COLOR_ERROR + "There is no poll in progress to cancel"); } else if(!this.pollOwner.equals(message.getSender())) { this.bot.reply(message, COLOR_ERROR + "Only " + this.pollOwner + " can cancel the poll"); } else if(!this.votes.isEmpty()) { this.bot.reply(message, COLOR_ERROR + "You can't cancel a poll once votes are in"); } else { this.pollTimer.cancel(); this.pollTimer = null; this.bot.reply(message, COLOR_SUCCESS + "Poll canceled"); } } private void finished() { this.pollTimer = null; this.bot.sendMessage(COLOR_SUCCESS + "Poll finished" + NORMAL + ": " + this.pollText); this.bot.sendMessage("Results: " + (this.votes.isEmpty() ? COLOR_VOTE + "No votes" : this.tabulate())); } private String tabulate() { final Map<String, LinkedList<String>> nicksPerVote = new HashMap<String, LinkedList<String>>(); for(String vote : this.validVotes) { nicksPerVote.put(vote, new LinkedList<String>()); } for(String nick : this.votes.keySet()) { nicksPerVote.get(this.votes.get(nick)).add(nick); } final Vector<String> texts = new Vector<String>(nicksPerVote.size()); for(String vote : this.validVotes) { final LinkedList<String> nicks = nicksPerVote.get(vote); texts.add(COLOR_VOTE + nicks.size() + " " + vote + NORMAL + (nicks.isEmpty() ? "" : " (" + implode(nicks.toArray(new String[0]), ", ") + ")")); } return implode(texts.toArray(new String[0]), ", "); } @Override public String getFriendlyName() {return "Poll";} @Override public String getDescription() {return "Polls users about a given question";} @Override public String[] getExamples() { return new String[] { // ".poll _question_ -- Allow users to vote yes or no on _question_", // ".poll [_vote1_,_vote2_,...] _question_ -- Allow users to vote _vote1_ or _vote2_ or ... on _question_", ".poll _question_ -- Allow users to vote yes or no on _question_. Double-quote _question_ if it has spaces", ".poll _question_ _vote1_ _vote2_ ... -- Allow users to vote _vote1_ or _vote2_ or ... on _question_. Double-quote any arguments if they have spaces", ".vote _vote_ -- Cast your vote as _vote_ (must be one of the votes specified in the poll)", ".pollstats -- Display time remaining in the poll and the current votes", ".cancelpoll -- Cancel the poll if no votes have been cast yet" }; } @Override public void unload() { if(this.pollTimer != null) { this.pollTimer.cancel(); this.pollTimer = null; } } }
true
true
public void poll(Message message, String argLine) { if(this.pollTimer != null) { this.bot.reply(message, "A poll is in progress"); return; } this.pollOwner = message.getSender(); this.votes = new HashMap<String, String>(); try { final String[] args = this.parser.parseLine(argLine); this.pollText = args[0]; this.validVotes = new LinkedList<String>(); if(args.length > 1) { for(int i = 1; i < args.length; i++) { String option = args[i].trim(); if(!option.isEmpty() && !this.validVotes.contains(option)) this.validVotes.add(option); } } else { this.validVotes.addAll(Arrays.asList(new String[] {"yes", "no"})); } } catch(IOException e) { this.bot.sendMessage(COLOR_ERROR + "Exception attempting to parse vote options"); Log.e(e); return; } if(this.validVotes.size() < 2) { this.bot.reply(message, "Polls need at least two options"); return; } this.pollTimer = new Timer(); this.pollTimer.schedule(new TimerTask() { @Override public void run() { Poll.this.finished(); } }, WAIT_TIME * 1000); this.startTime = System.currentTimeMillis(); this.bot.sendMessage(message.getSender() + " has started a poll (vote with ." + Help.COLOR_COMMAND + "vote" + NORMAL + " " + Help.COLOR_ARGUMENT + implode(this.validVotes.toArray(new String[0]), NORMAL + "/" + Help.COLOR_ARGUMENT) + NORMAL + " in the next " + WAIT_TIME + " seconds): " + this.pollText); }
public void poll(Message message, String argLine) { if(this.pollTimer != null) { this.bot.reply(message, "A poll is in progress"); return; } this.pollOwner = message.getSender(); this.votes = new HashMap<String, String>(); try { final String[] args = this.parser.parseLine(argLine); this.pollText = args[0]; this.validVotes = new LinkedList<String>(); if(args.length > 1) { for(int i = 1; i < args.length; i++) { String option = args[i].trim(); if(!option.isEmpty() && !this.validVotes.contains(option)) this.validVotes.add(option); } } else { this.validVotes.addAll(Arrays.asList(new String[] {"yes", "no"})); } } catch(IOException e) { this.bot.sendMessage(COLOR_ERROR + "Exception attempting to parse vote options"); Log.e(e); return; } if(this.validVotes.size() < 2) { this.bot.reply(message, "Polls need at least two options"); return; } this.pollTimer = new Timer(); this.pollTimer.schedule(new TimerTask() { @Override public void run() { Poll.this.finished(); } }, WAIT_TIME * 1000); this.startTime = System.currentTimeMillis(); String msg = String.format("%s has started a poll (vote with .%svote%s {%s%s%s} in the next %d seconds): %s", message.getSender(), Help.COLOR_COMMAND, NORMAL, Help.COLOR_ARGUMENT, implode(this.validVotes.toArray(new String[0]), NORMAL + "|" + Help.COLOR_ARGUMENT), NORMAL, WAIT_TIME, this.pollText); this.bot.sendMessage(msg); }
diff --git a/TFC_Shared/src/TFC/TileEntities/TileEntityEarlyBloomery.java b/TFC_Shared/src/TFC/TileEntities/TileEntityEarlyBloomery.java index 9a2b6c72d..b69dd9ba8 100644 --- a/TFC_Shared/src/TFC/TileEntities/TileEntityEarlyBloomery.java +++ b/TFC_Shared/src/TFC/TileEntities/TileEntityEarlyBloomery.java @@ -1,318 +1,318 @@ package TFC.TileEntities; import java.util.Iterator; import java.util.List; import net.minecraft.block.material.Material; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import TFC.TFCBlocks; import TFC.TFCItems; import TFC.API.ISmeltable; import TFC.API.Constant.Global; import TFC.Blocks.Devices.BlockEarlyBloomery; import TFC.Core.TFC_Time; import TFC.Items.ItemOre; public class TileEntityEarlyBloomery extends TileEntity { public boolean isValid; public boolean bloomeryLit; private int prevStackSize; private int numAirBlocks; //Bloomery public int charcoalCount; public long fuelTimeLeft; public int oreCount; public int outCount; public TileEntityEarlyBloomery() { isValid = false; bloomeryLit = false; numAirBlocks = 0; charcoalCount = 0; oreCount = 0; outCount = 0; } private Boolean CheckValidity() { if(!worldObj.isBlockNormalCube(xCoord, yCoord+1, zCoord)) { return false; } if(!worldObj.isBlockNormalCube(xCoord, yCoord-1, zCoord)) { return false; } return true; } public boolean isStackValid(int i, int j, int k) { if(((worldObj.getBlockId(i, j-1, k) != TFCBlocks.Molten.blockID && worldObj.getBlockMaterial(i, j-1, k) != Material.rock) || (!worldObj.isBlockNormalCube(i, j-1, k)))&& worldObj.getBlockId(i, j-1, k) != TFCBlocks.Charcoal.blockID) { return false; } if(worldObj.getBlockMaterial(i+1, j, k) != Material.rock || !worldObj.isBlockNormalCube(i+1, j, k)) { return false; } if(worldObj.getBlockMaterial(i-1, j, k) != Material.rock || !worldObj.isBlockNormalCube(i-1, j, k)) { return false; } if(worldObj.getBlockMaterial(i, j, k+1) != Material.rock || !worldObj.isBlockNormalCube(i, j, k+1)) { return false; } if(worldObj.getBlockMaterial(i, j, k-1) != Material.rock || !worldObj.isBlockNormalCube(i, j, k-1)) { return false; } return true; } public boolean AddOreToFire(ItemStack is) { if(((ISmeltable)is.getItem()).GetMetalType(is) == Global.PIGIRON || ((ISmeltable)is.getItem()).GetMetalType(is) == Global.WROUGHTIRON) { outCount += ((ISmeltable)is.getItem()).GetMetalReturnAmount(is); return true; } return false; } public boolean canLight() { if(!worldObj.isRemote) { //get the direction that the bloomery is facing so that we know where the stack should be int meta = worldObj.getBlockMetadata(xCoord, yCoord, zCoord) & 3; int[] direction = BlockEarlyBloomery.headBlockToFootBlockMap[meta]; if (this.charcoalCount < this.oreCount) { return false; } if(worldObj.getBlockId(xCoord+direction[0], yCoord, zCoord+direction[1])==TFCBlocks.Charcoal.blockID && worldObj.getBlockMetadata(xCoord+direction[0], yCoord, zCoord+direction[1]) >= 7 && !bloomeryLit) { bloomeryLit = true; this.fuelTimeLeft = TFC_Time.getTotalTicks() + 14400; if((meta & 4) == 0) { worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, meta + 4, 3); } return true; } } return false; } @Override public void updateEntity() { if(!worldObj.isRemote) { //Do the funky math to find how many molten blocks should be placed int count = charcoalCount+oreCount; int moltenCount = count > 0 && count < 8 ? 1 : count / 8; int validCount = 0; int maxCount = 0; //get the direction that the bloomery is facing so that we know where the stack should be int meta = worldObj.getBlockMetadata(xCoord, yCoord, zCoord); int[] direction = BlockEarlyBloomery.headBlockToFootBlockMap[meta & 3]; if(bloomeryLit && TFC_Time.getTotalTicks() > fuelTimeLeft) { if((worldObj.getBlockId(xCoord+direction[0], yCoord, zCoord+direction[1])==TFCBlocks.Charcoal.blockID)) { bloomeryLit = false; worldObj.setBlock(xCoord+direction[0], yCoord, zCoord+direction[1], TFCBlocks.Bloom.blockID); - worldObj.setBlockToAir(xCoord+direction[0], yCoord+moltenCount-1, zCoord+direction[1]); + worldObj.setBlockToAir(xCoord+direction[0], yCoord+(moltenCount<2?2:moltenCount)-1, zCoord+direction[1]); oreCount = 0; charcoalCount = 0; ((TileEntityBloom)(worldObj.getBlockTileEntity(xCoord+direction[0], yCoord, zCoord+direction[1]))).setSize(outCount); outCount = 0; } if((meta & 4) != 0) { worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, meta & 3, 3); } } if(outCount < 0) { outCount = 0; } if(oreCount < 0) { oreCount = 0; } if(charcoalCount < 0) { charcoalCount = 0; } /* Calculate how much ore the bloomery can hold. */ if(isStackValid(xCoord+direction[0], yCoord+3, zCoord+direction[1])) { maxCount = 16; } else if(isStackValid(xCoord+direction[0], yCoord+2, zCoord+direction[1])) { maxCount = 12; } else if(isStackValid(xCoord+direction[0], yCoord+1, zCoord+direction[1])) { maxCount = 8; } /*Fill the bloomery stack with molten ore. */ for (int i = 1; i < moltenCount; i++) { /*The stack must be air or already be molten rock*/ if((worldObj.getBlockId(xCoord+direction[0], yCoord+i, zCoord+direction[1]) == 0 || worldObj.getBlockId(xCoord+direction[0], yCoord+i, zCoord+direction[1]) == TFCBlocks.Molten.blockID) && worldObj.getBlockMaterial(xCoord+direction[0], yCoord-1, zCoord+direction[1]) == Material.rock) { //Make sure that the Stack is surrounded by rock if(isStackValid(xCoord+direction[0], yCoord+i, zCoord+direction[1])) { validCount++; } if(i-1 < moltenCount && i <= validCount) { if(this.bloomeryLit) { worldObj.setBlock(xCoord+direction[0], yCoord+i, zCoord+direction[1], TFCBlocks.Molten.blockID, 15, 2); } else { worldObj.setBlock(xCoord+direction[0], yCoord+i, zCoord+direction[1], TFCBlocks.Molten.blockID, 0, 2); } } else { worldObj.setBlockToAir(xCoord+direction[0], yCoord+i, zCoord+direction[1]); } } } /*Create a list of all the items that are falling into the stack */ List list = worldObj.getEntitiesWithinAABB(EntityItem.class, AxisAlignedBB.getBoundingBox( xCoord+direction[0], yCoord+moltenCount, zCoord+direction[1], xCoord+direction[0]+1, yCoord+moltenCount+1.1, zCoord+direction[1]+1)); if(moltenCount == 0) { moltenCount = 1; } /*Make sure the list isn't null or empty and that the stack is valid 1 layer above the Molten Ore*/ if (list != null && !list.isEmpty() && isStackValid(xCoord+direction[0], yCoord+moltenCount, zCoord+direction[1]) && !bloomeryLit) { /*Iterate through the list and check for charcoal, coke, and ore*/ for (Iterator iterator = list.iterator(); iterator.hasNext();) { EntityItem entity = (EntityItem)iterator.next(); if(entity.getEntityItem().itemID == Item.coal.itemID && entity.getEntityItem().getItemDamage() == 1 || entity.getEntityItem().itemID == TFCItems.Coke.itemID) { for(int c = 0; c < entity.getEntityItem().stackSize; c++) { if(charcoalCount+oreCount < (2*maxCount) && charcoalCount < (maxCount)) { charcoalCount++; entity.getEntityItem().stackSize--; } } if(entity.getEntityItem().stackSize == 0) { entity.setDead(); } } /*If the item that's been tossed in is a type of Ore and it can melt down into something then add the ore to the list of items in the fire.*/ else if(entity.getEntityItem().getItem() instanceof ItemOre && ((ItemOre)entity.getEntityItem().getItem()).isSmeltable(entity.getEntityItem())) { int c = entity.getEntityItem().stackSize; for(; c > 0; ) { if(charcoalCount+oreCount < (2*maxCount) && oreCount < (maxCount) && outCount < 1000) { if(AddOreToFire(new ItemStack(entity.getEntityItem().getItem(),1,entity.getEntityItem().getItemDamage()))) { oreCount+=1; c--; } else { break; } } else { break; } } if(c == 0) { entity.setDead(); } else { entity.getEntityItem().stackSize = c; } } else if(entity.getEntityItem().getItem() instanceof ISmeltable && ((ISmeltable)entity.getEntityItem().getItem()).isSmeltable(entity.getEntityItem())) { int c = entity.getEntityItem().stackSize; for(; c > 0; ) { if(((ISmeltable)entity.getEntityItem().getItem()).GetMetalReturnAmount(entity.getEntityItem()) < 100 && outCount < 1000) { if(AddOreToFire(new ItemStack(entity.getEntityItem().getItem(),1,entity.getEntityItem().getItemDamage()))) { oreCount+=1; c--; } else { break; } } else { break; } } if(c == 0) { entity.setDead(); } else { entity.getEntityItem().stackSize = c; } } } } //Here we make sure that the forge is valid isValid = CheckValidity(); } } @Override public void writeToNBT(NBTTagCompound nbttagcompound) { super.writeToNBT(nbttagcompound); nbttagcompound.setBoolean("isValid", isValid); nbttagcompound.setLong("fuelTimeLeft", fuelTimeLeft); nbttagcompound.setInteger("charcoalCount", charcoalCount); nbttagcompound.setInteger("outCount", outCount); nbttagcompound.setInteger("oreCount", oreCount); nbttagcompound.setBoolean("isLit",bloomeryLit); } @Override public void readFromNBT(NBTTagCompound nbttagcompound) { super.readFromNBT(nbttagcompound); isValid = nbttagcompound.getBoolean("isValid"); fuelTimeLeft = nbttagcompound.getLong("fuelTimeLeft"); charcoalCount = nbttagcompound.getInteger("charcoalCount"); outCount = nbttagcompound.getInteger("outCount"); oreCount = nbttagcompound.getInteger("oreCount"); bloomeryLit = nbttagcompound.getBoolean("isLit"); } }
true
true
public void updateEntity() { if(!worldObj.isRemote) { //Do the funky math to find how many molten blocks should be placed int count = charcoalCount+oreCount; int moltenCount = count > 0 && count < 8 ? 1 : count / 8; int validCount = 0; int maxCount = 0; //get the direction that the bloomery is facing so that we know where the stack should be int meta = worldObj.getBlockMetadata(xCoord, yCoord, zCoord); int[] direction = BlockEarlyBloomery.headBlockToFootBlockMap[meta & 3]; if(bloomeryLit && TFC_Time.getTotalTicks() > fuelTimeLeft) { if((worldObj.getBlockId(xCoord+direction[0], yCoord, zCoord+direction[1])==TFCBlocks.Charcoal.blockID)) { bloomeryLit = false; worldObj.setBlock(xCoord+direction[0], yCoord, zCoord+direction[1], TFCBlocks.Bloom.blockID); worldObj.setBlockToAir(xCoord+direction[0], yCoord+moltenCount-1, zCoord+direction[1]); oreCount = 0; charcoalCount = 0; ((TileEntityBloom)(worldObj.getBlockTileEntity(xCoord+direction[0], yCoord, zCoord+direction[1]))).setSize(outCount); outCount = 0; } if((meta & 4) != 0) { worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, meta & 3, 3); } } if(outCount < 0) { outCount = 0; } if(oreCount < 0) { oreCount = 0; } if(charcoalCount < 0) { charcoalCount = 0; } /* Calculate how much ore the bloomery can hold. */ if(isStackValid(xCoord+direction[0], yCoord+3, zCoord+direction[1])) { maxCount = 16; } else if(isStackValid(xCoord+direction[0], yCoord+2, zCoord+direction[1])) { maxCount = 12; } else if(isStackValid(xCoord+direction[0], yCoord+1, zCoord+direction[1])) { maxCount = 8; } /*Fill the bloomery stack with molten ore. */ for (int i = 1; i < moltenCount; i++) { /*The stack must be air or already be molten rock*/ if((worldObj.getBlockId(xCoord+direction[0], yCoord+i, zCoord+direction[1]) == 0 || worldObj.getBlockId(xCoord+direction[0], yCoord+i, zCoord+direction[1]) == TFCBlocks.Molten.blockID) && worldObj.getBlockMaterial(xCoord+direction[0], yCoord-1, zCoord+direction[1]) == Material.rock) { //Make sure that the Stack is surrounded by rock if(isStackValid(xCoord+direction[0], yCoord+i, zCoord+direction[1])) { validCount++; } if(i-1 < moltenCount && i <= validCount) { if(this.bloomeryLit) { worldObj.setBlock(xCoord+direction[0], yCoord+i, zCoord+direction[1], TFCBlocks.Molten.blockID, 15, 2); } else { worldObj.setBlock(xCoord+direction[0], yCoord+i, zCoord+direction[1], TFCBlocks.Molten.blockID, 0, 2); } } else { worldObj.setBlockToAir(xCoord+direction[0], yCoord+i, zCoord+direction[1]); } } } /*Create a list of all the items that are falling into the stack */ List list = worldObj.getEntitiesWithinAABB(EntityItem.class, AxisAlignedBB.getBoundingBox( xCoord+direction[0], yCoord+moltenCount, zCoord+direction[1], xCoord+direction[0]+1, yCoord+moltenCount+1.1, zCoord+direction[1]+1)); if(moltenCount == 0) { moltenCount = 1; } /*Make sure the list isn't null or empty and that the stack is valid 1 layer above the Molten Ore*/ if (list != null && !list.isEmpty() && isStackValid(xCoord+direction[0], yCoord+moltenCount, zCoord+direction[1]) && !bloomeryLit) { /*Iterate through the list and check for charcoal, coke, and ore*/ for (Iterator iterator = list.iterator(); iterator.hasNext();) { EntityItem entity = (EntityItem)iterator.next(); if(entity.getEntityItem().itemID == Item.coal.itemID && entity.getEntityItem().getItemDamage() == 1 || entity.getEntityItem().itemID == TFCItems.Coke.itemID) { for(int c = 0; c < entity.getEntityItem().stackSize; c++) { if(charcoalCount+oreCount < (2*maxCount) && charcoalCount < (maxCount)) { charcoalCount++; entity.getEntityItem().stackSize--; } } if(entity.getEntityItem().stackSize == 0) { entity.setDead(); } } /*If the item that's been tossed in is a type of Ore and it can melt down into something then add the ore to the list of items in the fire.*/ else if(entity.getEntityItem().getItem() instanceof ItemOre && ((ItemOre)entity.getEntityItem().getItem()).isSmeltable(entity.getEntityItem())) { int c = entity.getEntityItem().stackSize; for(; c > 0; ) { if(charcoalCount+oreCount < (2*maxCount) && oreCount < (maxCount) && outCount < 1000) { if(AddOreToFire(new ItemStack(entity.getEntityItem().getItem(),1,entity.getEntityItem().getItemDamage()))) { oreCount+=1; c--; } else { break; } } else { break; } } if(c == 0) { entity.setDead(); } else { entity.getEntityItem().stackSize = c; } } else if(entity.getEntityItem().getItem() instanceof ISmeltable && ((ISmeltable)entity.getEntityItem().getItem()).isSmeltable(entity.getEntityItem())) { int c = entity.getEntityItem().stackSize; for(; c > 0; ) { if(((ISmeltable)entity.getEntityItem().getItem()).GetMetalReturnAmount(entity.getEntityItem()) < 100 && outCount < 1000) { if(AddOreToFire(new ItemStack(entity.getEntityItem().getItem(),1,entity.getEntityItem().getItemDamage()))) { oreCount+=1; c--; } else { break; } } else { break; } } if(c == 0) { entity.setDead(); } else { entity.getEntityItem().stackSize = c; } } } } //Here we make sure that the forge is valid isValid = CheckValidity(); } }
public void updateEntity() { if(!worldObj.isRemote) { //Do the funky math to find how many molten blocks should be placed int count = charcoalCount+oreCount; int moltenCount = count > 0 && count < 8 ? 1 : count / 8; int validCount = 0; int maxCount = 0; //get the direction that the bloomery is facing so that we know where the stack should be int meta = worldObj.getBlockMetadata(xCoord, yCoord, zCoord); int[] direction = BlockEarlyBloomery.headBlockToFootBlockMap[meta & 3]; if(bloomeryLit && TFC_Time.getTotalTicks() > fuelTimeLeft) { if((worldObj.getBlockId(xCoord+direction[0], yCoord, zCoord+direction[1])==TFCBlocks.Charcoal.blockID)) { bloomeryLit = false; worldObj.setBlock(xCoord+direction[0], yCoord, zCoord+direction[1], TFCBlocks.Bloom.blockID); worldObj.setBlockToAir(xCoord+direction[0], yCoord+(moltenCount<2?2:moltenCount)-1, zCoord+direction[1]); oreCount = 0; charcoalCount = 0; ((TileEntityBloom)(worldObj.getBlockTileEntity(xCoord+direction[0], yCoord, zCoord+direction[1]))).setSize(outCount); outCount = 0; } if((meta & 4) != 0) { worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, meta & 3, 3); } } if(outCount < 0) { outCount = 0; } if(oreCount < 0) { oreCount = 0; } if(charcoalCount < 0) { charcoalCount = 0; } /* Calculate how much ore the bloomery can hold. */ if(isStackValid(xCoord+direction[0], yCoord+3, zCoord+direction[1])) { maxCount = 16; } else if(isStackValid(xCoord+direction[0], yCoord+2, zCoord+direction[1])) { maxCount = 12; } else if(isStackValid(xCoord+direction[0], yCoord+1, zCoord+direction[1])) { maxCount = 8; } /*Fill the bloomery stack with molten ore. */ for (int i = 1; i < moltenCount; i++) { /*The stack must be air or already be molten rock*/ if((worldObj.getBlockId(xCoord+direction[0], yCoord+i, zCoord+direction[1]) == 0 || worldObj.getBlockId(xCoord+direction[0], yCoord+i, zCoord+direction[1]) == TFCBlocks.Molten.blockID) && worldObj.getBlockMaterial(xCoord+direction[0], yCoord-1, zCoord+direction[1]) == Material.rock) { //Make sure that the Stack is surrounded by rock if(isStackValid(xCoord+direction[0], yCoord+i, zCoord+direction[1])) { validCount++; } if(i-1 < moltenCount && i <= validCount) { if(this.bloomeryLit) { worldObj.setBlock(xCoord+direction[0], yCoord+i, zCoord+direction[1], TFCBlocks.Molten.blockID, 15, 2); } else { worldObj.setBlock(xCoord+direction[0], yCoord+i, zCoord+direction[1], TFCBlocks.Molten.blockID, 0, 2); } } else { worldObj.setBlockToAir(xCoord+direction[0], yCoord+i, zCoord+direction[1]); } } } /*Create a list of all the items that are falling into the stack */ List list = worldObj.getEntitiesWithinAABB(EntityItem.class, AxisAlignedBB.getBoundingBox( xCoord+direction[0], yCoord+moltenCount, zCoord+direction[1], xCoord+direction[0]+1, yCoord+moltenCount+1.1, zCoord+direction[1]+1)); if(moltenCount == 0) { moltenCount = 1; } /*Make sure the list isn't null or empty and that the stack is valid 1 layer above the Molten Ore*/ if (list != null && !list.isEmpty() && isStackValid(xCoord+direction[0], yCoord+moltenCount, zCoord+direction[1]) && !bloomeryLit) { /*Iterate through the list and check for charcoal, coke, and ore*/ for (Iterator iterator = list.iterator(); iterator.hasNext();) { EntityItem entity = (EntityItem)iterator.next(); if(entity.getEntityItem().itemID == Item.coal.itemID && entity.getEntityItem().getItemDamage() == 1 || entity.getEntityItem().itemID == TFCItems.Coke.itemID) { for(int c = 0; c < entity.getEntityItem().stackSize; c++) { if(charcoalCount+oreCount < (2*maxCount) && charcoalCount < (maxCount)) { charcoalCount++; entity.getEntityItem().stackSize--; } } if(entity.getEntityItem().stackSize == 0) { entity.setDead(); } } /*If the item that's been tossed in is a type of Ore and it can melt down into something then add the ore to the list of items in the fire.*/ else if(entity.getEntityItem().getItem() instanceof ItemOre && ((ItemOre)entity.getEntityItem().getItem()).isSmeltable(entity.getEntityItem())) { int c = entity.getEntityItem().stackSize; for(; c > 0; ) { if(charcoalCount+oreCount < (2*maxCount) && oreCount < (maxCount) && outCount < 1000) { if(AddOreToFire(new ItemStack(entity.getEntityItem().getItem(),1,entity.getEntityItem().getItemDamage()))) { oreCount+=1; c--; } else { break; } } else { break; } } if(c == 0) { entity.setDead(); } else { entity.getEntityItem().stackSize = c; } } else if(entity.getEntityItem().getItem() instanceof ISmeltable && ((ISmeltable)entity.getEntityItem().getItem()).isSmeltable(entity.getEntityItem())) { int c = entity.getEntityItem().stackSize; for(; c > 0; ) { if(((ISmeltable)entity.getEntityItem().getItem()).GetMetalReturnAmount(entity.getEntityItem()) < 100 && outCount < 1000) { if(AddOreToFire(new ItemStack(entity.getEntityItem().getItem(),1,entity.getEntityItem().getItemDamage()))) { oreCount+=1; c--; } else { break; } } else { break; } } if(c == 0) { entity.setDead(); } else { entity.getEntityItem().stackSize = c; } } } } //Here we make sure that the forge is valid isValid = CheckValidity(); } }
diff --git a/tool/src/java/org/sakaiproject/evaluation/tool/producers/EvaluationSettingsProducer.java b/tool/src/java/org/sakaiproject/evaluation/tool/producers/EvaluationSettingsProducer.java index 510628e6..ee427736 100644 --- a/tool/src/java/org/sakaiproject/evaluation/tool/producers/EvaluationSettingsProducer.java +++ b/tool/src/java/org/sakaiproject/evaluation/tool/producers/EvaluationSettingsProducer.java @@ -1,526 +1,526 @@ /****************************************************************************** * EvaluationSettingsProducer.java - created by [email protected] on Oct 05, 2006 * * Copyright (c) 2007 Virginia Polytechnic Institute and State University * Licensed under the Educational Community License version 1.0 * * A copy of the Educational Community License has been included in this * distribution and is available at: http://www.opensource.org/licenses/ecl1.php * * Contributors: * Kapil Ahuja ([email protected]) * Rui Feng ([email protected]) *****************************************************************************/ package org.sakaiproject.evaluation.tool.producers; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import org.sakaiproject.evaluation.logic.EvalExternalLogic; import org.sakaiproject.evaluation.logic.EvalSettings; import org.sakaiproject.evaluation.model.constant.EvalConstants; import org.sakaiproject.evaluation.tool.EvaluationBean; import org.sakaiproject.evaluation.tool.EvaluationConstant; import org.sakaiproject.evaluation.tool.params.EmailViewParameters; import org.sakaiproject.evaluation.tool.params.EvalViewParameters; import uk.org.ponder.arrayutil.ArrayUtil; import uk.org.ponder.rsf.components.UIBoundBoolean; import uk.org.ponder.rsf.components.UIBranchContainer; import uk.org.ponder.rsf.components.UICommand; import uk.org.ponder.rsf.components.UIContainer; import uk.org.ponder.rsf.components.UIELBinding; import uk.org.ponder.rsf.components.UIForm; import uk.org.ponder.rsf.components.UIInput; import uk.org.ponder.rsf.components.UIInternalLink; import uk.org.ponder.rsf.components.UIMessage; import uk.org.ponder.rsf.components.UIOutput; import uk.org.ponder.rsf.components.UISelect; import uk.org.ponder.rsf.components.decorators.DecoratorList; import uk.org.ponder.rsf.components.decorators.UIDisabledDecorator; import uk.org.ponder.rsf.evolvers.DateInputEvolver; import uk.org.ponder.rsf.flow.jsfnav.NavigationCase; import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter; import uk.org.ponder.rsf.view.ComponentChecker; import uk.org.ponder.rsf.view.ViewComponentProducer; import uk.org.ponder.rsf.viewstate.SimpleViewParameters; import uk.org.ponder.rsf.viewstate.ViewParameters; /** * This producer is used to render the evaluation settings page. It is used when * user either creates a new evaluation (coming forward from "Start Evaluation" * page or coming backward from "Assign Evaluation to courses" page) or from * control panel to edit the existing settings. * * @author:Kapil Ahuja ([email protected]) * @author:Rui Feng ([email protected]) */ public class EvaluationSettingsProducer implements ViewComponentProducer, NavigationCaseReporter { public static final String VIEW_ID = "evaluation_settings"; //$NON-NLS-1$ public String getViewID() { return VIEW_ID; } private EvalSettings settings; public void setSettings(EvalSettings settings) { this.settings = settings; } private EvaluationBean evaluationBean; public void setEvaluationBean(EvaluationBean evaluationBean) { this.evaluationBean = evaluationBean; } private EvalExternalLogic externalLogic; public void setExternalLogic(EvalExternalLogic externalLogic) { this.externalLogic = externalLogic; } private DateInputEvolver dateevolver; public void setDateEvolver(DateInputEvolver dateevolver) { this.dateevolver = dateevolver; } /* * (non-Javadoc) * * @see uk.org.ponder.rsf.view.ComponentProducer#fillComponents(uk.org.ponder.rsf.components.UIContainer, * uk.org.ponder.rsf.viewstate.ViewParameters, * uk.org.ponder.rsf.view.ComponentChecker) */ public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { // Displaying the top link, page title, page description, and creating the // HTML form - UIOutput.make(tofill, "eval-settings-title", "evalsettings.page.title"); //$NON-NLS-1$ //$NON-NLS-2$ - UIInternalLink.make(tofill, "summary-toplink", "summary.page.title", //$NON-NLS-1$ //$NON-NLS-2$ + UIMessage.make(tofill, "eval-settings-title", "evalsettings.page.title"); //$NON-NLS-1$ //$NON-NLS-2$ + UIInternalLink.make(tofill, "summary-toplink", UIMessage.make("summary.page.title"), //$NON-NLS-1$ //$NON-NLS-2$ new SimpleViewParameters(SummaryProducer.VIEW_ID)); UIForm form = UIForm.make(tofill, "evalSettingsForm"); //$NON-NLS-1$ UIMessage.make(form, "settings-desc-header", "evalsettings.settings.desc.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIOutput .make(form, "evaluationTitle", null, "#{evaluationBean.eval.title}"); //$NON-NLS-1$ //$NON-NLS-2$ Date today = new Date(); Calendar calendar = new GregorianCalendar(); calendar.setTime(today); UIMessage.make(form, "eval-dates-header", "evalsettings.dates.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-start-date-header", "evalsettings.start.date.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage .make(form, "eval-start-date-desc", "evalsettings.start.date.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput startDate = UIInput.make(form, "startDate:", "#{evaluationBean.startDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ if (evaluationBean.eval.getId() != null) { // queued evalution if (today.before(evaluationBean.eval.getStartDate())) { UIInput.make(form, "evalStatus", null, "queued"); //$NON-NLS-1$ //$NON-NLS-2$ } // started evaluation else { startDate.decorators = new DecoratorList(new UIDisabledDecorator()); UIInput.make(form, "evalStatus", null, "active"); //$NON-NLS-1$ //$NON-NLS-2$ } } else { UIInput.make(form, "evalStatus", null, "new"); //$NON-NLS-1$ //$NON-NLS-2$ } dateevolver.evolveDateInput(startDate, calendar.getTime()); calendar.add(Calendar.DATE, 1); // Show the "Stop date" text box only if it is set as yes in the System // settings if (((Boolean) settings.get(EvalSettings.EVAL_USE_STOP_DATE)) .booleanValue()) { UIBranchContainer showStopDate = UIBranchContainer.make(form, "showStopDate:"); //$NON-NLS-1$ UIMessage.make(showStopDate, "eval-stop-date-header", "evalsettings.stop.date.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput stopDate = UIInput.make(showStopDate, "stopDate:", "#{evaluationBean.stopDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(stopDate, calendar.getTime()); } calendar.add(Calendar.DATE, 1); UIMessage .make(form, "eval-due-date-header", "evalsettings.due.date.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput dueDate = UIInput.make(form, "dueDate:", "#{evaluationBean.dueDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(dueDate, calendar.getTime()); calendar.add(Calendar.DATE, 1); UIMessage.make(form, "eval-view-date-header", "evalsettings.view.date.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-view-date-desc", "evalsettings.view.date.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput viewDate = UIInput.make(form, "viewDate:", "#{evaluationBean.viewDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(viewDate, calendar.getTime()); UIMessage.make(form, "eval-results-viewable-header", "evalsettings.results.viewable.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-results-viewable-private-start", "evalsettings.results.viewable.private.start"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-results-viewable-private-middle", "evalsettings.results.viewable.private.middle"); //$NON-NLS-1$ //$NON-NLS-2$ UIOutput.make(form, "userInfo", externalLogic .getUserDisplayName(externalLogic.getCurrentUserId())); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "private-warning-desc", "evalsettings.private.warning.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIBoundBoolean.make(form, "resultsPrivate", "#{evaluationBean.eval.resultsPrivate}", null); //$NON-NLS-1$ //$NON-NLS-2$ /* * (non-Javadoc) Variable is used to decide whether to show the view date * textbox for student and instructor separately or not. */ boolean sameViewDateForAll = ((Boolean) settings .get(EvalSettings.EVAL_USE_SAME_VIEW_DATES)).booleanValue(); /* * (non-Javadoc) If "EvalSettings.STUDENT_VIEW_RESULTS" is set as * configurable i.e. NULL in the database OR is set as TRUE in database, * then show the checkbox. Else do not show the checkbox and just bind the * value to FALSE. */ Boolean tempValue = (Boolean) settings .get(EvalSettings.STUDENT_VIEW_RESULTS); if (tempValue == null || tempValue.booleanValue()) { UIBranchContainer showResultsToStudents = UIBranchContainer.make(form, "showResultsToStudents:"); //$NON-NLS-1$ UIMessage.make(showResultsToStudents, "eval-results-viewable-students", "evalsettings.results.viewable.students"); //$NON-NLS-1$ //$NON-NLS-2$ // If system setting was null implies normal checkbox. If it was TRUE then // a disabled selected checkbox if (tempValue == null) { UIBoundBoolean.make(showResultsToStudents, "studentViewResults", "#{evaluationBean.studentViewResults}", tempValue); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Display only (disabled) and selected check box UIBoundBoolean stuViewCheckbox = UIBoundBoolean.make( showResultsToStudents, "studentViewResults", tempValue); //$NON-NLS-1$ setDisabledAttribute(stuViewCheckbox); // As we have disabled the check box => RSF will not bind the value => // binding it explicitly. form.parameters.add(new UIELBinding( "#{evaluationBean.studentViewResults}", tempValue)); //$NON-NLS-1$ } // If same view date all then show a label else show a text box. if (sameViewDateForAll) { UIMessage.make(showResultsToStudents, "eval-results-stu-inst-date-label", "evalsettings.results.stu.inst.date.label"); //$NON-NLS-1$ //$NON-NLS-2$ } else { UIInput studentsDate = UIInput.make(showResultsToStudents, "studentsDate:", "#{evaluationBean.studentsDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(studentsDate, calendar.getTime()); } } else { form.parameters.add(new UIELBinding( "#{evaluationBean.studentViewResults}", Boolean.FALSE)); //$NON-NLS-1$ } /* * (non-javadoc) If "EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS" is set as * configurable i.e. NULL in the database OR is set as TRUE in database, * then show the checkbox. Else do not show the checkbox and just bind the * value to FALSE. */ tempValue = (Boolean) settings .get(EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS); if (tempValue == null || tempValue.booleanValue()) { UIBranchContainer showResultsToInst = UIBranchContainer.make(form, "showResultsToInst:"); //$NON-NLS-1$ UIMessage.make(showResultsToInst, "eval-results-viewable-instructors", "evalsettings.results.viewable.instructors"); //$NON-NLS-1$ //$NON-NLS-2$ // If system setting was null implies normal checkbox. If it was TRUE then // a disabled selected checkbox if (tempValue == null) { UIBoundBoolean.make(showResultsToInst, "instructorViewResults", "#{evaluationBean.instructorViewResults}", tempValue); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Display only (disabled) and selected check box UIBoundBoolean instViewCheckbox = UIBoundBoolean.make( showResultsToInst, "instructorViewResults", tempValue); //$NON-NLS-1$ setDisabledAttribute(instViewCheckbox); // As we have disabled the check box => RSF will not bind the value => // binding it explicitly. form.parameters.add(new UIELBinding( "#{evaluationBean.instructorViewResults}", tempValue)); //$NON-NLS-1$ } // If same view date all then show a label else show a text box. if (sameViewDateForAll) { UIBranchContainer showResultsToInstLabel = UIBranchContainer.make( showResultsToInst, "showResultsToInstLabel:"); //$NON-NLS-1$ UIMessage.make(showResultsToInstLabel, "eval-results-stu-inst-date-label", "evalsettings.results.stu.inst.date.label"); //$NON-NLS-1$ //$NON-NLS-2$ } else { UIBranchContainer showResultsToInstDate = UIBranchContainer.make( showResultsToInst, "showResultsToInstDate:"); //$NON-NLS-1$ UIInput instructorsDate = UIInput.make(showResultsToInstDate, "instructorsDate:", "#{evaluationBean.instructorsDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(instructorsDate, calendar.getTime()); } } else { form.parameters.add(new UIELBinding( "#{evaluationBean.instructorViewResults}", Boolean.FALSE)); //$NON-NLS-1$ } UIMessage.make(form, "eval-results-viewable-admin-note", "evalsettings.results.viewable.admin.note"); //$NON-NLS-1$ //$NON-NLS-2$ /* * (non-javadoc) If "EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED" is set * as configurable i.e. NULL in the database OR is set as TRUE in database, * then show the checkbox. Else do not show the checkbox and just bind the * value to FALSE. * * Note: The variable showStudentCompletionHeader is used to show * "student-completion-settings-header" It is true only if either of the * three "if's" below are evaluated to true. */ boolean showStudentCompletionHeader = false; tempValue = (Boolean) settings .get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED); if (tempValue == null || tempValue.booleanValue()) { showStudentCompletionHeader = true; UIBranchContainer showBlankQuestionAllowedToStut = UIBranchContainer .make(form, "showBlankQuestionAllowedToStut:"); //$NON-NLS-1$ UIMessage.make(showBlankQuestionAllowedToStut, "blank-responses-allowed-desc", "evalsettings.blank.responses.allowed.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showBlankQuestionAllowedToStut, "blank-responses-allowed-note", "evalsettings.blank.responses.allowed.note"); //$NON-NLS-1$ //$NON-NLS-2$ // If system setting was null implies normal checkbox. If it was TRUE then // a disabled selected checkbox if (tempValue == null) { UIBoundBoolean.make(showBlankQuestionAllowedToStut, "blankResponsesAllowed", "#{evaluationBean.eval.blankResponsesAllowed}", tempValue); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Display only (disabled) and selected check box UIBoundBoolean stuLeaveUnanswered = UIBoundBoolean.make( showBlankQuestionAllowedToStut, "blankResponsesAllowed", tempValue); //$NON-NLS-1$ setDisabledAttribute(stuLeaveUnanswered); // As we have disabled the check box => RSF will not bind the value => // binding it explicitly. form.parameters.add(new UIELBinding( "#{evaluationBean.eval.blankResponsesAllowed}", tempValue)); //$NON-NLS-1$ } } else { form.parameters.add(new UIELBinding( "#{evaluationBean.eval.blankResponsesAllowed}", Boolean.FALSE)); //$NON-NLS-1$ } /* * (non-javadoc) If "EvalSettings.STUDENT_MODIFY_RESPONSES" is set as * configurable i.e. NULL in the database OR is set as TRUE in database, * then show the checkbox. Else do not show the checkbox and just bind the * value to FALSE. */ tempValue = (Boolean) settings.get(EvalSettings.STUDENT_MODIFY_RESPONSES); if (tempValue == null || tempValue.booleanValue()) { showStudentCompletionHeader = true; UIBranchContainer showModifyResponsesAllowedToStu = UIBranchContainer .make(form, "showModifyResponsesAllowedToStu:"); //$NON-NLS-1$ UIMessage.make(showModifyResponsesAllowedToStu, "modify-responses-allowed-desc", "evalsettings.modify.responses.allowed.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showModifyResponsesAllowedToStu, "modify-responses-allowed-note", "evalsettings.modify.responses.allowed.note"); //$NON-NLS-1$ //$NON-NLS-2$ // If system setting was null implies normal checkbox. If it was TRUE then // a disabled selected checkbox if (tempValue == null) { UIBoundBoolean.make(showModifyResponsesAllowedToStu, "modifyResponsesAllowed", "#{evaluationBean.eval.modifyResponsesAllowed}", tempValue); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Display only (disabled) and selected check box UIBoundBoolean stuModifyResponses = UIBoundBoolean.make( showModifyResponsesAllowedToStu, "modifyResponsesAllowed", tempValue); //$NON-NLS-1$ setDisabledAttribute(stuModifyResponses); // As we have disabled the check box => RSF will not bind the value => // binding it explicitly. form.parameters.add(new UIELBinding( "#{evaluationBean.eval.modifyResponsesAllowed}", tempValue)); //$NON-NLS-1$ } } else { form.parameters.add(new UIELBinding( "#{evaluationBean.eval.modifyResponsesAllowed}", Boolean.FALSE)); //$NON-NLS-1$ } // This options are commented for some time. if (false) { showStudentCompletionHeader = true; UIBranchContainer showUnregAllowedOption = UIBranchContainer.make(form, "showUnregAllowedOption:"); //$NON-NLS-1$ UIMessage.make(showUnregAllowedOption, "unregistered-allowed-desc", "evalsettings.unregistered.allowed.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showUnregAllowedOption, "unregistered-allowed-note", "evalsettings.unregistered.allowed.note"); //$NON-NLS-1$ //$NON-NLS-2$ UIBoundBoolean.make(showUnregAllowedOption, "unregisteredAllowed", "#{evaluationBean.eval.unregisteredAllowed}", null); //$NON-NLS-1$ //$NON-NLS-2$ } /* * (non-javadoc) Continued from the note above, that is show * "student-completion-settings-header" only if there are any student * completion settings to be displayed on the page. */ if (showStudentCompletionHeader) { UIBranchContainer showStudentCompletionDiv = UIBranchContainer.make(form, "showStudentCompletionDiv:"); //$NON-NLS-1$ UIMessage.make(showStudentCompletionDiv, "student-completion-settings-header", "evalsettings.student.completion.settings.header"); //$NON-NLS-1$ //$NON-NLS-2$ } /* * (non-javadoc) If the person is an admin (any kind), then only we need to * show these instructor opt in/out settings. */ if (externalLogic.isUserAdmin(externalLogic.getCurrentUserId())) { UIBranchContainer showInstUseFromAbove = UIBranchContainer.make(form, "showInstUseFromAbove:"); //$NON-NLS-1$ UIMessage.make(showInstUseFromAbove, "admin-settings-header", "evalsettings.admin.settings.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showInstUseFromAbove, "admin-settings-instructions", "evalsettings.admin.settings.instructions"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showInstUseFromAbove, "instructor-opt-desc", "evalsettings.instructor.opt.desc"); //$NON-NLS-1$ //$NON-NLS-2$ /* * (non-javadoc) If "EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE" is * set as configurable i.e. NULL in the database then show the instructor * opt select box. Else just show the value as label. */ String[] instructorOptLabels = { "evalsettings.instructors.label.opt.in", "evalsettings.instructors.label.opt.out", "evalsettings.instructors.label.required" }; if (settings.get(EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE) == null) { UIBranchContainer showInstUseFromAboveOptions = UIBranchContainer.make( showInstUseFromAbove, "showInstUseFromAboveOptions:"); //$NON-NLS-1$ UISelect.make(showInstUseFromAboveOptions, "instructorOpt", EvaluationConstant.INSTRUCTOR_OPT_VALUES, instructorOptLabels, "#{evaluationBean.eval.instructorOpt}", null).setMessageKeys(); //$NON-NLS-1$ } else { UIBranchContainer showInstUseFromAboveLabel = UIBranchContainer.make( showInstUseFromAbove, "showInstUseFromAboveLabel:"); //$NON-NLS-1$ String instUseFromAboveValue = (String) settings .get(EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE); int index = ArrayUtil.indexOf(EvaluationConstant.INSTRUCTOR_OPT_VALUES, instUseFromAboveValue); String instUseFromAboveLabel = instructorOptLabels[index]; /* * (non-javadoc) Displaying the label corresponding to * INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE value set as system property. */ UIMessage.make(showInstUseFromAboveLabel, "instUseFromAboveLabel", instUseFromAboveLabel); //$NON-NLS-1$ /* * (non-javadoc) Doing the binding of this * INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE value so that it can be saved in * the database */ form.parameters.add(new UIELBinding( "#{evaluationBean.eval.instructorOpt}", instUseFromAboveValue)); //$NON-NLS-1$ } } UIMessage.make(form, "eval-reminder-settings-header", "evalsettings.reminder.settings.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIInternalLink.make(form, "emailAvailable_link", UIMessage .make("evalsettings.available.mail.link"), new EmailViewParameters( PreviewEmailProducer.VIEW_ID, null, EvalConstants.EMAIL_TEMPLATE_AVAILABLE)); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-available-mail-desc", "evalsettings.available.mail.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "reminder-noresponders-header", "evalsettings.reminder.noresponders.header"); //$NON-NLS-1$ //$NON-NLS-2$ String[] reminderEmailDaysLabels = { "evalsettings.reminder.days.0", "evalsettings.reminder.days.1", "evalsettings.reminder.days.2", "evalsettings.reminder.days.3", "evalsettings.reminder.days.4", "evalsettings.reminder.days.5", "evalsettings.reminder.days.6", "evalsettings.reminder.days.7" }; // Reminder email select box UISelect.make(form, "reminderDays", EvaluationConstant.REMINDER_EMAIL_DAYS_VALUES, reminderEmailDaysLabels, "#{evaluationBean.eval.reminderDays}", null).setMessageKeys(); //$NON-NLS-1$ UIInternalLink.make(form, "emailReminder_link", UIMessage .make("evalsettings.reminder.mail.link"), new EmailViewParameters( PreviewEmailProducer.VIEW_ID, null, EvalConstants.EMAIL_TEMPLATE_REMINDER)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ UIMessage.make(form, "eval-reminder-mail-desc", "evalsettings.reminder.mail.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-from-email-header", "evalsettings.from.email.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput.make(form, "reminderFromEmail", "#{evaluationBean.eval.reminderFromEmail}", null); //$NON-NLS-1$ //$NON-NLS-2$ /* * (non-javadoc) if this evaluation is already saved, show "Save Settings" * button else this is the "Continue to Assign to Courses" button */ if (evaluationBean.eval.getId() == null) { UICommand.make(form, "continueAssigning", UIMessage .make("evalsettings.continue.assigning.link"), "#{evaluationBean.continueAssigningAction}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else { UICommand.make(form, "continueAssigning", UIMessage .make("evalsettings.save.settings.link"), "#{evaluationBean.saveSettingsAction}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } UIMessage.make(form, "cancel-button", "general.cancel.button"); } /* * (non-Javadoc) * * @see uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter#reportNavigationCases() */ public List reportNavigationCases() { List i = new ArrayList(); i.add(new NavigationCase(EvaluationStartProducer.VIEW_ID, new EvalViewParameters(EvaluationStartProducer.VIEW_ID, null))); i.add(new NavigationCase(ControlPanelProducer.VIEW_ID, new SimpleViewParameters(ControlPanelProducer.VIEW_ID))); i.add(new NavigationCase(EvaluationAssignProducer.VIEW_ID, new SimpleViewParameters(EvaluationAssignProducer.VIEW_ID))); return i; } /* * (non-Javadoc) This method is used to make the checkbox appear disabled * where ever needed. */ private void setDisabledAttribute(UIBoundBoolean checkbox) { checkbox.decorators = new DecoratorList(new UIDisabledDecorator()); } }
true
true
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { // Displaying the top link, page title, page description, and creating the // HTML form UIOutput.make(tofill, "eval-settings-title", "evalsettings.page.title"); //$NON-NLS-1$ //$NON-NLS-2$ UIInternalLink.make(tofill, "summary-toplink", "summary.page.title", //$NON-NLS-1$ //$NON-NLS-2$ new SimpleViewParameters(SummaryProducer.VIEW_ID)); UIForm form = UIForm.make(tofill, "evalSettingsForm"); //$NON-NLS-1$ UIMessage.make(form, "settings-desc-header", "evalsettings.settings.desc.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIOutput .make(form, "evaluationTitle", null, "#{evaluationBean.eval.title}"); //$NON-NLS-1$ //$NON-NLS-2$ Date today = new Date(); Calendar calendar = new GregorianCalendar(); calendar.setTime(today); UIMessage.make(form, "eval-dates-header", "evalsettings.dates.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-start-date-header", "evalsettings.start.date.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage .make(form, "eval-start-date-desc", "evalsettings.start.date.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput startDate = UIInput.make(form, "startDate:", "#{evaluationBean.startDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ if (evaluationBean.eval.getId() != null) { // queued evalution if (today.before(evaluationBean.eval.getStartDate())) { UIInput.make(form, "evalStatus", null, "queued"); //$NON-NLS-1$ //$NON-NLS-2$ } // started evaluation else { startDate.decorators = new DecoratorList(new UIDisabledDecorator()); UIInput.make(form, "evalStatus", null, "active"); //$NON-NLS-1$ //$NON-NLS-2$ } } else { UIInput.make(form, "evalStatus", null, "new"); //$NON-NLS-1$ //$NON-NLS-2$ } dateevolver.evolveDateInput(startDate, calendar.getTime()); calendar.add(Calendar.DATE, 1); // Show the "Stop date" text box only if it is set as yes in the System // settings if (((Boolean) settings.get(EvalSettings.EVAL_USE_STOP_DATE)) .booleanValue()) { UIBranchContainer showStopDate = UIBranchContainer.make(form, "showStopDate:"); //$NON-NLS-1$ UIMessage.make(showStopDate, "eval-stop-date-header", "evalsettings.stop.date.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput stopDate = UIInput.make(showStopDate, "stopDate:", "#{evaluationBean.stopDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(stopDate, calendar.getTime()); } calendar.add(Calendar.DATE, 1); UIMessage .make(form, "eval-due-date-header", "evalsettings.due.date.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput dueDate = UIInput.make(form, "dueDate:", "#{evaluationBean.dueDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(dueDate, calendar.getTime()); calendar.add(Calendar.DATE, 1); UIMessage.make(form, "eval-view-date-header", "evalsettings.view.date.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-view-date-desc", "evalsettings.view.date.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput viewDate = UIInput.make(form, "viewDate:", "#{evaluationBean.viewDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(viewDate, calendar.getTime()); UIMessage.make(form, "eval-results-viewable-header", "evalsettings.results.viewable.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-results-viewable-private-start", "evalsettings.results.viewable.private.start"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-results-viewable-private-middle", "evalsettings.results.viewable.private.middle"); //$NON-NLS-1$ //$NON-NLS-2$ UIOutput.make(form, "userInfo", externalLogic .getUserDisplayName(externalLogic.getCurrentUserId())); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "private-warning-desc", "evalsettings.private.warning.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIBoundBoolean.make(form, "resultsPrivate", "#{evaluationBean.eval.resultsPrivate}", null); //$NON-NLS-1$ //$NON-NLS-2$ /* * (non-Javadoc) Variable is used to decide whether to show the view date * textbox for student and instructor separately or not. */ boolean sameViewDateForAll = ((Boolean) settings .get(EvalSettings.EVAL_USE_SAME_VIEW_DATES)).booleanValue(); /* * (non-Javadoc) If "EvalSettings.STUDENT_VIEW_RESULTS" is set as * configurable i.e. NULL in the database OR is set as TRUE in database, * then show the checkbox. Else do not show the checkbox and just bind the * value to FALSE. */ Boolean tempValue = (Boolean) settings .get(EvalSettings.STUDENT_VIEW_RESULTS); if (tempValue == null || tempValue.booleanValue()) { UIBranchContainer showResultsToStudents = UIBranchContainer.make(form, "showResultsToStudents:"); //$NON-NLS-1$ UIMessage.make(showResultsToStudents, "eval-results-viewable-students", "evalsettings.results.viewable.students"); //$NON-NLS-1$ //$NON-NLS-2$ // If system setting was null implies normal checkbox. If it was TRUE then // a disabled selected checkbox if (tempValue == null) { UIBoundBoolean.make(showResultsToStudents, "studentViewResults", "#{evaluationBean.studentViewResults}", tempValue); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Display only (disabled) and selected check box UIBoundBoolean stuViewCheckbox = UIBoundBoolean.make( showResultsToStudents, "studentViewResults", tempValue); //$NON-NLS-1$ setDisabledAttribute(stuViewCheckbox); // As we have disabled the check box => RSF will not bind the value => // binding it explicitly. form.parameters.add(new UIELBinding( "#{evaluationBean.studentViewResults}", tempValue)); //$NON-NLS-1$ } // If same view date all then show a label else show a text box. if (sameViewDateForAll) { UIMessage.make(showResultsToStudents, "eval-results-stu-inst-date-label", "evalsettings.results.stu.inst.date.label"); //$NON-NLS-1$ //$NON-NLS-2$ } else { UIInput studentsDate = UIInput.make(showResultsToStudents, "studentsDate:", "#{evaluationBean.studentsDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(studentsDate, calendar.getTime()); } } else { form.parameters.add(new UIELBinding( "#{evaluationBean.studentViewResults}", Boolean.FALSE)); //$NON-NLS-1$ } /* * (non-javadoc) If "EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS" is set as * configurable i.e. NULL in the database OR is set as TRUE in database, * then show the checkbox. Else do not show the checkbox and just bind the * value to FALSE. */ tempValue = (Boolean) settings .get(EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS); if (tempValue == null || tempValue.booleanValue()) { UIBranchContainer showResultsToInst = UIBranchContainer.make(form, "showResultsToInst:"); //$NON-NLS-1$ UIMessage.make(showResultsToInst, "eval-results-viewable-instructors", "evalsettings.results.viewable.instructors"); //$NON-NLS-1$ //$NON-NLS-2$ // If system setting was null implies normal checkbox. If it was TRUE then // a disabled selected checkbox if (tempValue == null) { UIBoundBoolean.make(showResultsToInst, "instructorViewResults", "#{evaluationBean.instructorViewResults}", tempValue); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Display only (disabled) and selected check box UIBoundBoolean instViewCheckbox = UIBoundBoolean.make( showResultsToInst, "instructorViewResults", tempValue); //$NON-NLS-1$ setDisabledAttribute(instViewCheckbox); // As we have disabled the check box => RSF will not bind the value => // binding it explicitly. form.parameters.add(new UIELBinding( "#{evaluationBean.instructorViewResults}", tempValue)); //$NON-NLS-1$ } // If same view date all then show a label else show a text box. if (sameViewDateForAll) { UIBranchContainer showResultsToInstLabel = UIBranchContainer.make( showResultsToInst, "showResultsToInstLabel:"); //$NON-NLS-1$ UIMessage.make(showResultsToInstLabel, "eval-results-stu-inst-date-label", "evalsettings.results.stu.inst.date.label"); //$NON-NLS-1$ //$NON-NLS-2$ } else { UIBranchContainer showResultsToInstDate = UIBranchContainer.make( showResultsToInst, "showResultsToInstDate:"); //$NON-NLS-1$ UIInput instructorsDate = UIInput.make(showResultsToInstDate, "instructorsDate:", "#{evaluationBean.instructorsDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(instructorsDate, calendar.getTime()); } } else { form.parameters.add(new UIELBinding( "#{evaluationBean.instructorViewResults}", Boolean.FALSE)); //$NON-NLS-1$ } UIMessage.make(form, "eval-results-viewable-admin-note", "evalsettings.results.viewable.admin.note"); //$NON-NLS-1$ //$NON-NLS-2$ /* * (non-javadoc) If "EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED" is set * as configurable i.e. NULL in the database OR is set as TRUE in database, * then show the checkbox. Else do not show the checkbox and just bind the * value to FALSE. * * Note: The variable showStudentCompletionHeader is used to show * "student-completion-settings-header" It is true only if either of the * three "if's" below are evaluated to true. */ boolean showStudentCompletionHeader = false; tempValue = (Boolean) settings .get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED); if (tempValue == null || tempValue.booleanValue()) { showStudentCompletionHeader = true; UIBranchContainer showBlankQuestionAllowedToStut = UIBranchContainer .make(form, "showBlankQuestionAllowedToStut:"); //$NON-NLS-1$ UIMessage.make(showBlankQuestionAllowedToStut, "blank-responses-allowed-desc", "evalsettings.blank.responses.allowed.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showBlankQuestionAllowedToStut, "blank-responses-allowed-note", "evalsettings.blank.responses.allowed.note"); //$NON-NLS-1$ //$NON-NLS-2$ // If system setting was null implies normal checkbox. If it was TRUE then // a disabled selected checkbox if (tempValue == null) { UIBoundBoolean.make(showBlankQuestionAllowedToStut, "blankResponsesAllowed", "#{evaluationBean.eval.blankResponsesAllowed}", tempValue); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Display only (disabled) and selected check box UIBoundBoolean stuLeaveUnanswered = UIBoundBoolean.make( showBlankQuestionAllowedToStut, "blankResponsesAllowed", tempValue); //$NON-NLS-1$ setDisabledAttribute(stuLeaveUnanswered); // As we have disabled the check box => RSF will not bind the value => // binding it explicitly. form.parameters.add(new UIELBinding( "#{evaluationBean.eval.blankResponsesAllowed}", tempValue)); //$NON-NLS-1$ } } else { form.parameters.add(new UIELBinding( "#{evaluationBean.eval.blankResponsesAllowed}", Boolean.FALSE)); //$NON-NLS-1$ } /* * (non-javadoc) If "EvalSettings.STUDENT_MODIFY_RESPONSES" is set as * configurable i.e. NULL in the database OR is set as TRUE in database, * then show the checkbox. Else do not show the checkbox and just bind the * value to FALSE. */ tempValue = (Boolean) settings.get(EvalSettings.STUDENT_MODIFY_RESPONSES); if (tempValue == null || tempValue.booleanValue()) { showStudentCompletionHeader = true; UIBranchContainer showModifyResponsesAllowedToStu = UIBranchContainer .make(form, "showModifyResponsesAllowedToStu:"); //$NON-NLS-1$ UIMessage.make(showModifyResponsesAllowedToStu, "modify-responses-allowed-desc", "evalsettings.modify.responses.allowed.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showModifyResponsesAllowedToStu, "modify-responses-allowed-note", "evalsettings.modify.responses.allowed.note"); //$NON-NLS-1$ //$NON-NLS-2$ // If system setting was null implies normal checkbox. If it was TRUE then // a disabled selected checkbox if (tempValue == null) { UIBoundBoolean.make(showModifyResponsesAllowedToStu, "modifyResponsesAllowed", "#{evaluationBean.eval.modifyResponsesAllowed}", tempValue); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Display only (disabled) and selected check box UIBoundBoolean stuModifyResponses = UIBoundBoolean.make( showModifyResponsesAllowedToStu, "modifyResponsesAllowed", tempValue); //$NON-NLS-1$ setDisabledAttribute(stuModifyResponses); // As we have disabled the check box => RSF will not bind the value => // binding it explicitly. form.parameters.add(new UIELBinding( "#{evaluationBean.eval.modifyResponsesAllowed}", tempValue)); //$NON-NLS-1$ } } else { form.parameters.add(new UIELBinding( "#{evaluationBean.eval.modifyResponsesAllowed}", Boolean.FALSE)); //$NON-NLS-1$ } // This options are commented for some time. if (false) { showStudentCompletionHeader = true; UIBranchContainer showUnregAllowedOption = UIBranchContainer.make(form, "showUnregAllowedOption:"); //$NON-NLS-1$ UIMessage.make(showUnregAllowedOption, "unregistered-allowed-desc", "evalsettings.unregistered.allowed.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showUnregAllowedOption, "unregistered-allowed-note", "evalsettings.unregistered.allowed.note"); //$NON-NLS-1$ //$NON-NLS-2$ UIBoundBoolean.make(showUnregAllowedOption, "unregisteredAllowed", "#{evaluationBean.eval.unregisteredAllowed}", null); //$NON-NLS-1$ //$NON-NLS-2$ } /* * (non-javadoc) Continued from the note above, that is show * "student-completion-settings-header" only if there are any student * completion settings to be displayed on the page. */ if (showStudentCompletionHeader) { UIBranchContainer showStudentCompletionDiv = UIBranchContainer.make(form, "showStudentCompletionDiv:"); //$NON-NLS-1$ UIMessage.make(showStudentCompletionDiv, "student-completion-settings-header", "evalsettings.student.completion.settings.header"); //$NON-NLS-1$ //$NON-NLS-2$ } /* * (non-javadoc) If the person is an admin (any kind), then only we need to * show these instructor opt in/out settings. */ if (externalLogic.isUserAdmin(externalLogic.getCurrentUserId())) { UIBranchContainer showInstUseFromAbove = UIBranchContainer.make(form, "showInstUseFromAbove:"); //$NON-NLS-1$ UIMessage.make(showInstUseFromAbove, "admin-settings-header", "evalsettings.admin.settings.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showInstUseFromAbove, "admin-settings-instructions", "evalsettings.admin.settings.instructions"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showInstUseFromAbove, "instructor-opt-desc", "evalsettings.instructor.opt.desc"); //$NON-NLS-1$ //$NON-NLS-2$ /* * (non-javadoc) If "EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE" is * set as configurable i.e. NULL in the database then show the instructor * opt select box. Else just show the value as label. */ String[] instructorOptLabels = { "evalsettings.instructors.label.opt.in", "evalsettings.instructors.label.opt.out", "evalsettings.instructors.label.required" }; if (settings.get(EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE) == null) { UIBranchContainer showInstUseFromAboveOptions = UIBranchContainer.make( showInstUseFromAbove, "showInstUseFromAboveOptions:"); //$NON-NLS-1$ UISelect.make(showInstUseFromAboveOptions, "instructorOpt", EvaluationConstant.INSTRUCTOR_OPT_VALUES, instructorOptLabels, "#{evaluationBean.eval.instructorOpt}", null).setMessageKeys(); //$NON-NLS-1$ } else { UIBranchContainer showInstUseFromAboveLabel = UIBranchContainer.make( showInstUseFromAbove, "showInstUseFromAboveLabel:"); //$NON-NLS-1$ String instUseFromAboveValue = (String) settings .get(EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE); int index = ArrayUtil.indexOf(EvaluationConstant.INSTRUCTOR_OPT_VALUES, instUseFromAboveValue); String instUseFromAboveLabel = instructorOptLabels[index]; /* * (non-javadoc) Displaying the label corresponding to * INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE value set as system property. */ UIMessage.make(showInstUseFromAboveLabel, "instUseFromAboveLabel", instUseFromAboveLabel); //$NON-NLS-1$ /* * (non-javadoc) Doing the binding of this * INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE value so that it can be saved in * the database */ form.parameters.add(new UIELBinding( "#{evaluationBean.eval.instructorOpt}", instUseFromAboveValue)); //$NON-NLS-1$ } } UIMessage.make(form, "eval-reminder-settings-header", "evalsettings.reminder.settings.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIInternalLink.make(form, "emailAvailable_link", UIMessage .make("evalsettings.available.mail.link"), new EmailViewParameters( PreviewEmailProducer.VIEW_ID, null, EvalConstants.EMAIL_TEMPLATE_AVAILABLE)); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-available-mail-desc", "evalsettings.available.mail.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "reminder-noresponders-header", "evalsettings.reminder.noresponders.header"); //$NON-NLS-1$ //$NON-NLS-2$ String[] reminderEmailDaysLabels = { "evalsettings.reminder.days.0", "evalsettings.reminder.days.1", "evalsettings.reminder.days.2", "evalsettings.reminder.days.3", "evalsettings.reminder.days.4", "evalsettings.reminder.days.5", "evalsettings.reminder.days.6", "evalsettings.reminder.days.7" }; // Reminder email select box UISelect.make(form, "reminderDays", EvaluationConstant.REMINDER_EMAIL_DAYS_VALUES, reminderEmailDaysLabels, "#{evaluationBean.eval.reminderDays}", null).setMessageKeys(); //$NON-NLS-1$ UIInternalLink.make(form, "emailReminder_link", UIMessage .make("evalsettings.reminder.mail.link"), new EmailViewParameters( PreviewEmailProducer.VIEW_ID, null, EvalConstants.EMAIL_TEMPLATE_REMINDER)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ UIMessage.make(form, "eval-reminder-mail-desc", "evalsettings.reminder.mail.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-from-email-header", "evalsettings.from.email.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput.make(form, "reminderFromEmail", "#{evaluationBean.eval.reminderFromEmail}", null); //$NON-NLS-1$ //$NON-NLS-2$ /* * (non-javadoc) if this evaluation is already saved, show "Save Settings" * button else this is the "Continue to Assign to Courses" button */ if (evaluationBean.eval.getId() == null) { UICommand.make(form, "continueAssigning", UIMessage .make("evalsettings.continue.assigning.link"), "#{evaluationBean.continueAssigningAction}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else { UICommand.make(form, "continueAssigning", UIMessage .make("evalsettings.save.settings.link"), "#{evaluationBean.saveSettingsAction}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } UIMessage.make(form, "cancel-button", "general.cancel.button"); }
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { // Displaying the top link, page title, page description, and creating the // HTML form UIMessage.make(tofill, "eval-settings-title", "evalsettings.page.title"); //$NON-NLS-1$ //$NON-NLS-2$ UIInternalLink.make(tofill, "summary-toplink", UIMessage.make("summary.page.title"), //$NON-NLS-1$ //$NON-NLS-2$ new SimpleViewParameters(SummaryProducer.VIEW_ID)); UIForm form = UIForm.make(tofill, "evalSettingsForm"); //$NON-NLS-1$ UIMessage.make(form, "settings-desc-header", "evalsettings.settings.desc.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIOutput .make(form, "evaluationTitle", null, "#{evaluationBean.eval.title}"); //$NON-NLS-1$ //$NON-NLS-2$ Date today = new Date(); Calendar calendar = new GregorianCalendar(); calendar.setTime(today); UIMessage.make(form, "eval-dates-header", "evalsettings.dates.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-start-date-header", "evalsettings.start.date.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage .make(form, "eval-start-date-desc", "evalsettings.start.date.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput startDate = UIInput.make(form, "startDate:", "#{evaluationBean.startDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ if (evaluationBean.eval.getId() != null) { // queued evalution if (today.before(evaluationBean.eval.getStartDate())) { UIInput.make(form, "evalStatus", null, "queued"); //$NON-NLS-1$ //$NON-NLS-2$ } // started evaluation else { startDate.decorators = new DecoratorList(new UIDisabledDecorator()); UIInput.make(form, "evalStatus", null, "active"); //$NON-NLS-1$ //$NON-NLS-2$ } } else { UIInput.make(form, "evalStatus", null, "new"); //$NON-NLS-1$ //$NON-NLS-2$ } dateevolver.evolveDateInput(startDate, calendar.getTime()); calendar.add(Calendar.DATE, 1); // Show the "Stop date" text box only if it is set as yes in the System // settings if (((Boolean) settings.get(EvalSettings.EVAL_USE_STOP_DATE)) .booleanValue()) { UIBranchContainer showStopDate = UIBranchContainer.make(form, "showStopDate:"); //$NON-NLS-1$ UIMessage.make(showStopDate, "eval-stop-date-header", "evalsettings.stop.date.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput stopDate = UIInput.make(showStopDate, "stopDate:", "#{evaluationBean.stopDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(stopDate, calendar.getTime()); } calendar.add(Calendar.DATE, 1); UIMessage .make(form, "eval-due-date-header", "evalsettings.due.date.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput dueDate = UIInput.make(form, "dueDate:", "#{evaluationBean.dueDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(dueDate, calendar.getTime()); calendar.add(Calendar.DATE, 1); UIMessage.make(form, "eval-view-date-header", "evalsettings.view.date.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-view-date-desc", "evalsettings.view.date.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput viewDate = UIInput.make(form, "viewDate:", "#{evaluationBean.viewDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(viewDate, calendar.getTime()); UIMessage.make(form, "eval-results-viewable-header", "evalsettings.results.viewable.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-results-viewable-private-start", "evalsettings.results.viewable.private.start"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-results-viewable-private-middle", "evalsettings.results.viewable.private.middle"); //$NON-NLS-1$ //$NON-NLS-2$ UIOutput.make(form, "userInfo", externalLogic .getUserDisplayName(externalLogic.getCurrentUserId())); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "private-warning-desc", "evalsettings.private.warning.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIBoundBoolean.make(form, "resultsPrivate", "#{evaluationBean.eval.resultsPrivate}", null); //$NON-NLS-1$ //$NON-NLS-2$ /* * (non-Javadoc) Variable is used to decide whether to show the view date * textbox for student and instructor separately or not. */ boolean sameViewDateForAll = ((Boolean) settings .get(EvalSettings.EVAL_USE_SAME_VIEW_DATES)).booleanValue(); /* * (non-Javadoc) If "EvalSettings.STUDENT_VIEW_RESULTS" is set as * configurable i.e. NULL in the database OR is set as TRUE in database, * then show the checkbox. Else do not show the checkbox and just bind the * value to FALSE. */ Boolean tempValue = (Boolean) settings .get(EvalSettings.STUDENT_VIEW_RESULTS); if (tempValue == null || tempValue.booleanValue()) { UIBranchContainer showResultsToStudents = UIBranchContainer.make(form, "showResultsToStudents:"); //$NON-NLS-1$ UIMessage.make(showResultsToStudents, "eval-results-viewable-students", "evalsettings.results.viewable.students"); //$NON-NLS-1$ //$NON-NLS-2$ // If system setting was null implies normal checkbox. If it was TRUE then // a disabled selected checkbox if (tempValue == null) { UIBoundBoolean.make(showResultsToStudents, "studentViewResults", "#{evaluationBean.studentViewResults}", tempValue); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Display only (disabled) and selected check box UIBoundBoolean stuViewCheckbox = UIBoundBoolean.make( showResultsToStudents, "studentViewResults", tempValue); //$NON-NLS-1$ setDisabledAttribute(stuViewCheckbox); // As we have disabled the check box => RSF will not bind the value => // binding it explicitly. form.parameters.add(new UIELBinding( "#{evaluationBean.studentViewResults}", tempValue)); //$NON-NLS-1$ } // If same view date all then show a label else show a text box. if (sameViewDateForAll) { UIMessage.make(showResultsToStudents, "eval-results-stu-inst-date-label", "evalsettings.results.stu.inst.date.label"); //$NON-NLS-1$ //$NON-NLS-2$ } else { UIInput studentsDate = UIInput.make(showResultsToStudents, "studentsDate:", "#{evaluationBean.studentsDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(studentsDate, calendar.getTime()); } } else { form.parameters.add(new UIELBinding( "#{evaluationBean.studentViewResults}", Boolean.FALSE)); //$NON-NLS-1$ } /* * (non-javadoc) If "EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS" is set as * configurable i.e. NULL in the database OR is set as TRUE in database, * then show the checkbox. Else do not show the checkbox and just bind the * value to FALSE. */ tempValue = (Boolean) settings .get(EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS); if (tempValue == null || tempValue.booleanValue()) { UIBranchContainer showResultsToInst = UIBranchContainer.make(form, "showResultsToInst:"); //$NON-NLS-1$ UIMessage.make(showResultsToInst, "eval-results-viewable-instructors", "evalsettings.results.viewable.instructors"); //$NON-NLS-1$ //$NON-NLS-2$ // If system setting was null implies normal checkbox. If it was TRUE then // a disabled selected checkbox if (tempValue == null) { UIBoundBoolean.make(showResultsToInst, "instructorViewResults", "#{evaluationBean.instructorViewResults}", tempValue); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Display only (disabled) and selected check box UIBoundBoolean instViewCheckbox = UIBoundBoolean.make( showResultsToInst, "instructorViewResults", tempValue); //$NON-NLS-1$ setDisabledAttribute(instViewCheckbox); // As we have disabled the check box => RSF will not bind the value => // binding it explicitly. form.parameters.add(new UIELBinding( "#{evaluationBean.instructorViewResults}", tempValue)); //$NON-NLS-1$ } // If same view date all then show a label else show a text box. if (sameViewDateForAll) { UIBranchContainer showResultsToInstLabel = UIBranchContainer.make( showResultsToInst, "showResultsToInstLabel:"); //$NON-NLS-1$ UIMessage.make(showResultsToInstLabel, "eval-results-stu-inst-date-label", "evalsettings.results.stu.inst.date.label"); //$NON-NLS-1$ //$NON-NLS-2$ } else { UIBranchContainer showResultsToInstDate = UIBranchContainer.make( showResultsToInst, "showResultsToInstDate:"); //$NON-NLS-1$ UIInput instructorsDate = UIInput.make(showResultsToInstDate, "instructorsDate:", "#{evaluationBean.instructorsDate}", null); //$NON-NLS-1$ //$NON-NLS-2$ dateevolver.evolveDateInput(instructorsDate, calendar.getTime()); } } else { form.parameters.add(new UIELBinding( "#{evaluationBean.instructorViewResults}", Boolean.FALSE)); //$NON-NLS-1$ } UIMessage.make(form, "eval-results-viewable-admin-note", "evalsettings.results.viewable.admin.note"); //$NON-NLS-1$ //$NON-NLS-2$ /* * (non-javadoc) If "EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED" is set * as configurable i.e. NULL in the database OR is set as TRUE in database, * then show the checkbox. Else do not show the checkbox and just bind the * value to FALSE. * * Note: The variable showStudentCompletionHeader is used to show * "student-completion-settings-header" It is true only if either of the * three "if's" below are evaluated to true. */ boolean showStudentCompletionHeader = false; tempValue = (Boolean) settings .get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED); if (tempValue == null || tempValue.booleanValue()) { showStudentCompletionHeader = true; UIBranchContainer showBlankQuestionAllowedToStut = UIBranchContainer .make(form, "showBlankQuestionAllowedToStut:"); //$NON-NLS-1$ UIMessage.make(showBlankQuestionAllowedToStut, "blank-responses-allowed-desc", "evalsettings.blank.responses.allowed.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showBlankQuestionAllowedToStut, "blank-responses-allowed-note", "evalsettings.blank.responses.allowed.note"); //$NON-NLS-1$ //$NON-NLS-2$ // If system setting was null implies normal checkbox. If it was TRUE then // a disabled selected checkbox if (tempValue == null) { UIBoundBoolean.make(showBlankQuestionAllowedToStut, "blankResponsesAllowed", "#{evaluationBean.eval.blankResponsesAllowed}", tempValue); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Display only (disabled) and selected check box UIBoundBoolean stuLeaveUnanswered = UIBoundBoolean.make( showBlankQuestionAllowedToStut, "blankResponsesAllowed", tempValue); //$NON-NLS-1$ setDisabledAttribute(stuLeaveUnanswered); // As we have disabled the check box => RSF will not bind the value => // binding it explicitly. form.parameters.add(new UIELBinding( "#{evaluationBean.eval.blankResponsesAllowed}", tempValue)); //$NON-NLS-1$ } } else { form.parameters.add(new UIELBinding( "#{evaluationBean.eval.blankResponsesAllowed}", Boolean.FALSE)); //$NON-NLS-1$ } /* * (non-javadoc) If "EvalSettings.STUDENT_MODIFY_RESPONSES" is set as * configurable i.e. NULL in the database OR is set as TRUE in database, * then show the checkbox. Else do not show the checkbox and just bind the * value to FALSE. */ tempValue = (Boolean) settings.get(EvalSettings.STUDENT_MODIFY_RESPONSES); if (tempValue == null || tempValue.booleanValue()) { showStudentCompletionHeader = true; UIBranchContainer showModifyResponsesAllowedToStu = UIBranchContainer .make(form, "showModifyResponsesAllowedToStu:"); //$NON-NLS-1$ UIMessage.make(showModifyResponsesAllowedToStu, "modify-responses-allowed-desc", "evalsettings.modify.responses.allowed.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showModifyResponsesAllowedToStu, "modify-responses-allowed-note", "evalsettings.modify.responses.allowed.note"); //$NON-NLS-1$ //$NON-NLS-2$ // If system setting was null implies normal checkbox. If it was TRUE then // a disabled selected checkbox if (tempValue == null) { UIBoundBoolean.make(showModifyResponsesAllowedToStu, "modifyResponsesAllowed", "#{evaluationBean.eval.modifyResponsesAllowed}", tempValue); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Display only (disabled) and selected check box UIBoundBoolean stuModifyResponses = UIBoundBoolean.make( showModifyResponsesAllowedToStu, "modifyResponsesAllowed", tempValue); //$NON-NLS-1$ setDisabledAttribute(stuModifyResponses); // As we have disabled the check box => RSF will not bind the value => // binding it explicitly. form.parameters.add(new UIELBinding( "#{evaluationBean.eval.modifyResponsesAllowed}", tempValue)); //$NON-NLS-1$ } } else { form.parameters.add(new UIELBinding( "#{evaluationBean.eval.modifyResponsesAllowed}", Boolean.FALSE)); //$NON-NLS-1$ } // This options are commented for some time. if (false) { showStudentCompletionHeader = true; UIBranchContainer showUnregAllowedOption = UIBranchContainer.make(form, "showUnregAllowedOption:"); //$NON-NLS-1$ UIMessage.make(showUnregAllowedOption, "unregistered-allowed-desc", "evalsettings.unregistered.allowed.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showUnregAllowedOption, "unregistered-allowed-note", "evalsettings.unregistered.allowed.note"); //$NON-NLS-1$ //$NON-NLS-2$ UIBoundBoolean.make(showUnregAllowedOption, "unregisteredAllowed", "#{evaluationBean.eval.unregisteredAllowed}", null); //$NON-NLS-1$ //$NON-NLS-2$ } /* * (non-javadoc) Continued from the note above, that is show * "student-completion-settings-header" only if there are any student * completion settings to be displayed on the page. */ if (showStudentCompletionHeader) { UIBranchContainer showStudentCompletionDiv = UIBranchContainer.make(form, "showStudentCompletionDiv:"); //$NON-NLS-1$ UIMessage.make(showStudentCompletionDiv, "student-completion-settings-header", "evalsettings.student.completion.settings.header"); //$NON-NLS-1$ //$NON-NLS-2$ } /* * (non-javadoc) If the person is an admin (any kind), then only we need to * show these instructor opt in/out settings. */ if (externalLogic.isUserAdmin(externalLogic.getCurrentUserId())) { UIBranchContainer showInstUseFromAbove = UIBranchContainer.make(form, "showInstUseFromAbove:"); //$NON-NLS-1$ UIMessage.make(showInstUseFromAbove, "admin-settings-header", "evalsettings.admin.settings.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showInstUseFromAbove, "admin-settings-instructions", "evalsettings.admin.settings.instructions"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(showInstUseFromAbove, "instructor-opt-desc", "evalsettings.instructor.opt.desc"); //$NON-NLS-1$ //$NON-NLS-2$ /* * (non-javadoc) If "EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE" is * set as configurable i.e. NULL in the database then show the instructor * opt select box. Else just show the value as label. */ String[] instructorOptLabels = { "evalsettings.instructors.label.opt.in", "evalsettings.instructors.label.opt.out", "evalsettings.instructors.label.required" }; if (settings.get(EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE) == null) { UIBranchContainer showInstUseFromAboveOptions = UIBranchContainer.make( showInstUseFromAbove, "showInstUseFromAboveOptions:"); //$NON-NLS-1$ UISelect.make(showInstUseFromAboveOptions, "instructorOpt", EvaluationConstant.INSTRUCTOR_OPT_VALUES, instructorOptLabels, "#{evaluationBean.eval.instructorOpt}", null).setMessageKeys(); //$NON-NLS-1$ } else { UIBranchContainer showInstUseFromAboveLabel = UIBranchContainer.make( showInstUseFromAbove, "showInstUseFromAboveLabel:"); //$NON-NLS-1$ String instUseFromAboveValue = (String) settings .get(EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE); int index = ArrayUtil.indexOf(EvaluationConstant.INSTRUCTOR_OPT_VALUES, instUseFromAboveValue); String instUseFromAboveLabel = instructorOptLabels[index]; /* * (non-javadoc) Displaying the label corresponding to * INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE value set as system property. */ UIMessage.make(showInstUseFromAboveLabel, "instUseFromAboveLabel", instUseFromAboveLabel); //$NON-NLS-1$ /* * (non-javadoc) Doing the binding of this * INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE value so that it can be saved in * the database */ form.parameters.add(new UIELBinding( "#{evaluationBean.eval.instructorOpt}", instUseFromAboveValue)); //$NON-NLS-1$ } } UIMessage.make(form, "eval-reminder-settings-header", "evalsettings.reminder.settings.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIInternalLink.make(form, "emailAvailable_link", UIMessage .make("evalsettings.available.mail.link"), new EmailViewParameters( PreviewEmailProducer.VIEW_ID, null, EvalConstants.EMAIL_TEMPLATE_AVAILABLE)); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-available-mail-desc", "evalsettings.available.mail.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "reminder-noresponders-header", "evalsettings.reminder.noresponders.header"); //$NON-NLS-1$ //$NON-NLS-2$ String[] reminderEmailDaysLabels = { "evalsettings.reminder.days.0", "evalsettings.reminder.days.1", "evalsettings.reminder.days.2", "evalsettings.reminder.days.3", "evalsettings.reminder.days.4", "evalsettings.reminder.days.5", "evalsettings.reminder.days.6", "evalsettings.reminder.days.7" }; // Reminder email select box UISelect.make(form, "reminderDays", EvaluationConstant.REMINDER_EMAIL_DAYS_VALUES, reminderEmailDaysLabels, "#{evaluationBean.eval.reminderDays}", null).setMessageKeys(); //$NON-NLS-1$ UIInternalLink.make(form, "emailReminder_link", UIMessage .make("evalsettings.reminder.mail.link"), new EmailViewParameters( PreviewEmailProducer.VIEW_ID, null, EvalConstants.EMAIL_TEMPLATE_REMINDER)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ UIMessage.make(form, "eval-reminder-mail-desc", "evalsettings.reminder.mail.desc"); //$NON-NLS-1$ //$NON-NLS-2$ UIMessage.make(form, "eval-from-email-header", "evalsettings.from.email.header"); //$NON-NLS-1$ //$NON-NLS-2$ UIInput.make(form, "reminderFromEmail", "#{evaluationBean.eval.reminderFromEmail}", null); //$NON-NLS-1$ //$NON-NLS-2$ /* * (non-javadoc) if this evaluation is already saved, show "Save Settings" * button else this is the "Continue to Assign to Courses" button */ if (evaluationBean.eval.getId() == null) { UICommand.make(form, "continueAssigning", UIMessage .make("evalsettings.continue.assigning.link"), "#{evaluationBean.continueAssigningAction}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else { UICommand.make(form, "continueAssigning", UIMessage .make("evalsettings.save.settings.link"), "#{evaluationBean.saveSettingsAction}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } UIMessage.make(form, "cancel-button", "general.cancel.button"); }
diff --git a/src/main/java/nl/mineleni/cbsviewer/servlet/gazetteer/lusclient/OpenLSClientUtil.java b/src/main/java/nl/mineleni/cbsviewer/servlet/gazetteer/lusclient/OpenLSClientUtil.java index 663067e40..6c8479641 100644 --- a/src/main/java/nl/mineleni/cbsviewer/servlet/gazetteer/lusclient/OpenLSClientUtil.java +++ b/src/main/java/nl/mineleni/cbsviewer/servlet/gazetteer/lusclient/OpenLSClientUtil.java @@ -1,112 +1,122 @@ package nl.mineleni.cbsviewer.servlet.gazetteer.lusclient; import java.util.ArrayList; import java.util.List; import nl.mineleni.openls.databinding.openls.Address; import nl.mineleni.openls.databinding.openls.GeocodeResponse; import nl.mineleni.openls.databinding.openls.GeocodeResponseList; import nl.mineleni.openls.databinding.openls.GeocodedAddress; /** * Utility klasse OpenLSClientUtil. * * @author mprins */ public final class OpenLSClientUtil { /** De constante PLACE_TYPE_COUNTRYSUBDIVISION. {@value} */ public final static String PLACE_TYPE_COUNTRYSUBDIVISION = "CountrySubdivision"; /** De constante PLACE_TYPE_MUNICIPALITY. {@value} */ public static final String PLACE_TYPE_MUNICIPALITY = "Municipality"; /** De constante PLACE_TYPE_MUNICIPALITYSUBDIVISION. {@value} */ public static final String PLACE_TYPE_MUNICIPALITYSUBDIVISION = "MunicipalitySubdivision"; /** * private constructor voor deze utility klasse. */ private OpenLSClientUtil() { /* private constructor voor deze utility klasse. */ } /** * Gets the geocoded address list. * * @param gcr * the gcr * @return the geocoded address list */ public static List<GeocodedAddress> getGeocodedAddressList( final GeocodeResponse gcr) { final List<GeocodedAddress> addressList = new ArrayList<GeocodedAddress>(); for (int i = 0; i < gcr.getGeocodeResponseListSize(); i++) { final GeocodeResponseList gcrl = gcr.getGeocodeResponseListAt(i); for (int j = 0; j < gcrl.getGeocodedAddressSize(); j++) { final GeocodedAddress gca = gcrl.getGeocodedAddressAt(j); addressList.add(gca); } } return addressList; } /** * Gets the open ls client address list. * * @param gcr * the gcr * @return the open ls client address list */ public static List<OpenLSClientAddress> getOpenLSClientAddressList( final GeocodeResponse gcr) { final List<OpenLSClientAddress> addressList = new ArrayList<OpenLSClientAddress>(); final List<GeocodedAddress> gcal = getGeocodedAddressList(gcr); for (int i = 0; i < gcal.size(); i++) { final GeocodedAddress gca = gcal.get(i); final OpenLSClientAddress addr = new OpenLSClientAddress(); if (!gca.hasPoint() || (gca.getPoint().getPosSize() == 0)) { continue; } - addr.setxCoord((gca.getPoint().getPosAt(0).getX()).toString()); - addr.setyCoord((gca.getPoint().getPosAt(0).getY()).toString()); + if (gca.getPoint().getSrsName().equalsIgnoreCase("EPSG:28992")) { + // afronden naar meters in het geval van Rijksdriekhoek + // WORKAROUND voor bug in PDOK gazetteer service die belachelijk + // hoge nauwkeurigheid hanteerd voor centroiden + addr.setxCoord((gca.getPoint().getPosAt(0).getX()).intValue() + + ""); + addr.setyCoord((gca.getPoint().getPosAt(0).getY()).intValue() + + ""); + } else { + addr.setxCoord((gca.getPoint().getPosAt(0).getX()).toString()); + addr.setyCoord((gca.getPoint().getPosAt(0).getY()).toString()); + } if (gca.getAddress() != null) { final Address adr = gca.getAddress(); if (adr.hasStreetAddress() && adr.getStreetAddress().hasStreet()) { addr.setStreetName(adr.getStreetAddress().getStreet() .getStreet()); } if (adr.hasStreetAddress() && adr.getStreetAddress().hasBuilding() && adr.getStreetAddress().getBuilding().hasNumber()) { addr.setStreetNumber(adr.getStreetAddress().getBuilding() .getNumber()); } if (adr.hasPostalCode() && adr.getPostalCode().hasPostalCode()) { addr.setPostalCode(adr.getPostalCode().getPostalCode()); } if (adr.getPlaceByType(PLACE_TYPE_COUNTRYSUBDIVISION) != null) { addr.setCountrySubdivision(adr .getPlaceByType(PLACE_TYPE_COUNTRYSUBDIVISION)); } if (adr.getPlaceByType(PLACE_TYPE_MUNICIPALITY) != null) { addr.setMunicipality(adr .getPlaceByType(PLACE_TYPE_MUNICIPALITY)); } if (adr.getPlaceByType(PLACE_TYPE_MUNICIPALITYSUBDIVISION) != null) { addr.setMunicipalitySubdivision(adr .getPlaceByType(PLACE_TYPE_MUNICIPALITYSUBDIVISION)); } } if (addr.isValidClientAddress()) { addressList.add(addr); } } return addressList; } }
true
true
public static List<OpenLSClientAddress> getOpenLSClientAddressList( final GeocodeResponse gcr) { final List<OpenLSClientAddress> addressList = new ArrayList<OpenLSClientAddress>(); final List<GeocodedAddress> gcal = getGeocodedAddressList(gcr); for (int i = 0; i < gcal.size(); i++) { final GeocodedAddress gca = gcal.get(i); final OpenLSClientAddress addr = new OpenLSClientAddress(); if (!gca.hasPoint() || (gca.getPoint().getPosSize() == 0)) { continue; } addr.setxCoord((gca.getPoint().getPosAt(0).getX()).toString()); addr.setyCoord((gca.getPoint().getPosAt(0).getY()).toString()); if (gca.getAddress() != null) { final Address adr = gca.getAddress(); if (adr.hasStreetAddress() && adr.getStreetAddress().hasStreet()) { addr.setStreetName(adr.getStreetAddress().getStreet() .getStreet()); } if (adr.hasStreetAddress() && adr.getStreetAddress().hasBuilding() && adr.getStreetAddress().getBuilding().hasNumber()) { addr.setStreetNumber(adr.getStreetAddress().getBuilding() .getNumber()); } if (adr.hasPostalCode() && adr.getPostalCode().hasPostalCode()) { addr.setPostalCode(adr.getPostalCode().getPostalCode()); } if (adr.getPlaceByType(PLACE_TYPE_COUNTRYSUBDIVISION) != null) { addr.setCountrySubdivision(adr .getPlaceByType(PLACE_TYPE_COUNTRYSUBDIVISION)); } if (adr.getPlaceByType(PLACE_TYPE_MUNICIPALITY) != null) { addr.setMunicipality(adr .getPlaceByType(PLACE_TYPE_MUNICIPALITY)); } if (adr.getPlaceByType(PLACE_TYPE_MUNICIPALITYSUBDIVISION) != null) { addr.setMunicipalitySubdivision(adr .getPlaceByType(PLACE_TYPE_MUNICIPALITYSUBDIVISION)); } } if (addr.isValidClientAddress()) { addressList.add(addr); } } return addressList; }
public static List<OpenLSClientAddress> getOpenLSClientAddressList( final GeocodeResponse gcr) { final List<OpenLSClientAddress> addressList = new ArrayList<OpenLSClientAddress>(); final List<GeocodedAddress> gcal = getGeocodedAddressList(gcr); for (int i = 0; i < gcal.size(); i++) { final GeocodedAddress gca = gcal.get(i); final OpenLSClientAddress addr = new OpenLSClientAddress(); if (!gca.hasPoint() || (gca.getPoint().getPosSize() == 0)) { continue; } if (gca.getPoint().getSrsName().equalsIgnoreCase("EPSG:28992")) { // afronden naar meters in het geval van Rijksdriekhoek // WORKAROUND voor bug in PDOK gazetteer service die belachelijk // hoge nauwkeurigheid hanteerd voor centroiden addr.setxCoord((gca.getPoint().getPosAt(0).getX()).intValue() + ""); addr.setyCoord((gca.getPoint().getPosAt(0).getY()).intValue() + ""); } else { addr.setxCoord((gca.getPoint().getPosAt(0).getX()).toString()); addr.setyCoord((gca.getPoint().getPosAt(0).getY()).toString()); } if (gca.getAddress() != null) { final Address adr = gca.getAddress(); if (adr.hasStreetAddress() && adr.getStreetAddress().hasStreet()) { addr.setStreetName(adr.getStreetAddress().getStreet() .getStreet()); } if (adr.hasStreetAddress() && adr.getStreetAddress().hasBuilding() && adr.getStreetAddress().getBuilding().hasNumber()) { addr.setStreetNumber(adr.getStreetAddress().getBuilding() .getNumber()); } if (adr.hasPostalCode() && adr.getPostalCode().hasPostalCode()) { addr.setPostalCode(adr.getPostalCode().getPostalCode()); } if (adr.getPlaceByType(PLACE_TYPE_COUNTRYSUBDIVISION) != null) { addr.setCountrySubdivision(adr .getPlaceByType(PLACE_TYPE_COUNTRYSUBDIVISION)); } if (adr.getPlaceByType(PLACE_TYPE_MUNICIPALITY) != null) { addr.setMunicipality(adr .getPlaceByType(PLACE_TYPE_MUNICIPALITY)); } if (adr.getPlaceByType(PLACE_TYPE_MUNICIPALITYSUBDIVISION) != null) { addr.setMunicipalitySubdivision(adr .getPlaceByType(PLACE_TYPE_MUNICIPALITYSUBDIVISION)); } } if (addr.isValidClientAddress()) { addressList.add(addr); } } return addressList; }
diff --git a/wallet/src/de/schildbach/wallet/util/WalletUtils.java b/wallet/src/de/schildbach/wallet/util/WalletUtils.java index 952076e..35607ef 100644 --- a/wallet/src/de/schildbach/wallet/util/WalletUtils.java +++ b/wallet/src/de/schildbach/wallet/util/WalletUtils.java @@ -1,318 +1,318 @@ /* * Copyright 2011-2013 the original author or authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.schildbach.wallet.util; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import java.io.Writer; import java.math.BigInteger; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Typeface; import android.text.Editable; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.RelativeSizeSpan; import android.text.style.StyleSpan; import android.text.style.TypefaceSpan; import com.google.bitcoin.core.Address; import com.google.bitcoin.core.AddressFormatException; import com.google.bitcoin.core.DumpedPrivateKey; import com.google.bitcoin.core.ECKey; import com.google.bitcoin.core.ScriptException; import com.google.bitcoin.core.Transaction; import com.google.bitcoin.core.TransactionInput; import com.google.bitcoin.core.TransactionOutput; import com.google.bitcoin.core.Utils; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import de.schildbach.wallet.Constants; /** * @author Andreas Schildbach */ public class WalletUtils { public final static QRCodeWriter QR_CODE_WRITER = new QRCodeWriter(); public static Bitmap getQRCodeBitmap(final String url, final int size) { try { final Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); hints.put(EncodeHintType.MARGIN, 0); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); final BitMatrix result = QR_CODE_WRITER.encode(url, BarcodeFormat.QR_CODE, size, size, hints); final int width = result.getWidth(); final int height = result.getHeight(); final int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { final int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT; } } final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } catch (final WriterException x) { x.printStackTrace(); return null; } } public static Editable formatAddress(final Address address, final int groupSize, final int lineSize) { return formatAddress(address.toString(), groupSize, lineSize); } public static Editable formatAddress(final String prefix, final Address address, final int groupSize, final int lineSize) { return formatAddress(prefix, address.toString(), groupSize, lineSize); } public static Editable formatAddress(final String address, final int groupSize, final int lineSize) { return formatAddress(null, address, groupSize, lineSize); } public static Editable formatAddress(final String prefix, final String address, final int groupSize, final int lineSize) { final SpannableStringBuilder builder = prefix != null ? new SpannableStringBuilder(prefix) : new SpannableStringBuilder(); final int len = address.length(); for (int i = 0; i < len; i += groupSize) { final int end = i + groupSize; final String part = address.substring(i, end < len ? end : len); builder.append(part); builder.setSpan(new TypefaceSpan("monospace"), builder.length() - part.length(), builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); if (end < len) { final boolean endOfLine = lineSize > 0 && end % lineSize == 0; builder.append(endOfLine ? '\n' : Constants.CHAR_THIN_SPACE); } } return builder; } public static String formatValue(final BigInteger value, final int precision) { return formatValue(value, "", "-", precision); } public static String formatValue(final BigInteger value, final String plusSign, final String minusSign, final int precision) { final boolean negative = value.compareTo(BigInteger.ZERO) < 0; final BigInteger absValue = value.abs(); final String sign = negative ? minusSign : plusSign; final int coins = absValue.divide(Utils.COIN).intValue(); final int cents = absValue.remainder(Utils.COIN).intValue(); if (cents % 1000000 == 0 || precision <= 2) return String.format(Locale.US, "%s%d.%02d", sign, coins, cents / 1000000 + cents % 1000000 / 500000); else if (cents % 10000 == 0 || precision <= 4) return String.format(Locale.US, "%s%d.%04d", sign, coins, cents / 10000 + cents % 10000 / 5000); else if (precision <= 6) return String.format(Locale.US, "%s%d.%06d", sign, coins, cents / 100 + cents % 100 / 50); else return String.format(Locale.US, "%s%d.%08d", sign, coins, cents); } private static final Pattern P_SIGNIFICANT = Pattern.compile("^([-+]" + Constants.CHAR_THIN_SPACE + ")?\\d*(\\.\\d{0,2})?"); private static Object SIGNIFICANT_SPAN = new StyleSpan(Typeface.BOLD); private static Object UNSIGNIFICANT_SPAN = new RelativeSizeSpan(0.85f); public static void formatSignificant(final Editable s, final boolean smallerInsignificant) { s.removeSpan(SIGNIFICANT_SPAN); s.removeSpan(UNSIGNIFICANT_SPAN); final Matcher m = P_SIGNIFICANT.matcher(s); if (m.find()) { final int pivot = m.group().length(); s.setSpan(SIGNIFICANT_SPAN, 0, pivot, 0); if (s.length() > pivot && smallerInsignificant) s.setSpan(UNSIGNIFICANT_SPAN, pivot, s.length(), 0); } } public static BigInteger localValue(final BigInteger btcValue, final BigInteger rate) { return btcValue.multiply(rate).divide(Utils.COIN); } public static BigInteger btcValue(final BigInteger localValue, final BigInteger rate) { return localValue.multiply(Utils.COIN).divide(rate); } public static Address getFromAddress(final Transaction tx) { try { for (final TransactionInput input : tx.getInputs()) { return input.getFromAddress(); } throw new IllegalStateException(); } catch (final ScriptException x) { // this will happen on inputs connected to coinbase transactions return null; } } public static Address getToAddress(final Transaction tx) { try { for (final TransactionOutput output : tx.getOutputs()) { return output.getScriptPubKey().getToAddress(); } throw new IllegalStateException(); } catch (final ScriptException x) { return null; } } public static void writeKeys(final Writer out, final List<ECKey> keys) throws IOException { final DateFormat format = Iso8601Format.newDateTimeFormatT(); out.write("# KEEP YOUR PRIVATE KEYS SAFE! Anyone who can read this can spend your Bitcoins.\n"); for (final ECKey key : keys) { out.write(key.getPrivateKeyEncoded(Constants.NETWORK_PARAMETERS).toString()); if (key.getCreationTimeSeconds() != 0) { out.write(' '); out.write(format.format(new Date(key.getCreationTimeSeconds() * 1000))); } out.write('\n'); } } public static List<ECKey> readKeys(final BufferedReader in) throws IOException { try { final DateFormat format = Iso8601Format.newDateTimeFormatT(); final List<ECKey> keys = new LinkedList<ECKey>(); while (true) { final String line = in.readLine(); if (line == null) break; // eof - if (line.length() == 0 || line.charAt(0) == '#') + if (line.trim().length() == 0 || line.charAt(0) == '#') continue; // skip comment final String[] parts = line.split(" "); final ECKey key = new DumpedPrivateKey(Constants.NETWORK_PARAMETERS, parts[0]).getKey(); key.setCreationTimeSeconds(parts.length >= 2 ? format.parse(parts[1]).getTime() / 1000 : 0); keys.add(key); } return keys; } catch (final AddressFormatException x) { throw new IOException("cannot read keys: " + x); } catch (final ParseException x) { throw new IOException("cannot read keys: " + x); } } public static final FileFilter KEYS_FILE_FILTER = new FileFilter() { public boolean accept(final File file) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); WalletUtils.readKeys(reader); return true; } catch (final IOException x) { return false; } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { x.printStackTrace(); } } } } }; }
true
true
public static List<ECKey> readKeys(final BufferedReader in) throws IOException { try { final DateFormat format = Iso8601Format.newDateTimeFormatT(); final List<ECKey> keys = new LinkedList<ECKey>(); while (true) { final String line = in.readLine(); if (line == null) break; // eof if (line.length() == 0 || line.charAt(0) == '#') continue; // skip comment final String[] parts = line.split(" "); final ECKey key = new DumpedPrivateKey(Constants.NETWORK_PARAMETERS, parts[0]).getKey(); key.setCreationTimeSeconds(parts.length >= 2 ? format.parse(parts[1]).getTime() / 1000 : 0); keys.add(key); } return keys; } catch (final AddressFormatException x) { throw new IOException("cannot read keys: " + x); } catch (final ParseException x) { throw new IOException("cannot read keys: " + x); } }
public static List<ECKey> readKeys(final BufferedReader in) throws IOException { try { final DateFormat format = Iso8601Format.newDateTimeFormatT(); final List<ECKey> keys = new LinkedList<ECKey>(); while (true) { final String line = in.readLine(); if (line == null) break; // eof if (line.trim().length() == 0 || line.charAt(0) == '#') continue; // skip comment final String[] parts = line.split(" "); final ECKey key = new DumpedPrivateKey(Constants.NETWORK_PARAMETERS, parts[0]).getKey(); key.setCreationTimeSeconds(parts.length >= 2 ? format.parse(parts[1]).getTime() / 1000 : 0); keys.add(key); } return keys; } catch (final AddressFormatException x) { throw new IOException("cannot read keys: " + x); } catch (final ParseException x) { throw new IOException("cannot read keys: " + x); } }
diff --git a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/HRMController.java b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/HRMController.java index d261eae3..d8da6c17 100644 --- a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/HRMController.java +++ b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/HRMController.java @@ -1,4028 +1,4030 @@ /******************************************************************************* * Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management * Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. ******************************************************************************/ package de.tuilmenau.ics.fog.routing.hierarchical; import java.net.UnknownHostException; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.LinkedList; import java.util.List; import java.util.Observer; import de.tuilmenau.ics.fog.FoGEntity; import de.tuilmenau.ics.fog.IEvent; import de.tuilmenau.ics.fog.application.Application; import de.tuilmenau.ics.fog.application.util.ServerCallback; import de.tuilmenau.ics.fog.application.util.Service; import de.tuilmenau.ics.fog.eclipse.GraphViewer; import de.tuilmenau.ics.fog.facade.Binding; import de.tuilmenau.ics.fog.facade.Connection; import de.tuilmenau.ics.fog.facade.Description; import de.tuilmenau.ics.fog.facade.Identity; import de.tuilmenau.ics.fog.facade.Name; import de.tuilmenau.ics.fog.facade.Namespace; import de.tuilmenau.ics.fog.facade.NetworkException; import de.tuilmenau.ics.fog.facade.RequirementsException; import de.tuilmenau.ics.fog.facade.RoutingException; import de.tuilmenau.ics.fog.facade.Signature; import de.tuilmenau.ics.fog.facade.events.ConnectedEvent; import de.tuilmenau.ics.fog.facade.events.ErrorEvent; import de.tuilmenau.ics.fog.facade.events.Event; import de.tuilmenau.ics.fog.facade.properties.CommunicationTypeProperty; import de.tuilmenau.ics.fog.packets.hierarchical.clustering.RequestClusterMembership; import de.tuilmenau.ics.fog.routing.Route; import de.tuilmenau.ics.fog.routing.RouteSegmentPath; import de.tuilmenau.ics.fog.routing.RoutingServiceLink; import de.tuilmenau.ics.fog.routing.hierarchical.election.BullyPriority; import de.tuilmenau.ics.fog.routing.hierarchical.election.Elector; import de.tuilmenau.ics.fog.routing.hierarchical.management.*; import de.tuilmenau.ics.fog.routing.hierarchical.properties.*; import de.tuilmenau.ics.fog.routing.naming.HierarchicalNameMappingService; import de.tuilmenau.ics.fog.routing.naming.NameMappingEntry; import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID; import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMName; import de.tuilmenau.ics.fog.routing.naming.hierarchical.L2Address; import de.tuilmenau.ics.fog.topology.AutonomousSystem; import de.tuilmenau.ics.fog.topology.NetworkInterface; import de.tuilmenau.ics.fog.topology.Node; import de.tuilmenau.ics.fog.transfer.TransferPlaneObserver.NamingLevel; import de.tuilmenau.ics.fog.transfer.gates.GateID; import de.tuilmenau.ics.fog.ui.Decoration; import de.tuilmenau.ics.fog.ui.Logging; import de.tuilmenau.ics.fog.ui.eclipse.NodeDecorator; import de.tuilmenau.ics.fog.util.BlockingEventHandling; import de.tuilmenau.ics.fog.util.SimpleName; import edu.uci.ics.jung.graph.util.Pair; /** * This is the main HRM controller. It provides functions that are necessary to build up the hierarchical structure - every node contains such an object */ public class HRMController extends Application implements ServerCallback, IEvent { /** * Stores the node specific graph decorator for HRM coordinators and HRMIDs */ private NodeDecorator mDecoratorForCoordinatorsAndHRMIDs = null; /** * Stores the node specific graph decorator for HRM coordinators and clusters */ private NodeDecorator mDecoratorForCoordinatorsAndClusters = null; /** * Stores the node specific graph decorator for the active HRM infrastructure */ private NodeDecorator mDecoratorActiveHRMInfrastructure = null; /** * Stores the node specific graph decorator for HRM node base priority */ private NodeDecorator mDecoratorForNodePriorities = null; /** * Stores the GUI observable, which is used to notify possible GUIs about changes within this HRMController instance. */ private HRMControllerObservable mGUIInformer = new HRMControllerObservable(this); /** * Stores the HRG-GUI observable, which is used to notify possible HRG-GUI about changes within the HRG of the HRMController instance. */ private HRMControllerObservable mHRGGUIInformer = new HRMControllerObservable(this); /** * The name under which the HRMController application is registered on the local node. */ private SimpleName mApplicationName = null; /** * Reference to physical node. */ private Node mNode; /** * Stores a reference to the local autonomous system instance. */ private AutonomousSystem mAS = null; /** * Stores the registered HRMIDs. * This is used within the GUI and during "share phase". */ private LinkedList<HRMID> mRegisteredOwnHRMIDs = new LinkedList<HRMID>(); /** * Stores a database about all registered coordinators. * For example, this list is used for the GUI. */ private LinkedList<Coordinator> mLocalCoordinators = new LinkedList<Coordinator>(); /** * Stores all former known Coordinator IDs */ private LinkedList<Long> mFormerLocalCoordinatorIDs = new LinkedList<Long>(); /** * Stores a database about all registered coordinator proxies. */ private LinkedList<CoordinatorProxy> mLocalCoordinatorProxies = new LinkedList<CoordinatorProxy>(); /** * Stores a database about all registered clusters. * For example, this list is used for the GUI. */ private LinkedList<Cluster> mLocalClusters = new LinkedList<Cluster>(); /** * Stores a database about all registered cluster members (including Cluster objects). */ private LinkedList<ClusterMember> mLocalClusterMembers = new LinkedList<ClusterMember>(); /** * Stores a database about all registered L0 cluster members (including Cluster objects). * This list is used for deriving connectivity data for the distribution of topology data. */ private LinkedList<ClusterMember> mLocalL0ClusterMembers = new LinkedList<ClusterMember>(); /** * Stores a database about all registered CoordinatorAsClusterMemeber instances. */ private LinkedList<CoordinatorAsClusterMember> mLocalCoordinatorAsClusterMemebers = new LinkedList<CoordinatorAsClusterMember>(); /** * Stores a database about all registered comm. sessions. */ private LinkedList<ComSession> mCommunicationSessions = new LinkedList<ComSession>(); /** * Stores a reference to the local instance of the hierarchical routing service. */ private HRMRoutingService mHierarchicalRoutingService = null; /** * Stores if the application was already started. */ private boolean mApplicationStarted = false; /** * Stores a database including all HRMControllers of this physical simulation machine */ private static LinkedList<HRMController> mRegisteredHRMControllers = new LinkedList<HRMController>(); /** * Stores an abstract routing graph (ARG), which provides an abstract overview about logical links between clusters/coordinator. */ private AbstractRoutingGraph<AbstractRoutingGraphNode, AbstractRoutingGraphLink> mAbstractRoutingGraph = new AbstractRoutingGraph<AbstractRoutingGraphNode, AbstractRoutingGraphLink>(); /** * Stores the hierarchical routing graph (HRG), which provides a hierarchical overview about the network topology. */ private AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink> mHierarchicalRoutingGraph = new AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink>(); /** * Count the outgoing connections */ private int mCounterOutgoingConnections = 0; /** * Stores if the entire FoGSiEm simulation was already created. * This is only used for debugging purposes. This is NOT a way for avoiding race conditions in signaling. */ private static boolean mFoGSiEmSimulationCreationFinished = false; /** * Stores the node priority per hierarchy level. * Level 0 isn't used here. (see "mNodeConnectivityPriority") */ private long mNodeHierarchyPriority[] = new long[HRMConfig.Hierarchy.HEIGHT]; /** * Stores the connectivity node priority */ private long mNodeConnectivityPriority = HRMConfig.Election.DEFAULT_BULLY_PRIORITY; /** * Stores the central node for the ARG */ private CentralNodeARG mCentralARGNode = null; /** * Stores a description about all connectivity priority updates */ private String mDesriptionConnectivityPriorityUpdates = new String(); /** * Stores a description about all HRMID updates */ private String mDescriptionHRMIDUpdates = new String(); /** * Stores a description about all HRG updates */ private String mDescriptionHRGUpdates = new String(); /** * Stores a description about all hierarchy priority updates */ private String mDesriptionHierarchyPriorityUpdates = new String(); /** * Stores the thread for clustering tasks and packet processing */ private HRMControllerProcessor mProcessorThread = null; /** * Stores a database about all known superior coordinators */ private LinkedList<ClusterName> mSuperiorCoordinators = new LinkedList<ClusterName>(); /** * Stores a database about all known network interfaces of this node */ private LinkedList<NetworkInterface> mLocalNetworkInterfaces = new LinkedList<NetworkInterface>(); /** * Stores the node-global election state */ private Object mNodeElectionState = null; /** * Stores the node-global election state change description */ private String mDescriptionNodeElectionState = new String(); /** * @param pAS the autonomous system at which this HRMController is instantiated * @param pNode the node on which this controller was started * @param pHRS is the hierarchical routing service that should be used */ public HRMController(AutonomousSystem pAS, Node pNode, HRMRoutingService pHierarchicalRoutingService) { // initialize the application context super(pNode, null, pNode.getIdentity()); // define the local name "routing://" mApplicationName = new SimpleName(ROUTING_NAMESPACE, null); // reference to the physical node mNode = pNode; // reference to the AutonomousSystem object mAS = pAS; // set the node-global election state mNodeElectionState = Elector.createNodeElectionState(); /** * Create the node specific decorator for HRM coordinators and HRMIDs */ mDecoratorForCoordinatorsAndHRMIDs = new NodeDecorator(); /** * Create the node specific decorator for HRM coordinators and clusters */ mDecoratorForCoordinatorsAndClusters = new NodeDecorator(); /** * Create the node specific decorator for HRM node priorities */ mDecoratorForNodePriorities = new NodeDecorator(); /** * Create the node specific decorator for the active HRM infrastructure */ mDecoratorActiveHRMInfrastructure = new NodeDecorator(); /** * Initialize the node hierarchy priority */ for(int i = 0; i < HRMConfig.Hierarchy.HEIGHT; i++){ mNodeHierarchyPriority[i] = HRMConfig.Election.DEFAULT_BULLY_PRIORITY; } /** * Set the node decorations */ Decoration tDecoration = null; // create own decoration for HRM coordinators & HRMIDs tDecoration = Decoration.getInstance(DECORATION_NAME_COORDINATORS_AND_HRMIDS); tDecoration.setDecorator(mNode, mDecoratorForCoordinatorsAndHRMIDs); // create own decoration for HRM coordinators and clusters tDecoration = Decoration.getInstance(DECORATION_NAME_COORDINATORS_AND_CLUSTERS); tDecoration.setDecorator(mNode, mDecoratorForCoordinatorsAndClusters); // create own decoration for HRM node priorities tDecoration = Decoration.getInstance(DECORATION_NAME_NODE_PRIORITIES); tDecoration.setDecorator(mNode, mDecoratorForNodePriorities); // create own decoration for HRM node priorities tDecoration = Decoration.getInstance(DECORATION_NAME_ACTIVE_HRM_INFRASTRUCTURE); tDecoration.setDecorator(mNode, mDecoratorActiveHRMInfrastructure); // overwrite default decoration tDecoration = Decoration.getInstance(GraphViewer.DEFAULT_DECORATION); tDecoration.setDecorator(mNode, mDecoratorForCoordinatorsAndHRMIDs); /** * Create clusterer thread */ mProcessorThread = new HRMControllerProcessor(this); /** * Start the clusterer thread */ mProcessorThread.start(); /** * Create communication service */ // bind the HRMController application to a local socket Binding tServerSocket=null; // enable simple datagram based communication Description tServiceReq = getDescription(); tServiceReq.set(CommunicationTypeProperty.DATAGRAM); tServerSocket = getLayer().bind(null, mApplicationName, tServiceReq, getIdentity()); if (tServerSocket != null){ // create and start the socket service Service tService = new Service(false, this); tService.start(tServerSocket); }else{ Logging.err(this, "Unable to start the HRMController service"); } // store the reference to the local instance of hierarchical routing service mHierarchicalRoutingService = pHierarchicalRoutingService; // create central node in the local ARG mCentralARGNode = new CentralNodeARG(this); // create local loopback session ComSession.createLoopback(this); // fire the first "report/share phase" trigger reportAndShare(); Logging.log(this, "CREATED"); // start the application start(); } /** * Returns the local instance of the hierarchical routing service * * @return hierarchical routing service of this entity */ public HRMRoutingService getHRS() { return mHierarchicalRoutingService; } /** * Returns the local physical node object. * * @return the physical node running this coordinator */ public Node getNode() { return mNode; } /** * Return the actual GUI name description of the physical node; * However, this function should only be used for debug outputs, e.g., GUI outputs. * * @return the GUI name */ @SuppressWarnings("deprecation") public String getNodeGUIName() { return mNode.getName(); } /** * Notifies the GUI about essential updates within the HRM system */ private void notifyGUI(Object pArgument) { if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){ Logging.log(this, "Got notification with argument " + pArgument); } mGUIInformer.notifyObservers(pArgument); } /** * Notifies the HRGViewer about essential updates within the HRG graph */ private void notifyHRGGUI(Object pArgument) { if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){ Logging.log(this, "Got HRG notification with argument " + pArgument); } mHRGGUIInformer.notifyObservers(pArgument); } /** * Registers a GUI for being notified about HRMController internal changes. */ public void registerGUI(Observer pGUI) { if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){ Logging.log(this, "Registering GUI " + pGUI); } mGUIInformer.addObserver(pGUI); } /** * Registers a HRG-GUI for being notified about HRG internal changes. */ public void registerHRGGUI(Observer pHRGGUI) { if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){ Logging.log(this, "Registering HRG-GUI " + pHRGGUI); } mHRGGUIInformer.addObserver(pHRGGUI); } /** * Unregisters a GUI for being notified about HRMController internal changes. */ public void unregisterGUI(Observer pGUI) { if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){ Logging.log(this, "Unregistering GUI " + pGUI); } mGUIInformer.deleteObserver(pGUI); } /** * Unregisters a HRG-GUI for being notified about HRG internal changes. */ public void unregisterHRGGUI(Observer pHRGGUI) { if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){ Logging.log(this, "Unregistering HRG-GUI " + pHRGGUI); } mHRGGUIInformer.deleteObserver(pHRGGUI); } /** * Registers a coordinator proxy at the local database. * * @param pCoordinatorProxy the coordinator proxy for a defined coordinator */ public synchronized void registerCoordinatorProxy(CoordinatorProxy pCoordinatorProxy) { Logging.log(this, "Registering coordinator proxy " + pCoordinatorProxy + " at level " + pCoordinatorProxy.getHierarchyLevel().getValue()); synchronized (mLocalCoordinatorProxies) { // register as known coordinator proxy mLocalCoordinatorProxies.add(pCoordinatorProxy); } // increase hierarchy node priority increaseHierarchyNodePriority_KnownBaseCoordinator(pCoordinatorProxy); // updates the GUI decoration for this node updateGUINodeDecoration(); // register the coordinator prxy in the local ARG registerNodeARG(pCoordinatorProxy); // it's time to update the GUI notifyGUI(pCoordinatorProxy); } /** * Unregisters a coordinator proxy from the local database. * * @param pCoordinatorProxy the coordinator proxy for a defined coordinator */ public synchronized void unregisterCoordinatorProxy(CoordinatorProxy pCoordinatorProxy) { Logging.log(this, "Unregistering coordinator proxy " + pCoordinatorProxy + " at level " + pCoordinatorProxy.getHierarchyLevel().getValue()); synchronized (mLocalCoordinatorProxies) { // unregister as known coordinator proxy mLocalCoordinatorProxies.remove(pCoordinatorProxy); } // increase hierarchy node priority decreaseHierarchyNodePriority_KnownBaseCoordinator(pCoordinatorProxy); // updates the GUI decoration for this node updateGUINodeDecoration(); // register the coordinator prxy in the local ARG unregisterNodeARG(pCoordinatorProxy); // it's time to update the GUI notifyGUI(pCoordinatorProxy); } /** * Registers a coordinator at the local database. * * @param pCoordinator the coordinator for a defined cluster */ public synchronized void registerCoordinator(Coordinator pCoordinator) { Logging.log(this, "Registering coordinator " + pCoordinator + " at level " + pCoordinator.getHierarchyLevel().getValue()); Coordinator tFoundAnInferiorCoordinator = getCoordinator(pCoordinator.getHierarchyLevel().getValue() - 1); /** * Check if the hierarchy is continuous */ if((!pCoordinator.getHierarchyLevel().isBaseLevel()) && (tFoundAnInferiorCoordinator == null)){ Logging.err(this, "Hierarchy is temporary non continuous, detected an error in the Matrix!?"); } synchronized (mLocalCoordinators) { // register as known coordinator mLocalCoordinators.add(pCoordinator); } // increase hierarchy node priority increaseHierarchyNodePriority_KnownBaseCoordinator(pCoordinator); // updates the GUI decoration for this node updateGUINodeDecoration(); // register the coordinator in the local ARG if (HRMConfig.DebugOutput.GUI_SHOW_COORDINATORS_IN_ARG){ registerNodeARG(pCoordinator); registerLinkARG(pCoordinator, pCoordinator.getCluster(), new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF)); } // it's time to update the GUI notifyGUI(pCoordinator); } /** * Unregisters a coordinator from the internal database. * * @param pCoordinator the coordinator which should be unregistered */ public synchronized void unregisterCoordinator(Coordinator pCoordinator) { Logging.log(this, "Unregistering coordinator " + pCoordinator + " at level " + pCoordinator.getHierarchyLevel().getValue()); synchronized (mLocalCoordinators) { // unregister from list of known coordinators mLocalCoordinators.remove(pCoordinator); synchronized (mFormerLocalCoordinatorIDs) { mFormerLocalCoordinatorIDs.add(pCoordinator.getGUICoordinatorID()); } } // increase hierarchy node priority decreaseHierarchyNodePriority_KnownBaseCoordinator(pCoordinator); // updates the GUI decoration for this node updateGUINodeDecoration(); // unregister from the ARG if (HRMConfig.DebugOutput.GUI_SHOW_COORDINATORS_IN_ARG){ unregisterNodeARG(pCoordinator); } // it's time to update the GUI notifyGUI(pCoordinator); } /** * Registers an HRMID at local database * * @param pEntity the entity for which the HRMID should be registered * @param pCause the cause for the registration */ private void registerHRMID(ControlEntity pEntity, String pCause) { /** * Get the new HRMID */ HRMID tHRMID = pEntity.getHRMID(); if((tHRMID != null) && (!tHRMID.isZero())){ registerHRMID(pEntity, tHRMID, pCause); } } /** * Registers an HRMID at local database * * @param pEntity the entity for which the HRMID should be registered * @param pHRMID the new HRMID * @param pCause the cause for the registration */ public void registerHRMID(ControlEntity pEntity, HRMID pHRMID, String pCause) { /** * Some validations */ if(pHRMID != null){ // ignore "0.0.0" if(!pHRMID.isZero()){ /** * Register the HRMID */ synchronized(mRegisteredOwnHRMIDs){ if ((!mRegisteredOwnHRMIDs.contains(pHRMID)) || (!HRMConfig.DebugOutput.GUI_AVOID_HRMID_DUPLICATES)){ /** * Update the local address DB with the given HRMID */ if (HRMConfig.DebugOutput.GUI_HRMID_UPDATES){ Logging.log(this, "Updating the HRMID to: " + pHRMID.toString() + " for: " + pEntity); } // register the new HRMID as local one mRegisteredOwnHRMIDs.add(pHRMID); if(!pHRMID.isClusterAddress()){ mDescriptionHRMIDUpdates += "\n + " + pHRMID.toString() + " <== " + pEntity + ", cause=" + pCause; /** * Register a local loopback route for the new address */ // register a route to the cluster member as addressable target addHRMRoute(RoutingEntry.createLocalhostEntry(pHRMID, pCause + ", " + this + "::registerHRMID()")); /** * Update the DNS */ // register the HRMID in the hierarchical DNS for the local router HierarchicalNameMappingService<HRMID> tNMS = null; try { tNMS = (HierarchicalNameMappingService) HierarchicalNameMappingService.getGlobalNameMappingService(mAS.getSimulation()); } catch (RuntimeException tExc) { HierarchicalNameMappingService.createGlobalNameMappingService(getNode().getAS().getSimulation()); } // get the local router's human readable name (= DNS name) Name tLocalRouterName = getNodeName(); // register HRMID for the given DNS name tNMS.registerName(tLocalRouterName, pHRMID, NamingLevel.NAMES); // give some debug output about the current DNS state String tString = new String(); for(NameMappingEntry<HRMID> tEntry : tNMS.getAddresses(tLocalRouterName)) { if (!tString.isEmpty()){ tString += ", "; } tString += tEntry; } Logging.log(this, "HRM router " + tLocalRouterName + " is now known under: " + tString); } /** * Update the GUI */ // updates the GUI decoration for this node updateGUINodeDecoration(); // it's time to update the GUI notifyGUI(pEntity); }else{ if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){ Logging.warn(this, "Skipping HRMID duplicate for " + pHRMID.toString() + ", additional registration is triggered by " + pEntity); } } } }else{ throw new RuntimeException(this + "registerHRMID() got a zero HRMID " + pHRMID.toString() + " for: " + pEntity); } }else{ Logging.err(this, "registerHRMID() got an invalid HRMID for: " + pEntity); } } /** * Unregisters an HRMID at local database * * @param pEntity the entity for which the HRMID should be registered * @param pOldHRMID the old HRMID which should be unregistered * @param pCause the cause for this call */ public void unregisterHRMID(ControlEntity pEntity, HRMID pOldHRMID, String pCause) { /** * Some validations */ if(pOldHRMID != null){ // ignore "0.0.0" if(!pOldHRMID.isZero()){ /** * Unregister the HRMID */ synchronized(mRegisteredOwnHRMIDs){ if (mRegisteredOwnHRMIDs.contains(pOldHRMID)){ /** * Update the local address DB with the given HRMID */ if (HRMConfig.DebugOutput.GUI_HRMID_UPDATES){ Logging.log(this, "Revoking the HRMID: " + pOldHRMID.toString() + " of: " + pEntity); } // unregister the HRMID as local one mRegisteredOwnHRMIDs.remove(pOldHRMID); if(!pOldHRMID.isClusterAddress()){ mDescriptionHRMIDUpdates += "\n - " + pOldHRMID.toString() + " <== " + pEntity; /** * Unregister the local loopback route for the address */ // unregister a route to the cluster member as addressable target delHRMRoute(RoutingEntry.createLocalhostEntry(pOldHRMID, pCause + ", " + this + "::unregisterHRMID()")); /** * Update the DNS */ //TODO // register the HRMID in the hierarchical DNS for the local router // HierarchicalNameMappingService<HRMID> tNMS = null; // try { // tNMS = (HierarchicalNameMappingService) HierarchicalNameMappingService.getGlobalNameMappingService(mAS.getSimulation()); // } catch (RuntimeException tExc) { // HierarchicalNameMappingService.createGlobalNameMappingService(getNode().getAS().getSimulation()); // } // // get the local router's human readable name (= DNS name) // Name tLocalRouterName = getNodeName(); // // register HRMID for the given DNS name // tNMS.registerName(tLocalRouterName, pOldHRMID, NamingLevel.NAMES); // // give some debug output about the current DNS state // String tString = new String(); // for(NameMappingEntry<HRMID> tEntry : tNMS.getAddresses(tLocalRouterName)) { // if (!tString.isEmpty()){ // tString += ", "; // } // tString += tEntry; // } // Logging.log(this, "HRM router " + tLocalRouterName + " is now known under: " + tString); } /** * Update the GUI */ // updates the GUI decoration for this node updateGUINodeDecoration(); // it's time to update the GUI notifyGUI(pEntity); }else{ if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){ Logging.warn(this, "Skipping unknown HRMID " + pOldHRMID.toString() + ", unregistration is triggered by " + pEntity); } } } }else{ throw new RuntimeException(this + "unregisterHRMID() got a zero HRMID " + pOldHRMID.toString() + " for: " + pEntity); } }else{ Logging.err(this, "unregisterHRMID() got an invalid HRMID for: " + pEntity); } } /** * Updates the registered HRMID for a defined coordinator. * * @param pCluster the cluster whose HRMID is updated * @param pOldHRMID the old HRMID which should be unregistered */ public void updateCoordinatorAddress(Coordinator pCoordinator, HRMID pOldHRMID) { /** * Unregister old */ if((pOldHRMID != null) && (!pOldHRMID.isZero())){ unregisterHRMID(pCoordinator, pOldHRMID, "updateCoordinatorAddress() for " + pCoordinator); } /** * Register new */ HRMID tHRMID = pCoordinator.getHRMID(); Logging.log(this, "Updating address from " + pOldHRMID + " to " + (tHRMID != null ? tHRMID.toString() : "null") + " for Coordinator " + pCoordinator); registerHRMID(pCoordinator, "updateCoordinatorAddress() for " + pCoordinator); } /** * Returns if a coordinator ID is a formerly known one * * @param pCoordinatorID the coordinator ID * * @return true or false */ public boolean isGUIFormerCoordiantorID(long pCoordinatorID) { boolean tResult = false; synchronized (mFormerLocalCoordinatorIDs) { tResult = mFormerLocalCoordinatorIDs.contains(pCoordinatorID); } return tResult; } /** * Revokes a coordinator address * * @param pCoordinator the coordinator for which the address is revoked * @param pOldHRMID the old HRMID which should be unregistered */ public void revokeCoordinatorAddress(Coordinator pCoordinator, HRMID pOldHRMID) { if((pOldHRMID != null) && (!pOldHRMID.isZero())){ Logging.log(this, "Revoking address " + pOldHRMID.toString() + " for coordinator " + pCoordinator); unregisterHRMID(pCoordinator, pOldHRMID, "revokeCoordinatorAddress()"); } } /** * Updates the decoration of the node (image and label text) */ private void updateGUINodeDecoration() { /** * Set the decoration texts */ String tActiveHRMInfrastructureText = ""; for (int i = 0; i < HRMConfig.Hierarchy.HEIGHT; i++){ LinkedList<Cluster> tClusters = getAllClusters(i); for(Cluster tCluster : tClusters){ if(tCluster.hasLocalCoordinator()){ if (tActiveHRMInfrastructureText != ""){ tActiveHRMInfrastructureText += ", "; } tActiveHRMInfrastructureText += "<" + Long.toString(tCluster.getGUIClusterID()) + ">"; for(int j = 0; j < tCluster.getHierarchyLevel().getValue(); j++){ tActiveHRMInfrastructureText += "^"; } } } } LinkedList<ClusterName> tSuperiorCoordiantors = getAllSuperiorCoordinators(); for(ClusterName tSuperiorCoordinator : tSuperiorCoordiantors){ if (tActiveHRMInfrastructureText != ""){ tActiveHRMInfrastructureText += ", "; } tActiveHRMInfrastructureText += Long.toString(tSuperiorCoordinator.getGUIClusterID()); for(int i = 0; i < tSuperiorCoordinator.getHierarchyLevel().getValue(); i++){ tActiveHRMInfrastructureText += "^"; } } mDecoratorActiveHRMInfrastructure.setText(" [Active clusters: " + tActiveHRMInfrastructureText + "]"); String tHierPrio = ""; for(int i = 1; i < HRMConfig.Hierarchy.HEIGHT; i++){ if (tHierPrio != ""){ tHierPrio += ", "; } tHierPrio += Long.toString(mNodeHierarchyPriority[i]) +"@" + i; } mDecoratorForNodePriorities.setText(" [Hier.: " + tHierPrio + "/ Conn.: " + Long.toString(getConnectivityNodePriority()) + "]"); String tNodeText = ""; synchronized (mRegisteredOwnHRMIDs) { for (HRMID tHRMID: mRegisteredOwnHRMIDs){ if (((!tHRMID.isRelativeAddress()) || (HRMConfig.DebugOutput.GUI_SHOW_RELATIVE_ADDRESSES)) && ((!tHRMID.isClusterAddress()) || (HRMConfig.DebugOutput.GUI_SHOW_CLUSTER_ADDRESSES))){ if (tNodeText != ""){ tNodeText += ", "; } tNodeText += tHRMID.toString(); } } } mDecoratorForCoordinatorsAndHRMIDs.setText(tNodeText); String tClustersText = ""; tClustersText = ""; LinkedList<ClusterMember> tAllClusterMembers = getAllClusterMembers(); for (ClusterMember tClusterMember : tAllClusterMembers){ if (tClustersText != ""){ tClustersText += ", "; } // is this node the cluster head? if (tClusterMember instanceof Cluster){ Cluster tCluster = (Cluster)tClusterMember; if(tCluster.hasLocalCoordinator()){ tClustersText += "<" + Long.toString(tClusterMember.getGUIClusterID()) + ">"; }else{ tClustersText += "(" + Long.toString(tClusterMember.getGUIClusterID()) + ")"; } }else{ tClustersText += Long.toString(tClusterMember.getGUIClusterID()); } for(int i = 0; i < tClusterMember.getHierarchyLevel().getValue(); i++){ tClustersText += "^"; } } mDecoratorForCoordinatorsAndClusters.setText("- clusters: " + tClustersText); /** * Set the decoration images */ LinkedList<Coordinator> tAllCoordinators = getAllCoordinators(); int tHighestCoordinatorLevel = -1; for (Coordinator tCoordinator : tAllCoordinators){ int tCoordLevel = tCoordinator.getHierarchyLevel().getValue(); if (tCoordLevel > tHighestCoordinatorLevel){ tHighestCoordinatorLevel = tCoordLevel; } } mDecoratorForNodePriorities.setImage(tHighestCoordinatorLevel); mDecoratorForCoordinatorsAndHRMIDs.setImage(tHighestCoordinatorLevel); mDecoratorForCoordinatorsAndClusters.setImage(tHighestCoordinatorLevel); mDecoratorActiveHRMInfrastructure.setImage(tHighestCoordinatorLevel); } /** * Returns a list of all known network interfaces * * @return the list of known network interfaces */ @SuppressWarnings("unchecked") public LinkedList<NetworkInterface> getAllNetworkInterfaces() { LinkedList<NetworkInterface> tResult = null; synchronized (mLocalNetworkInterfaces) { tResult = (LinkedList<NetworkInterface>) mLocalNetworkInterfaces.clone(); } return tResult; } /** * Returns a list of all known local coordinators. * * @return the list of known local coordinators */ @SuppressWarnings("unchecked") public LinkedList<Coordinator> getAllCoordinators() { LinkedList<Coordinator> tResult; synchronized (mLocalCoordinators) { tResult = (LinkedList<Coordinator>) mLocalCoordinators.clone(); } return tResult; } /** * Returns all known coordinators for a given hierarchy level. * * @param pHierarchyLevel the hierarchy level for which all coordinators have to be determined * * @return the list of coordinators on the defined hierarchy level */ public LinkedList<Coordinator> getAllCoordinators(HierarchyLevel pHierarchyLevel) { return getAllCoordinators(pHierarchyLevel.getValue()); } /** * Returns all known coordinators for a given hierarchy level. * * @param pHierarchyLevel the hierarchy level for which all coordinators have to be determined * * @return the list of coordinators on the defined hierarchy level */ public LinkedList<Coordinator> getAllCoordinators(int pHierarchyLevel) { LinkedList<Coordinator> tResult = new LinkedList<Coordinator>(); // get a list of all known coordinators LinkedList<Coordinator> tAllCoordinators = getAllCoordinators(); // iterate over all known coordinators for (Coordinator tCoordinator : tAllCoordinators){ // have we found a matching coordinator? if (tCoordinator.getHierarchyLevel().getValue() == pHierarchyLevel){ // add this coordinator to the result tResult.add(tCoordinator); } } return tResult; } /** * Returns a list of all known local coordinator proxies. * * @return the list of known local coordinator proxies */ @SuppressWarnings("unchecked") public LinkedList<CoordinatorProxy> getAllCoordinatorProxies() { LinkedList<CoordinatorProxy> tResult; synchronized (mLocalCoordinatorProxies) { tResult = (LinkedList<CoordinatorProxy>) mLocalCoordinatorProxies.clone(); } return tResult; } /** * Returns all known coordinator proxies for a given hierarchy level. * * @param pHierarchyLevel the hierarchy level for which all coordinator proxies have to be determined * * @return the list of coordinator proies at the defined hierarchy level */ public LinkedList<CoordinatorProxy> getAllCoordinatorProxies(int pHierarchyLevel) { //Logging.log(this, "Searching for coordinator proxies at hierarchy level: " + pHierarchyLevel); LinkedList<CoordinatorProxy> tResult = new LinkedList<CoordinatorProxy>(); // get a list of all known coordinator proxies LinkedList<CoordinatorProxy> tAllCoordinatorProxies = getAllCoordinatorProxies(); // iterate over all known coordinator proxies for (CoordinatorProxy tCoordinatorProxy : tAllCoordinatorProxies){ // have we found a matching coordinator proxy? if (tCoordinatorProxy.getHierarchyLevel().getValue() == pHierarchyLevel){ // add this coordinator proxy to the result tResult.add(tCoordinatorProxy); } } //Logging.log(this, " ..found: " + tResult); return tResult; } /** * Registers a coordinator-as-cluster-member at the local database. * * @param pCoordinatorAsClusterMember the coordinator-as-cluster-member which should be registered */ public synchronized void registerCoordinatorAsClusterMember(CoordinatorAsClusterMember pCoordinatorAsClusterMember) { int tLevel = pCoordinatorAsClusterMember.getHierarchyLevel().getValue(); Logging.log(this, "Registering coordinator-as-cluster-member " + pCoordinatorAsClusterMember + " at level " + tLevel); boolean tNewEntry = false; synchronized (mLocalCoordinatorAsClusterMemebers) { // make sure the Bully priority is the right one, avoid race conditions here pCoordinatorAsClusterMember.setPriority(BullyPriority.create(this, getHierarchyNodePriority(pCoordinatorAsClusterMember.getHierarchyLevel()))); if(!mLocalCoordinatorAsClusterMemebers.contains(pCoordinatorAsClusterMember)){ // register as known coordinator-as-cluster-member mLocalCoordinatorAsClusterMemebers.add(pCoordinatorAsClusterMember); tNewEntry = true; } } if(tNewEntry){ if(HRMConfig.DebugOutput.GUI_SHOW_COORDINATOR_CLUSTER_MEMBERS_IN_ARG){ // updates the GUI decoration for this node updateGUINodeDecoration(); // register the node in the local ARG registerNodeARG(pCoordinatorAsClusterMember); // register the link in the local ARG registerLinkARG(pCoordinatorAsClusterMember, pCoordinatorAsClusterMember.getCoordinator(), new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF)); // register link to central node in the ARG if (HRMConfig.DebugOutput.SHOW_ALL_OBJECT_REFS_TO_CENTRAL_NODE_IN_ARG){ registerLinkARG(mCentralARGNode, pCoordinatorAsClusterMember, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF)); } // it's time to update the GUI notifyGUI(pCoordinatorAsClusterMember); } } } /** * Unregister a coordinator-as-cluster-member from the local database * * @param pCoordinatorAsClusterMember the coordinator-as-cluster-member which should be unregistered */ public synchronized void unregisterCoordinatorAsClusterMember(CoordinatorAsClusterMember pCoordinatorAsClusterMember) { Logging.log(this, "Unregistering coordinator-as-cluster-member " + pCoordinatorAsClusterMember); boolean tFoundEntry = false; synchronized (mLocalCoordinatorAsClusterMemebers) { if(mLocalCoordinatorAsClusterMemebers.contains(pCoordinatorAsClusterMember)){ // unregister the old HRMID revokeClusterMemberAddress(pCoordinatorAsClusterMember, pCoordinatorAsClusterMember.getHRMID()); // unregister from list of known cluster members mLocalCoordinatorAsClusterMemebers.remove(pCoordinatorAsClusterMember); Logging.log(this, " ..unregistered: " + pCoordinatorAsClusterMember); }else{ Logging.log(this, " ..not found: " + pCoordinatorAsClusterMember); } } if(tFoundEntry){ if(HRMConfig.DebugOutput.GUI_SHOW_COORDINATOR_CLUSTER_MEMBERS_IN_ARG){ // updates the GUI decoration for this node updateGUINodeDecoration(); // register at the ARG unregisterNodeARG(pCoordinatorAsClusterMember); // it's time to update the GUI notifyGUI(pCoordinatorAsClusterMember); } } } /** * Registers a cluster member at the local database. * * @param pClusterMember the cluster member which should be registered */ public synchronized void registerClusterMember(ClusterMember pClusterMember) { int tLevel = pClusterMember.getHierarchyLevel().getValue(); Logging.log(this, "Registering cluster member " + pClusterMember + " at level " + tLevel); boolean tNewEntry = false; synchronized (mLocalClusterMembers) { // make sure the Bully priority is the right one, avoid race conditions here pClusterMember.setPriority(BullyPriority.create(this, getConnectivityNodePriority())); if(!mLocalClusterMembers.contains(pClusterMember)){ // register as known cluster member mLocalClusterMembers.add(pClusterMember); tNewEntry = true; } } /** * Register as L0 ClusterMember */ if(pClusterMember.getHierarchyLevel().isBaseLevel()){ synchronized (mLocalL0ClusterMembers) { if(!mLocalL0ClusterMembers.contains(pClusterMember)){ // register as known cluster member mLocalL0ClusterMembers.add(pClusterMember); } } } if(tNewEntry){ // updates the GUI decoration for this node updateGUINodeDecoration(); // register the cluster in the local ARG registerNodeARG(pClusterMember); // register link to central node in the ARG if (HRMConfig.DebugOutput.SHOW_ALL_OBJECT_REFS_TO_CENTRAL_NODE_IN_ARG){ registerLinkARG(mCentralARGNode, pClusterMember, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF)); } // it's time to update the GUI notifyGUI(pClusterMember); } } /** * Unregister a cluster member from the local database * * @param pClusterMember the cluster member which should be unregistered */ public synchronized void unregisterClusterMember(ClusterMember pClusterMember) { Logging.log(this, "Unregistering cluster member " + pClusterMember); boolean tFoundEntry = false; synchronized (mLocalClusterMembers) { if(mLocalClusterMembers.contains(pClusterMember)){ // unregister the old HRMID revokeClusterMemberAddress(pClusterMember, pClusterMember.getHRMID()); // unregister from list of known cluster members mLocalClusterMembers.remove(pClusterMember); tFoundEntry = true; } } /** * Unregister as L0 ClusterMember */ if(pClusterMember.getHierarchyLevel().isBaseLevel()){ synchronized (mLocalL0ClusterMembers) { if(mLocalL0ClusterMembers.contains(pClusterMember)){ // register as known cluster member mLocalL0ClusterMembers.remove(pClusterMember); } } } if(tFoundEntry){ // updates the GUI decoration for this node updateGUINodeDecoration(); // register at the ARG unregisterNodeARG(pClusterMember); // it's time to update the GUI notifyGUI(pClusterMember); } } /** * Registers a cluster at the local database. * * @param pCluster the cluster which should be registered */ public synchronized void registerCluster(Cluster pCluster) { int tLevel = pCluster.getHierarchyLevel().getValue(); Logging.log(this, "Registering cluster " + pCluster + " at level " + tLevel); synchronized (mLocalClusters) { // register as known cluster mLocalClusters.add(pCluster); } synchronized (mLocalClusterMembers) { // register as known cluster member mLocalClusterMembers.add(pCluster); } /** * Register as L0 ClusterMember */ if(pCluster.getHierarchyLevel().isBaseLevel()){ synchronized (mLocalL0ClusterMembers) { if(!mLocalL0ClusterMembers.contains(pCluster)){ // register as known cluster member mLocalL0ClusterMembers.add(pCluster); } } } // updates the GUI decoration for this node updateGUINodeDecoration(); // register the cluster in the local ARG registerNodeARG(pCluster); // register link to central node in the ARG if (HRMConfig.DebugOutput.SHOW_ALL_OBJECT_REFS_TO_CENTRAL_NODE_IN_ARG){ registerLinkARG(mCentralARGNode, pCluster, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.OBJECT_REF)); } // it's time to update the GUI notifyGUI(pCluster); } /** * Unregisters a cluster from the local database. * * @param pCluster the cluster which should be unregistered. */ public synchronized void unregisterCluster(Cluster pCluster) { Logging.log(this, "Unregistering cluster " + pCluster); synchronized (mLocalClusters) { // unregister the old HRMID revokeClusterAddress(pCluster, pCluster.getHRMID()); // unregister from list of known clusters mLocalClusters.remove(pCluster); } synchronized (mLocalClusterMembers) { // unregister from list of known cluster members mLocalClusterMembers.remove(pCluster); } /** * Unregister as L0 ClusterMember */ if(pCluster.getHierarchyLevel().isBaseLevel()){ synchronized (mLocalL0ClusterMembers) { if(mLocalL0ClusterMembers.contains(pCluster)){ // register as known cluster member mLocalL0ClusterMembers.remove(pCluster); } } } // updates the GUI decoration for this node updateGUINodeDecoration(); // register at the ARG unregisterNodeARG(pCluster); // it's time to update the GUI notifyGUI(pCluster); } /** * Updates the registered HRMID for a defined Cluster. * * @param pCluster the Cluster whose HRMID is updated * @param pOldHRMID the old HRMID */ public void updateClusterAddress(Cluster pCluster, HRMID pOldHRMID) { /** * Unregister old */ if((pOldHRMID != null) && (!pOldHRMID.isZero())){ unregisterHRMID(pCluster, pOldHRMID, "updateClusterAddress() for " + pCluster); } /** * Register new */ HRMID tHRMID = pCluster.getHRMID(); Logging.log(this, "Updating address from " + pOldHRMID + " to " + (tHRMID != null ? tHRMID.toString() : "null") + " for Cluster " + pCluster); registerHRMID(pCluster, "updateClusterAddress() for " + pCluster); } /** * Updates the registered HRMID for a defined ClusterMember. * * @param pClusterMember the ClusterMember whose HRMID is updated * @param pOldHRMID the old HRMID which should be unregistered */ public void updateClusterMemberAddress(ClusterMember pClusterMember, HRMID pOldHRMID) { /** * Unregister old */ if((pOldHRMID != null) && (!pOldHRMID.isZero())){ unregisterHRMID(pClusterMember, pOldHRMID, "updateClusterMemberAddress() for " + pClusterMember); } /** * Register new */ HRMID tHRMID = pClusterMember.getHRMID(); Logging.log(this, "Updating address from " + pOldHRMID.toString() + " to " + (tHRMID != null ? tHRMID.toString() : "null") + " for ClusterMember " + pClusterMember); // process this only if we are at base hierarchy level, otherwise we will receive the same update from // the corresponding coordinator instance if (pClusterMember.getHierarchyLevel().isBaseLevel()){ registerHRMID(pClusterMember, "updateClusterMemberAddress() for " + pClusterMember); }else{ // we are at a higher hierarchy level and don't need the HRMID update because we got the same from the corresponding coordinator instance if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){ Logging.warn(this, "Skipping HRMID registration " + (tHRMID != null ? tHRMID.toString() : "null") + " for " + pClusterMember); } } } /** * Revokes a cluster address * * @param pClusterMember the ClusterMember for which the address is revoked * @param pOldHRMID the old HRMID which should be unregistered */ public void revokeClusterMemberAddress(ClusterMember pClusterMember, HRMID pOldHRMID) { if((pOldHRMID != null) && (!pOldHRMID.isZero())){ Logging.log(this, "Revoking address " + pOldHRMID.toString() + " for ClusterMember " + pClusterMember); if (pClusterMember.getHierarchyLevel().isBaseLevel()){ unregisterHRMID(pClusterMember, pOldHRMID, "revokeClusterMemberAddress()"); }else{ // we are at a higher hierarchy level and don't need the HRMID revocation if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){ Logging.warn(this, "Skipping HRMID revocation of " + pOldHRMID.toString() + " for " + pClusterMember); } } } } /** * Revokes a cluster address * * @param pCluster the Cluster for which the address is revoked * @param pOldHRMID the old HRMID which should be unregistered */ public void revokeClusterAddress(Cluster pCluster, HRMID pOldHRMID) { if((pOldHRMID != null) && (!pOldHRMID.isZero())){ Logging.log(this, "Revoking address " + pOldHRMID.toString() + " for Cluster " + pCluster); if (pCluster.getHierarchyLevel().isBaseLevel()){ unregisterHRMID(pCluster, pOldHRMID, "revokeClusterAddress()"); }else{ // we are at a higher hierarchy level and don't need the HRMID revocation if (HRMConfig.DebugOutput.SHOW_DEBUG_ADDRESS_DISTRIBUTION){ Logging.warn(this, "Skipping HRMID revocation of " + pOldHRMID.toString() + " for " + pCluster); } } } } /** * Registers a superior coordinator at the local database * * @param pSuperiorCoordinatorClusterName a description of the announced superior coordinator */ public void registerSuperiorCoordinator(ClusterName pSuperiorCoordinatorClusterName) { boolean tUpdateGui = false; synchronized (mSuperiorCoordinators) { if(!mSuperiorCoordinators.contains(pSuperiorCoordinatorClusterName)){ Logging.log(this, "Registering superior coordinator: " + pSuperiorCoordinatorClusterName + ", knowing these superior coordinators: " + mSuperiorCoordinators); mSuperiorCoordinators.add(pSuperiorCoordinatorClusterName); tUpdateGui = true; }else{ // already registered } } /** * Update the GUI */ // updates the GUI decoration for this node if(tUpdateGui){ updateGUINodeDecoration(); } } /** * Unregisters a formerly registered superior coordinator from the local database * * @param pSuperiorCoordinatorClusterName a description of the invalid superior coordinator */ public void unregisterSuperiorCoordinator(ClusterName pSuperiorCoordinatorClusterName) { boolean tUpdateGui = false; synchronized (mSuperiorCoordinators) { if(mSuperiorCoordinators.contains(pSuperiorCoordinatorClusterName)){ Logging.log(this, "Unregistering superior coordinator: " + pSuperiorCoordinatorClusterName + ", knowing these superior coordinators: " + mSuperiorCoordinators); mSuperiorCoordinators.remove(pSuperiorCoordinatorClusterName); tUpdateGui = true; }else{ // already removed or never registered } } /** * Update the GUI */ // updates the GUI decoration for this node if(tUpdateGui){ updateGUINodeDecoration(); } } /** * Returns all superior coordinators * * @return the superior coordinators */ @SuppressWarnings("unchecked") public LinkedList<ClusterName> getAllSuperiorCoordinators() { LinkedList<ClusterName> tResult = null; synchronized (mSuperiorCoordinators) { tResult = (LinkedList<ClusterName>) mSuperiorCoordinators.clone(); } return tResult; } /** * Returns a list of known coordinator as cluster members. * * @return the list of known coordinator as cluster members */ @SuppressWarnings("unchecked") public LinkedList<CoordinatorAsClusterMember> getAllCoordinatorAsClusterMembers() { LinkedList<CoordinatorAsClusterMember> tResult = null; synchronized (mLocalCoordinatorAsClusterMemebers) { tResult = (LinkedList<CoordinatorAsClusterMember>) mLocalCoordinatorAsClusterMemebers.clone(); } return tResult; } /** * Returns a list of known cluster members. * * @return the list of known cluster members */ @SuppressWarnings("unchecked") public LinkedList<ClusterMember> getAllClusterMembers() { LinkedList<ClusterMember> tResult = null; synchronized (mLocalClusterMembers) { tResult = (LinkedList<ClusterMember>) mLocalClusterMembers.clone(); } return tResult; } /** * Returns a list of known L0 cluster members. * * @return the list of known L0 cluster members */ @SuppressWarnings("unchecked") public LinkedList<ClusterMember> getAllL0ClusterMembers() { LinkedList<ClusterMember> tResult = null; synchronized (mLocalL0ClusterMembers) { tResult = (LinkedList<ClusterMember>) mLocalL0ClusterMembers.clone(); } return tResult; } /** * Returns a list of known cluster members (including local Cluster objects) for a given hierarchy level. * * @param pHierarchyLevel the hierarchy level * * @return the list of cluster members */ public LinkedList<ClusterMember> getAllClusterMembers(HierarchyLevel pHierarchyLevel) { return getAllClusterMembers(pHierarchyLevel.getValue()); } /** * Returns a list of known CoordinatorAsClusterMember for a given hierarchy level. * * @param pHierarchyLevel the hierarchy level * * @return the list of CoordinatorAsClusterMember */ public LinkedList<CoordinatorAsClusterMember> getAllCoordinatorAsClusterMembers(int pHierarchyLevel) { LinkedList<CoordinatorAsClusterMember> tResult = new LinkedList<CoordinatorAsClusterMember>(); // get a list of all known coordinators LinkedList<CoordinatorAsClusterMember> tAllCoordinatorAsClusterMembers = getAllCoordinatorAsClusterMembers(); // iterate over all known coordinators for (CoordinatorAsClusterMember tCoordinatorAsClusterMember : tAllCoordinatorAsClusterMembers){ // have we found a matching coordinator? if (tCoordinatorAsClusterMember.getHierarchyLevel().getValue() == pHierarchyLevel){ // add this coordinator to the result tResult.add(tCoordinatorAsClusterMember); } } return tResult; } /** * Returns a list of known cluster members (including local Cluster objects) for a given hierarchy level. * * @param pHierarchyLevel the hierarchy level * * @return the list of cluster members */ public LinkedList<ClusterMember> getAllClusterMembers(int pHierarchyLevel) { LinkedList<ClusterMember> tResult = new LinkedList<ClusterMember>(); // get a list of all known coordinators LinkedList<ClusterMember> tAllClusterMembers = getAllClusterMembers(); // iterate over all known coordinators for (ClusterMember tClusterMember : tAllClusterMembers){ // have we found a matching coordinator? if (tClusterMember.getHierarchyLevel().getValue() == pHierarchyLevel){ // add this coordinator to the result tResult.add(tClusterMember); } } return tResult; } /** * Returns a list of known clusters. * * @return the list of known clusters */ @SuppressWarnings("unchecked") public LinkedList<Cluster> getAllClusters() { LinkedList<Cluster> tResult = null; synchronized (mLocalClusters) { tResult = (LinkedList<Cluster>) mLocalClusters.clone(); } return tResult; } /** * Returns a list of known clusters for a given hierarchy level. * * @param pHierarchyLevel the hierarchy level * * @return the list of clusters */ public LinkedList<Cluster> getAllClusters(HierarchyLevel pHierarchyLevel) { return getAllClusters(pHierarchyLevel.getValue()); } /** * Returns a list of known clusters for a given hierarchy level. * * @param pHierarchyLevel the hierarchy level * * @return the list of clusters */ public LinkedList<Cluster> getAllClusters(int pHierarchyLevel) { LinkedList<Cluster> tResult = new LinkedList<Cluster>(); // get a list of all known coordinators LinkedList<Cluster> tAllClusters = getAllClusters(); // iterate over all known coordinators for (Cluster tCluster : tAllClusters){ // have we found a matching coordinator? if (tCluster.getHierarchyLevel().getValue() == pHierarchyLevel){ // add this coordinator to the result tResult.add(tCluster); } } return tResult; } /** * Returns the locally known Cluster object, which was identified by its ClusterName * * @param pClusterName the cluster name of the searched cluster * * @return the desired cluster, null if the cluster isn't known */ private Cluster getClusterByName(ClusterName pClusterName) { Cluster tResult = null; for(Cluster tKnownCluster : getAllClusters()) { if(tKnownCluster.equals(pClusterName)) { tResult = tKnownCluster; break; } } return tResult; } /** * Returns the locally known Cluster object for a given hierarchy level * * @param pHierarchyLevel the hierarchy level for which the Cluster object is searched * * @return the found Cluster object */ public Cluster getCluster(int pHierarchyLevel) { Cluster tResult = null; for(Cluster tKnownCluster : getAllClusters()) { if(tKnownCluster.getHierarchyLevel().getValue() == pHierarchyLevel) { tResult = tKnownCluster; break; } } return tResult; } /** * Returns the locally known Coordinator object for a given hierarchy level * * @param pHierarchyLevelValue the hierarchy level for which the Coordinator object is searched * * @return the found Coordinator object */ public Coordinator getCoordinator(int pHierarchyLevelValue) { Coordinator tResult = null; for(Coordinator tKnownCoordinator : getAllCoordinators()) { if(tKnownCoordinator.getHierarchyLevel().getValue() == pHierarchyLevelValue) { tResult = tKnownCoordinator; break; } } return tResult; } /** * Returns a locally known Coordinator object for a given hierarchy level. * HINT: For base hierarchy level, there could exist more than one local coordinator! * * @param pHierarchyLevel the hierarchy level for which the Coordinator object is searched * * @return the found Coordinator object */ public Coordinator getCoordinator(HierarchyLevel pHierarchyLevel) { Coordinator tResult = null; for(Coordinator tKnownCoordinator : getAllCoordinators()) { if(tKnownCoordinator.getHierarchyLevel().equals(pHierarchyLevel)) { tResult = tKnownCoordinator; break; } } return tResult; } /** * Returns the locally known CoordinatorProxy object, which was identified by its ClusterName * * @param pClusterName the cluster name of the searched coordinator proxy * * @return the desired CoordinatorProxy, null if the coordinator isn't known */ public CoordinatorProxy getCoordinatorProxyByName(ClusterName pClusterName) { CoordinatorProxy tResult = null; synchronized (mLocalCoordinatorProxies) { for (CoordinatorProxy tCoordinatorProxy : mLocalCoordinatorProxies){ if(tCoordinatorProxy.equals(pClusterName)){ tResult = tCoordinatorProxy; break; } } } return tResult; } /** * Returns a known coordinator, which is identified by its ID. * * @param pCoordinatorID the coordinator ID * * @return the searched coordinator object */ public Coordinator getCoordinatorByID(int pCoordinatorID) { Coordinator tResult = null; for(Coordinator tKnownCoordinator : getAllCoordinators()) { if (tKnownCoordinator.getCoordinatorID() == pCoordinatorID) { tResult = tKnownCoordinator; } } return tResult; } /** * Clusters the given hierarchy level * HINT: It is synchronized to only one call at the same time. * * @param pHierarchyLevel the hierarchy level where a clustering should be done */ public void cluster(ControlEntity pCause, final HierarchyLevel pHierarchyLevel) { if(pHierarchyLevel.getValue() <= HRMConfig.Hierarchy.CONTINUE_AUTOMATICALLY_HIERARCHY_LIMIT){ Logging.log(this, "CLUSTERING REQUEST for hierarchy level: " + pHierarchyLevel.getValue() + ", cause=" + pCause); mProcessorThread.eventUpdateCluster(pCause, pHierarchyLevel); } } /** * Notifies packet processor about a new packet * * @param pComChannel the comm. channel which has a new received packet */ public void notifyPacketProcessor(ComChannel pComChannel) { mProcessorThread.eventReceivedPacket(pComChannel); } /** * Registers an outgoing communication session * * @param pComSession the new session */ public void registerSession(ComSession pComSession) { Logging.log(this, "Registering communication session: " + pComSession); synchronized (mCommunicationSessions) { mCommunicationSessions.add(pComSession); } } /** * Determines the outgoing communication session for a desired target cluster * HINT: This function has to be called in a separate thread! * * @param pDestinationL2Address the L2 address of the destination * * @return the found comm. session or null */ public ComSession getCreateComSession(L2Address pDestinationL2Address) { ComSession tResult = null; // is the destination valid? if (pDestinationL2Address != null){ //Logging.log(this, "Searching for outgoing comm. session to: " + pDestinationL2Address); synchronized (mCommunicationSessions) { for (ComSession tComSession : mCommunicationSessions){ //Logging.log(this, " ..ComSession: " + tComSession); // get the L2 address of the comm. session peer L2Address tPeerL2Address = tComSession.getPeerL2Address(); if(pDestinationL2Address.equals(tPeerL2Address)){ //Logging.log(this, " ..found match"); tResult = tComSession; break; }else{ //Logging.log(this, " ..uninteresting"); } } } // have we found an already existing connection? if(tResult == null){ //Logging.log(this, "getCreateComSession() could find a comm. session for destination: " + pDestinationL2Address + ", knowing these sessions and their channels:"); synchronized (mCommunicationSessions) { for (ComSession tComSession : mCommunicationSessions){ //Logging.log(this, " ..ComSession: " + tComSession); for(ComChannel tComChannel : tComSession.getAllComChannels()){ //Logging.log(this, " ..ComChannel: " + tComChannel); //Logging.log(this, " ..RemoteCluster: " + tComChannel.getRemoteClusterName().toString()); } } } /** * Create the new connection */ //Logging.log(this, " ..creating new connection and session to: " + pDestinationL2Address); tResult = createComSession(pDestinationL2Address); } }else{ //Logging.err(this, "getCreateComSession() detected invalid destination L2 address"); } return tResult; } /** * Creates a new comm. session (incl. connection) to a given destination L2 address and uses the given connection requirements * HINT: This function has to be called in a separate thread! * * @param pDestinationL2Address the L2 address of the destination * * @return the new comm. session or null */ private ComSession createComSession(L2Address pDestinationL2Address) { ComSession tResult = null; /** * Create default connection requirements */ Description tConnectionRequirements = createHRMControllerDestinationDescription(); Logging.log(this, "Creating connection/comm. session to: " + pDestinationL2Address + " with requirements: " + tConnectionRequirements); /** * Create communication session */ Logging.log(this, " ..creating new communication session"); ComSession tComSession = new ComSession(this); /** * Wait until the FoGSiEm simulation is created */ if(HRMConfig.DebugOutput.BLOCK_HIERARCHY_UNTIL_END_OF_SIMULATION_CREATION) { while(!simulationCreationFinished()){ try { Logging.log(this, "WAITING FOR END OF SIMULATION CREATION"); Thread.sleep(100); } catch (InterruptedException e) { } } } /** * Connect to the neighbor node */ Connection tConnection = null; Logging.log(this, " ..CONNECTING to: " + pDestinationL2Address + " with requirements: " + tConnectionRequirements); try { tConnection = connectBlock(pDestinationL2Address, tConnectionRequirements, getNode().getIdentity()); } catch (NetworkException tExc) { Logging.err(this, "Cannot connect to: " + pDestinationL2Address, tExc); } Logging.log(this, " ..connectBlock() FINISHED"); if(tConnection != null) { mCounterOutgoingConnections++; Logging.log(this, " ..starting this OUTGOING CONNECTION as nr. " + mCounterOutgoingConnections); tComSession.startConnection(pDestinationL2Address, tConnection); // return the created comm. session tResult = tComSession; }else{ Logging.err(this, " ..connection failed to: " + pDestinationL2Address + " with requirements: " + tConnectionRequirements); } return tResult; } /** * Unregisters an outgoing communication session * * @param pComSession the session */ public void unregisterSession(ComSession pComSession) { Logging.log(this, "Unregistering outgoing communication session: " + pComSession); synchronized (mCommunicationSessions) { mCommunicationSessions.remove(pComSession); } } /** * Returns the list of registered own HRMIDs which can be used to address the physical node on which this instance is running. * * @return the list of HRMIDs */ @SuppressWarnings("unchecked") public LinkedList<HRMID> getHRMIDs() { LinkedList<HRMID> tResult = null; synchronized(mRegisteredOwnHRMIDs){ tResult = (LinkedList<HRMID>) mRegisteredOwnHRMIDs.clone(); } return tResult; } /** * @param pForeignHRMID * @return */ public HRMID aggregateForeignHRMID(HRMID pForeignHRMID) { HRMID tResult = null; if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){ Logging.err(this, "Aggrgating foreign HRMID: " + pForeignHRMID); } synchronized(mRegisteredOwnHRMIDs){ int tHierLevel = 99; //TODO: final value here // iterate over all local HRMIDs for(HRMID tLocalHRMID : mRegisteredOwnHRMIDs){ // ignore cluster addresses if(!tLocalHRMID.isClusterAddress()){ /** * Is the potentially foreign HRMID a local one? */ if(tLocalHRMID.equals(pForeignHRMID)){ if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){ Logging.err(this, " ..found matching local HRMID: " + tLocalHRMID); } tResult = pForeignHRMID; break; } /** * Determine the foreign cluster in relation to current local HRMID */ HRMID tForeignCluster = tLocalHRMID.getForeignCluster(pForeignHRMID); if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){ Logging.err(this, " ..foreign cluster of " + pForeignHRMID + " for " + tLocalHRMID + " is " + tForeignCluster); } /** * Update the result value */ if((tResult == null) || (tHierLevel > tForeignCluster.getHierarchyLevel())){ tHierLevel = tForeignCluster.getHierarchyLevel(); tResult = tForeignCluster; if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){ Logging.err(this, " ..found better result: " + tResult); } } } } } if(HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_AGGREGATION){ Logging.err(this, " ..result: " + tResult); } return tResult; } /** * Adds an entry to the routing table of the local HRS instance. * In opposite to addHRMRoute() from the HierarchicalRoutingService class, this function additionally updates the GUI. * If the L2 address of the next hop is defined, the HRS will update the HRMID-to-L2ADDRESS mapping. * * @param pRoutingEntry the new routing entry * * @return true if the entry had new routing data */ private int mCallsAddHRMRoute = 0; public boolean addHRMRoute(RoutingEntry pRoutingEntry) { boolean tResult = false; mCallsAddHRMRoute++; Logging.log(this, "Adding (" + mCallsAddHRMRoute + ") HRM routing table entry: " + pRoutingEntry); // filter invalid destinations if(pRoutingEntry.getDest() == null){ throw new RuntimeException(this + "::addHRMRoute() detected an invalid destination in routing entry: " + pRoutingEntry); } // filter invalid next hop if(pRoutingEntry.getNextHop() == null){ throw new RuntimeException(this + "::addHRMRoute() detected an invalid next hop in routing entry: " + pRoutingEntry); } // plausibility check if((!pRoutingEntry.getDest().isClusterAddress()) && (!pRoutingEntry.getDest().equals(pRoutingEntry.getNextHop()))){ throw new RuntimeException(this + "::addHRMRoute() detected an invalid destination (should be equal to the next hop) in routing entry: " + pRoutingEntry); } /** * Inform the HRS about the new route */ tResult = getHRS().addHRMRoute(pRoutingEntry); /** * Update the hierarchical routing graph (HRG) */ if(tResult){ // record the cause for the routing entry pRoutingEntry.extendCause(this + "::addHRMRoute()"); HRMID tDestHRMID = pRoutingEntry.getDest(); /** * Ignore local loops */ if(!pRoutingEntry.isLocalLoop()){ /** * Does the next hop lead to a foreign cluster? */ if(tDestHRMID.isClusterAddress()){ // is it a route from a physical node to the next one, which belongs to the destination cluster? if(pRoutingEntry.isRouteToDirectNeighbor()){ // register automatically new links in the HRG based on pRoutingEntry registerAutoHRG(pRoutingEntry); } }else{ pRoutingEntry.extendCause(this + "::addHRMRoute()_2"); if(HRMConfig.DebugOutput.GUI_SHOW_HRG_UPDATES){ Logging.log(this, " ..registering (" + mCallsAddHRMRoute + ") nodeHRMID-2-nodeHRMID HRG link for: " + pRoutingEntry); } registerLinkHRG(pRoutingEntry.getSource(), pRoutingEntry.getNextHop(), pRoutingEntry); } }else{ /** * Local loop */ } }else{ if(HRMConfig.DebugOutput.GUI_SHOW_HRG_UPDATES){ Logging.warn(this, " ..ignoring for HRG the old HRM routing table entry: " + pRoutingEntry); } } /** * Notify GUI */ if(tResult){ // it's time to update the GUI notifyGUI(this); } return tResult; } /** * Registers automatically new links in the HRG based on a given routing table entry * * @param pRoutingEntry the routing table entry */ public void registerAutoHRG(RoutingEntry pRoutingEntry) { HRMID tDestHRMID = pRoutingEntry.getDest(); if(tDestHRMID != null){ HRMID tGeneralizedSourceHRMID = tDestHRMID.getForeignCluster(pRoutingEntry.getSource()); // get the hierarchy level at which this link connects two clusters int tLinkHierLvl = tGeneralizedSourceHRMID.getHierarchyLevel(); // initialize the source cluster HRMID HRMID tSourceClusterHRMID = pRoutingEntry.getSource().clone(); // initialize the destination cluster HRMID HRMID tDestClusterHRMID = pRoutingEntry.getNextHop().clone(); for(int i = 0; i <= tLinkHierLvl; i++){ // reset the value for the corresponding hierarchy level for both the source and destination cluster HRMID tSourceClusterHRMID.setLevelAddress(i, 0); tDestClusterHRMID.setLevelAddress(i, 0); if(!tSourceClusterHRMID.equals(tDestClusterHRMID)){ if(HRMConfig.DebugOutput.GUI_SHOW_HRG_UPDATES){ Logging.log(this, " ..registering (" + mCallsAddHRMRoute + ") cluster-2-cluster (lvl: " + i + ") HRG link from " + tSourceClusterHRMID + " to " + tDestClusterHRMID + " for: " + pRoutingEntry); } RoutingEntry tRoutingEntry = RoutingEntry.create(pRoutingEntry.getSource(), tDestClusterHRMID, pRoutingEntry.getNextHop(), RoutingEntry.NO_HOP_COSTS, RoutingEntry.NO_UTILIZATION, RoutingEntry.NO_DELAY, RoutingEntry.INFINITE_DATARATE, pRoutingEntry.getCause() + ", " + this + "::registerAutoHRG()"); registerCluster2ClusterLinkHRG(tSourceClusterHRMID, tDestClusterHRMID, tRoutingEntry); } } } } /** * Adds a table to the routing table of the local HRS instance. * In opposite to addHRMRoute() from the HierarchicalRoutingService class, this function additionally updates the GUI. * If the L2 address of the next hop is defined, the HRS will update the HRMID-to-L2ADDRESS mapping. * * @param pRoutingTable the routing table with new entries * * @return true if the table had new routing data */ public boolean addHRMRoutes(RoutingTable pRoutingTable) { boolean tResult = false; for(RoutingEntry tEntry : pRoutingTable){ tResult |= addHRMRoute(tEntry); } return tResult; } /** * Deletes a route from the local HRM routing table. * * @param pRoutingTableEntry the routing table entry * * @return true if the entry was found and removed, otherwise false */ private boolean delHRMRoute(RoutingEntry pRoutingEntry) { boolean tResult = false; Logging.log(this, "Deleting HRM routing table entry: " + pRoutingEntry); /** * Inform the HRS about the new route */ tResult = getHRS().delHRMRoute(pRoutingEntry); /** * Update the hierarchical routing graph (HRG) */ if(tResult){ HRMID tDestHRMID = pRoutingEntry.getDest(); // do we have a local loop? if(!pRoutingEntry.isLocalLoop()){ /** * No local loop */ if(tDestHRMID.isClusterAddress()){ if(pRoutingEntry.isRouteToDirectNeighbor()){ // register automatically new links in the HRG based on pRoutingEntry unregisterAutoHRG(pRoutingEntry); } }else{ pRoutingEntry.extendCause(this + "::delHRMRoute()"); Logging.log(this, " ..unregistering nodeHRMID-2-nodeHRMID HRG link for: " + pRoutingEntry); unregisterLinkHRG(pRoutingEntry.getSource(), pRoutingEntry.getNextHop(), pRoutingEntry); } } } /** * Notify GUI */ if(tResult){ // it's time to update the GUI notifyGUI(this); } return tResult; } /** * Unregisters automatically old links from the HRG based on a given routing table entry * * @param pRoutingEntry the routing table entry */ public void unregisterAutoHRG(RoutingEntry pRoutingEntry) { HRMID tDestHRMID = pRoutingEntry.getDest(); if(tDestHRMID != null){ HRMID tGeneralizedSourceHRMID = tDestHRMID.getForeignCluster(pRoutingEntry.getSource()); // get the hierarchy level at which this link connects two clusters int tLinkHierLvl = tGeneralizedSourceHRMID.getHierarchyLevel(); // initialize the source cluster HRMID HRMID tSourceClusterHRMID = pRoutingEntry.getSource().clone(); // initialize the destination cluster HRMID HRMID tDestClusterHRMID = pRoutingEntry.getNextHop().clone(); for(int i = 0; i <= tLinkHierLvl; i++){ // reset the value for the corresponding hierarchy level for both the source and destination cluster HRMID tSourceClusterHRMID.setLevelAddress(i, 0); tDestClusterHRMID.setLevelAddress(i, 0); if(!tSourceClusterHRMID.equals(tDestClusterHRMID)){ if(HRMConfig.DebugOutput.GUI_SHOW_HRG_UPDATES){ Logging.log(this, " ..unregistering (" + mCallsAddHRMRoute + ") cluster-2-cluster (lvl: " + i + ") HRG link from " + tSourceClusterHRMID + " to " + tDestClusterHRMID + " for: " + pRoutingEntry); } RoutingEntry tRoutingEntry = RoutingEntry.create(pRoutingEntry.getSource(), tDestClusterHRMID, pRoutingEntry.getNextHop(), RoutingEntry.NO_HOP_COSTS, RoutingEntry.NO_UTILIZATION, RoutingEntry.NO_DELAY, RoutingEntry.INFINITE_DATARATE, pRoutingEntry.getCause() + ", " + this + "::unregisterAutoHRG()"); unregisterCluster2ClusterLinkHRG(tSourceClusterHRMID, tDestClusterHRMID, tRoutingEntry); } } } } /** * Removes a table from the routing table of the local HRS instance. * * @param pRoutingTable the routing table with old entries * * @return true if the table had existing routing data */ public boolean delHRMRoutes(RoutingTable pRoutingTable) { boolean tResult = false; for(RoutingEntry tEntry : pRoutingTable){ tResult |= delHRMRoute(tEntry); } return tResult; } /** * Adds a route to the local L2 routing table. * * @param pToL2Address the L2Address of the destination * @param pRoute the route to the direct neighbor */ public void registerLinkL2(L2Address pToL2Address, Route pRoute) { if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, "REGISTERING LINK (L2):\n DEST.=" + pToL2Address + "\n LINK=" + pRoute); } // inform the HRS about the new route if(getHRS().registerLinkL2(pToL2Address, pRoute)){ // it's time to update the GUI notifyGUI(this); } } /** * Connects to a service with the given name. Method blocks until the connection has been set up. * * @param pDestination the connection destination * @param pRequirements the requirements for the connection * @param pIdentity the identity of the connection requester * * @return the created connection * * @throws NetworkException */ private Connection connectBlock(Name pDestination, Description pRequirements, Identity pIdentity) throws NetworkException { Logging.log(this, "\n\n\n========> OUTGOING CONNECTION REQUEST TO: " + pDestination + " with requirements: " + pRequirements); // connect Connection tConnection = getLayer().connect(pDestination, pRequirements, pIdentity); Logging.log(this, " ..=====> got connection: " + tConnection); // create blocking event handler BlockingEventHandling tBlockingEventHandling = new BlockingEventHandling(tConnection, 1); // wait for the first event Event tEvent = tBlockingEventHandling.waitForEvent(); Logging.log(this, " ..=====> got connection event: " + tEvent); if(tEvent instanceof ConnectedEvent) { if(!tConnection.isConnected()) { throw new NetworkException(this, "Connected event but connection is not connected."); } else { return tConnection; } }else if(tEvent instanceof ErrorEvent) { Exception exc = ((ErrorEvent) tEvent).getException(); if(exc instanceof NetworkException) { throw (NetworkException) exc; } else { throw new NetworkException(this, "Can not connect to " + pDestination +".", exc); } }else{ throw new NetworkException(this, "Can not connect to " + pDestination +" due to " + tEvent); } } /** * Marks the FoGSiEm simulation creation as finished. */ public static void simulationCreationHasFinished() { mFoGSiEmSimulationCreationFinished = true; } /** * Checks if the entire simulation was created * * @return true or false */ private boolean simulationCreationFinished() { return mFoGSiEmSimulationCreationFinished; } /** * Determines the Cluster object (on hierarchy level 0) for a given network interface * * @param pInterface the network interface * * @return the found Cluster object, null if nothing was found */ private Cluster getBaseHierarchyLevelCluster(NetworkInterface pInterface) { Cluster tResult = null; LinkedList<Cluster> tBaseClusters = getAllClusters(HierarchyLevel.BASE_LEVEL); for (Cluster tCluster : tBaseClusters){ NetworkInterface tClusterNetIf = tCluster.getBaseHierarchyLevelNetworkInterface(); if ((pInterface == tClusterNetIf) || (pInterface.equals(tCluster.getBaseHierarchyLevelNetworkInterface()))){ tResult = tCluster; } } return tResult; } /** * Determines the hierarchy node priority for Election processes * * @return the hierarchy node priority */ public long getHierarchyNodePriority(HierarchyLevel pLevel) { if (HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY){ // the used hierarchy level is always "1" above of the one from the causing entity int tHierLevel = pLevel.getValue(); if (!HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL){ // always use L1 tHierLevel = 1; } return mNodeHierarchyPriority[tHierLevel]; }else{ return getConnectivityNodePriority(); } } /** * Determines the connectivity node priority for Election processes * * @return the connectivity node priority */ public long getConnectivityNodePriority() { return mNodeConnectivityPriority; } /** * Sets new connectivity node priority for Election processes * * @param pPriority the new connectivity node priority */ private int mConnectivityPriorityUpdates = 0; private synchronized void setConnectivityPriority(long pPriority) { Logging.log(this, "Setting new connectivity node priority: " + pPriority); mNodeConnectivityPriority = pPriority; mConnectivityPriorityUpdates++; /** * Inform all local cluster members at level 0 about the change * HINT: we have to enforce a permanent lock of mLocalClusterMembers, * otherwise race conditions might be caused (another ClusterMemeber * could be created while we are updating the priorities of all the * formerly known ones) */ synchronized (mLocalClusterMembers) { Logging.log(this, " ..informing about the priority (" + pPriority + ") update (" + mConnectivityPriorityUpdates + ")"); int i = 0; for(ClusterMember tClusterMember : mLocalClusterMembers){ // only base hierarchy level! if(tClusterMember.getHierarchyLevel().isBaseLevel()){ Logging.log(this, " ..update (" + mConnectivityPriorityUpdates + ") - informing[" + i + "]: " + tClusterMember); tClusterMember.eventConnectivityNodePriorityUpdate(getConnectivityNodePriority()); i++; } } } } /** * Sets new hierarchy node priority for Election processes * * @param pPriority the new hierarchy node priority */ private int mHierarchyPriorityUpdates = 0; private synchronized void setHierarchyPriority(long pPriority, HierarchyLevel pLevel) { Logging.log(this, "Setting new hierarchy node priority: " + pPriority); mNodeHierarchyPriority[pLevel.getValue()] = pPriority; mHierarchyPriorityUpdates++; /** * Inform all local CoordinatorAsClusterMemeber objects about the change * HINT: we have to enforce a permanent lock of mLocalCoordinatorAsClusterMemebers, * otherwise race conditions might be caused (another CoordinatorAsClusterMemeber * could be created while we are updating the priorities of all the * formerly known ones) */ synchronized (mLocalCoordinatorAsClusterMemebers) { Logging.log(this, " ..informing about the priority (" + pPriority + ") update (" + mHierarchyPriorityUpdates + ")"); int i = 0; for(CoordinatorAsClusterMember tCoordinatorAsClusterMember : mLocalCoordinatorAsClusterMemebers){ if((tCoordinatorAsClusterMember.getHierarchyLevel().equals(pLevel)) || (!HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL)){ Logging.log(this, " ..update (" + mHierarchyPriorityUpdates + ") - informing[" + i + "]: " + tCoordinatorAsClusterMember); tCoordinatorAsClusterMember.eventHierarchyNodePriorityUpdate(getHierarchyNodePriority(pLevel)); i++; } } } } /** * Increases base Bully priority * * @param pCausingInterfaceToNeighbor the update causing interface to a neighbor */ private synchronized void increaseNodePriority_Connectivity(NetworkInterface pCausingInterfaceToNeighbor) { // get the current priority long tPriority = getConnectivityNodePriority(); Logging.log(this, "Increasing node priority (CONNECTIVITY) by " + BullyPriority.OFFSET_FOR_CONNECTIVITY); // increase priority tPriority += BullyPriority.OFFSET_FOR_CONNECTIVITY; mDesriptionConnectivityPriorityUpdates += "\n + " + BullyPriority.OFFSET_FOR_CONNECTIVITY + " ==> " + pCausingInterfaceToNeighbor; // update priority setConnectivityPriority(tPriority); Logging.log(this, "Increasing hierarchy node priority (CONNECTIVITY) by " + BullyPriority.OFFSET_FOR_CONNECTIVITY); // get the current priority long tHierarchyPriority = mNodeHierarchyPriority[1]; // increase priority tHierarchyPriority += BullyPriority.OFFSET_FOR_CONNECTIVITY; mDesriptionHierarchyPriorityUpdates += "\n + " + BullyPriority.OFFSET_FOR_CONNECTIVITY + " <== Cause: " + pCausingInterfaceToNeighbor; // update priority setHierarchyPriority(tHierarchyPriority, new HierarchyLevel(this, 1)); } /** * Decreases base Bully priority * * @param pCausingInterfaceToNeighbor the update causing interface to a neighbor */ private synchronized void decreaseNodePriority_Connectivity(NetworkInterface pCausingInterfaceToNeighbor) { // get the current priority long tPriority = getConnectivityNodePriority(); Logging.log(this, "Decreasing node priority (CONNECTIVITY) by " + BullyPriority.OFFSET_FOR_CONNECTIVITY); // increase priority tPriority -= BullyPriority.OFFSET_FOR_CONNECTIVITY; mDesriptionConnectivityPriorityUpdates += "\n - " + BullyPriority.OFFSET_FOR_CONNECTIVITY + " ==> " + pCausingInterfaceToNeighbor; // update priority setConnectivityPriority(tPriority); Logging.log(this, "Decreasing hierarchy node priority (CONNECTIVITY) by " + BullyPriority.OFFSET_FOR_CONNECTIVITY); // get the current priority long tHierarchyPriority = mNodeHierarchyPriority[1]; // increase priority tHierarchyPriority -= BullyPriority.OFFSET_FOR_CONNECTIVITY; mDesriptionHierarchyPriorityUpdates += "\n - " + BullyPriority.OFFSET_FOR_CONNECTIVITY + " <== Cause: " + pCausingInterfaceToNeighbor; // update priority setHierarchyPriority(tHierarchyPriority, new HierarchyLevel(this, 1)); } /** * Increases hierarchy Bully priority * * @param pCausingEntity the update causing entity */ public void increaseHierarchyNodePriority_KnownBaseCoordinator(ControlEntity pCausingEntity) { /** * Are we at base hierarchy level or should we accept all levels? */ if((pCausingEntity.getHierarchyLevel().isBaseLevel()) || (HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL)){ // the used hierarchy level is always "1" above of the one from the causing entity int tHierLevel = pCausingEntity.getHierarchyLevel().getValue() + 1; if (!HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL){ // always use L1 tHierLevel = 1; } int tDistance = 0; if(pCausingEntity instanceof CoordinatorProxy){ tDistance = ((CoordinatorProxy)pCausingEntity).getDistance(); } int tMaxDistance = HRMConfig.Hierarchy.EXPANSION_RADIUS; if(!pCausingEntity.getHierarchyLevel().isBaseLevel()){ tMaxDistance = 256; //TODO: use a definition here } if((tDistance >= 0) && (tDistance <= tMaxDistance)){ // get the current priority long tPriority = mNodeHierarchyPriority[tHierLevel]; float tOffset = 0; if (pCausingEntity.getHierarchyLevel().isBaseLevel()){ tOffset = (float)BullyPriority.OFFSET_FOR_KNOWN_BASE_REMOTE_L0_COORDINATOR * (2 + tMaxDistance - tDistance); }else{ tOffset = (float)BullyPriority.OFFSET_FOR_KNOWN_BASE_REMOTE_L1p_COORDINATOR * (2 + tMaxDistance - tDistance); } Logging.log(this, "Increasing hierarchy node priority (KNOWN BASE COORDINATOR) by " + (long)tOffset + ", distance=" + tDistance + "/" + tMaxDistance); // increase priority tPriority += (long)(tOffset); mDesriptionHierarchyPriorityUpdates += "\n + " + tOffset + " <== HOPS: " + tDistance + "/" + tMaxDistance + ", Cause: " + pCausingEntity; // update priority setHierarchyPriority(tPriority, new HierarchyLevel(this, tHierLevel)); }else{ Logging.err(this, "Detected invalid distance: " + tDistance + "/" + tMaxDistance); } } } /** * Decreases hierarchy Bully priority * * @param pCausingEntity the update causing entity */ public void decreaseHierarchyNodePriority_KnownBaseCoordinator(ControlEntity pCausingEntity) { /** * Are we at base hierarchy level or should we accept all levels? */ if((pCausingEntity.getHierarchyLevel().isBaseLevel()) || (HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL)){ // the used hierarchy level is always "1" above of the one from the causing entity int tHierLevel = pCausingEntity.getHierarchyLevel().getValue() + 1; if (!HRMConfig.Hierarchy.USE_SEPARATE_HIERARCHY_NODE_PRIORITY_PER_LEVEL){ // always use L1 tHierLevel = 1; } int tDistance = 0; if(pCausingEntity instanceof CoordinatorProxy){ tDistance = ((CoordinatorProxy)pCausingEntity).getDistance(); } int tMaxDistance = HRMConfig.Hierarchy.EXPANSION_RADIUS; if(!pCausingEntity.getHierarchyLevel().isBaseLevel()){ tMaxDistance = 256; //TODO: use a definition here } if((tDistance >= 0) && (tDistance <= tMaxDistance)){ // get the current priority long tPriority = mNodeHierarchyPriority[tHierLevel]; float tOffset = 0; if (pCausingEntity.getHierarchyLevel().isBaseLevel()){ tOffset = (float)BullyPriority.OFFSET_FOR_KNOWN_BASE_REMOTE_L0_COORDINATOR * (2 + tMaxDistance - tDistance); }else{ tOffset = (float)BullyPriority.OFFSET_FOR_KNOWN_BASE_REMOTE_L1p_COORDINATOR * (2 + tMaxDistance - tDistance); } Logging.log(this, "Decreasing hierarchy node priority (KNOWN BASE COORDINATOR) by " + (long)tOffset + ", distance=" + tDistance + "/" + tMaxDistance); // decrease priority tPriority -= (long)(tOffset); mDesriptionHierarchyPriorityUpdates += "\n - " + tOffset + " <== HOPS: " + tDistance + "/" + tMaxDistance + ", Cause: " + pCausingEntity; // update priority setHierarchyPriority(tPriority, new HierarchyLevel(this, tHierLevel)); }else{ Logging.err(this, "Detected invalid distance: " + tDistance + "/" + tMaxDistance); } } } /** * Returns a description about all connectivity priority updates. * This function is only used within the GUI. It is not part of the concept. * * @return the description */ public String getGUIDescriptionConnectivityPriorityUpdates() { return mDesriptionConnectivityPriorityUpdates; } /** * Returns a description about all HRMID updates. * * @return the description */ public String getGUIDescriptionHRMIDChanges() { return mDescriptionHRMIDUpdates; } /** * Returns a description about all HRG updates. * * @return the description */ public String getGUIDescriptionHRGChanges() { return mDescriptionHRGUpdates; } /** * Returns a description about all hierarchy priority updates * This function is only used within the GUI. It is not part of the concept. * * @return the description */ public String getGUIDescriptionHierarchyPriorityUpdates() { return mDesriptionHierarchyPriorityUpdates; } /** * Returns a log about "update cluster" events * This function is only used within the GUI. It is not part of the concept. * * @return the description */ public String getGUIDescriptionClusterUpdates() { return mProcessorThread.getGUIDescriptionClusterUpdates(); } /** * Returns a description about all used cluster addresses * * @return the description */ public String getGUIDEscriptionUsedAddresses() { String tResult = ""; LinkedList<Cluster> tAllClusters = getAllClusters(); for (Cluster tCluster : tAllClusters){ tResult += "\n .." + tCluster + " uses these addresses:"; LinkedList<Integer> tUsedAddresses = tCluster.getUsedAddresses(); int i = 0; for (int tUsedAddress : tUsedAddresses){ tResult += "\n ..[" + i + "]: " + tUsedAddress; i++; } LinkedList<ComChannel> tAllClusterChannels = tCluster.getComChannels(); tResult += "\n .." + tCluster + " channels:"; i = 0; for(ComChannel tComChannel : tAllClusterChannels){ tResult += "\n ..[" + i + "]: " + tComChannel; i++; } } return tResult; } /** * Reacts on a lost physical neighbor. * HINT: "pNeighborL2Address" doesn't correspond to the neighbor's central FN! * * @param pInterfaceToNeighbor the network interface to the neighbor * @param pNeighborL2Address the L2 address of the detected physical neighbor's first FN towards the common bus. */ public synchronized void eventLostPhysicalNeighborNode(final NetworkInterface pInterfaceToNeighbor, L2Address pNeighborL2Address) { Logging.log(this, "\n\n\n############## LOST DIRECT NEIGHBOR NODE " + pNeighborL2Address + ", interface=" + pInterfaceToNeighbor); synchronized (mCommunicationSessions) { Logging.log(this, " ..known sessions: " + mCommunicationSessions); for (ComSession tComSession : mCommunicationSessions){ if(tComSession.isPeer(pNeighborL2Address)){ Logging.log(this, " ..stopping session: " + tComSession); tComSession.stopConnection(); }else{ Logging.log(this, " ..leaving session: " + tComSession); } } } synchronized (mLocalNetworkInterfaces) { if(mLocalNetworkInterfaces.contains(pInterfaceToNeighbor)){ Logging.log(this, "\n######### Detected lost network interface: " + pInterfaceToNeighbor); mLocalNetworkInterfaces.remove(pInterfaceToNeighbor); //TODO: multiple nodes!? } decreaseNodePriority_Connectivity(pInterfaceToNeighbor); } // updates the GUI decoration for this node updateGUINodeDecoration(); } /** * Reacts on a detected new physical neighbor. A new connection to this neighbor is created. * HINT: "pNeighborL2Address" doesn't correspond to the neighbor's central FN! * * @param pInterfaceToNeighbor the network interface to the neighbor * @param pNeighborL2Address the L2 address of the detected physical neighbor's first FN towards the common bus. */ public synchronized void eventDetectedPhysicalNeighborNode(final NetworkInterface pInterfaceToNeighbor, final L2Address pNeighborL2Address) { Logging.log(this, "\n\n\n############## FOUND DIRECT NEIGHBOR NODE " + pNeighborL2Address + ", interface=" + pInterfaceToNeighbor); /** * Helper for having access to the HRMController within the created thread */ final HRMController tHRMController = this; /** * Create connection thread */ Thread tThread = new Thread() { public String toString() { return tHRMController.toString(); } public void run() { Thread.currentThread().setName("NeighborConnector@" + tHRMController.getNodeGUIName() + " for " + pNeighborL2Address); /** * Create/get the cluster on base hierarchy level */ Cluster tParentCluster = null; synchronized (mLocalNetworkInterfaces) { if(!mLocalNetworkInterfaces.contains(pInterfaceToNeighbor)){ Logging.log(this, "\n######### Detected new network interface: " + pInterfaceToNeighbor); mLocalNetworkInterfaces.add(pInterfaceToNeighbor); } //HINT: we make sure that we use only one Cluster object per Bus Cluster tExistingCluster = getBaseHierarchyLevelCluster(pInterfaceToNeighbor); if (tExistingCluster != null){ Logging.log(this, " ..using existing level0 cluster: " + tExistingCluster); tParentCluster = tExistingCluster; }else{ Logging.log(this, " ..knowing level0 clusters: " + getAllClusters(0)); Logging.log(this, " ..creating new level0 cluster"); tParentCluster = Cluster.createBaseCluster(tHRMController); tParentCluster.setBaseHierarchyLevelNetworkInterface(pInterfaceToNeighbor); increaseNodePriority_Connectivity(pInterfaceToNeighbor); // updates the GUI decoration for this node updateGUINodeDecoration(); } } /** * Create communication session */ Logging.log(this, " ..get/create communication session"); ComSession tComSession = getCreateComSession(pNeighborL2Address); if(tComSession != null) { /** * Update ARG */ //mHRMController.registerLinkARG(this, tParentCluster, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.REMOTE_CONNECTION)); /** * Create communication channel */ Logging.log(this, " ..creating new communication channel"); ComChannel tComChannel = new ComChannel(tHRMController, ComChannel.Direction.OUT, tParentCluster, tComSession); tComChannel.setRemoteClusterName(tParentCluster.createClusterName()); /** * Send "RequestClusterMembership" along the comm. session * HINT: we cannot use the created channel because the remote side doesn't know anything about the new comm. channel yet) */ RequestClusterMembership tRequestClusterMembership = new RequestClusterMembership(getNodeName(), pNeighborL2Address, tParentCluster.createClusterName(), tParentCluster.createClusterName()); Logging.log(this, " ..sending membership request: " + tRequestClusterMembership); if (tComSession.write(tRequestClusterMembership)){ Logging.log(this, " ..requested sucessfully for membership of: " + tParentCluster + " at node " + pNeighborL2Address); }else{ Logging.log(this, " ..failed to request for membership of: " + tParentCluster + " at node " + pNeighborL2Address); } Logging.log(this, "Connection thread for " + pNeighborL2Address + " finished"); }else{ Logging.log(this, "Connection thread for " + pNeighborL2Address + " failed"); } } }; /** * Start the connection thread */ tThread.start(); } /** * Determines a reference to the current AutonomousSystem instance. * * @return the desired reference */ public AutonomousSystem getAS() { return mAS; } /** * Returns the node-global election state * * @return the node-global election state */ public Object getNodeElectionState() { return mNodeElectionState; } /** * Returns the node-global election state change description * This function is only used within the GUI. It is not part of the concept. * * @return the description */ public Object getGUIDescriptionNodeElectionStateChanges() { return mDescriptionNodeElectionState; } /** * Adds a description to the node-global election state change description * * @param pAdd the additive string */ public void addGUIDescriptionNodeElectionStateChange(String pAdd) { mDescriptionNodeElectionState += pAdd; } /** * Determines the current simulation time * * @return the simulation time */ public double getSimulationTime() { return mAS.getTimeBase().now(); } /* (non-Javadoc) * @see de.tuilmenau.ics.fog.IEvent#fire() */ @Override public void fire() { reportAndShare(); } /** * Triggers the "report phase" / "share phase" of all known coordinators */ private void reportAndShare() { if (HRMConfig.DebugOutput.GUI_SHOW_TIMING_ROUTE_DISTRIBUTION){ Logging.log(this, "REPORT AND SHARE TRIGGER received"); } if(HRMConfig.Routing.REPORT_TOPOLOGY_AUTOMATICALLY){ /** * report phase */ for (Coordinator tCoordinator : getAllCoordinators()) { tCoordinator.reportPhase(); } if(HRMConfig.Routing.SHARE_ROUTES_AUTOMATICALLY){ /** * share phase */ for (Coordinator tCoordinator : getAllCoordinators()) { tCoordinator.sharePhase(); } } } if(HRMConfig.Routing.REPORT_TOPOLOGY_AUTOMATICALLY){ /** * register next trigger */ mAS.getTimeBase().scheduleIn(HRMConfig.Routing.GRANULARITY_SHARE_PHASE, this); } } /** * Calculate the time period between "share phases" * * @param pHierarchyLevel the hierarchy level * @return the calculated time period */ public double getPeriodSharePhase(int pHierarchyLevelValue) { return (double) 2 * HRMConfig.Routing.GRANULARITY_SHARE_PHASE * pHierarchyLevelValue; //TODO: use an exponential time distribution here } /** * Calculate the time period between "share phases" * * @param pHierarchyLevel the hierarchy level * @return the calculated time period */ public double getPeriodReportPhase(HierarchyLevel pHierarchyLevel) { return (double) HRMConfig.Routing.GRANULARITY_SHARE_PHASE * (pHierarchyLevel.getValue() - 1); //TODO: use an exponential time distribution here } /** * This method is derived from IServerCallback. It is called by the ServerFN in order to acquire the acknowledgment from the HRMController about the incoming connection * * @param pAuths the authentications of the requesting sender * @param pRequirements the requirements for the incoming connection * @param pTargetName the registered name of the addressed target service * @return true of false */ @Override public boolean openAck(LinkedList<Signature> pAuths, Description pRequirements, Name pTargetName) { //TODO: check if a neighbor wants to explore its neighbor -> select if we want to join its cluster or not if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, "Incoming request for acknowledging the connection:"); Logging.log(this, " ..source: " + pAuths); Logging.log(this, " ..destination: " + pTargetName); Logging.log(this, " ..requirements: " + pRequirements); } return true; } /** * Helper function to get the local machine's host name. * The output of this function is useful for distributed simulations if coordinators/clusters with the name might coexist on different machines. * * @return the host name */ public static String getHostName() { String tResult = null; try{ tResult = java.net.InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException tExc) { Logging.err(null, "Unable to determine the local host name", tExc); } return tResult; } /** * Determines the L2Address of the first FN towards a neighbor. This corresponds to the FN, located between the central FN and the bus to the neighbor node. * * @param pNeighborName the name of the neighbor * @return the L2Address of the search FN */ public L2Address getL2AddressOfFirstFNTowardsNeighbor(Name pNeighborName) { L2Address tResult = null; if (pNeighborName != null){ Route tRoute = null; // get the name of the central FN L2Address tCentralFNL2Address = getHRS().getCentralFNL2Address(); // get a route to the neighbor node (the destination of the desired connection) try { tRoute = getHRS().getRoute(pNeighborName, new Description(), getNode().getIdentity()); } catch (RoutingException tExc) { Logging.err(this, "getL2AddressOfFirstFNTowardsNeighbor() is unable to find route to " + pNeighborName, tExc); } catch (RequirementsException tExc) { Logging.err(this, "getL2AddressOfFirstFNTowardsNeighbor() is unable to find route to " + pNeighborName + " with requirements no requirents, Huh!", tExc); } // have we found a route to the neighbor? if((tRoute != null) && (!tRoute.isEmpty())) { // get the first route part, which corresponds to the link between the central FN and the searched first FN towards the neighbor RouteSegmentPath tPath = (RouteSegmentPath) tRoute.getFirst(); // check if route has entries if((tPath != null) && (!tPath.isEmpty())){ // get the gate ID of the link GateID tGateID = tPath.getFirst(); RoutingServiceLink tLinkBetweenCentralFNAndFirstNodeTowardsNeighbor = null; boolean tWithoutException = false; //TODO: rework some software structures to avoid this ugly implementation while(!tWithoutException){ try{ // get all outgoing links from the central FN Collection<RoutingServiceLink> tOutgoingLinksFromCentralFN = getHRS().getOutgoingLinks(tCentralFNL2Address); // iterate over all outgoing links and search for the link from the central FN to the FN, which comes first when routing towards the neighbor for(RoutingServiceLink tLink : tOutgoingLinksFromCentralFN) { // compare the GateIDs if(tLink.equals(tGateID)) { // found! tLinkBetweenCentralFNAndFirstNodeTowardsNeighbor = tLink; } } tWithoutException = true; }catch(ConcurrentModificationException tExc){ // FoG has manipulated the topology data and called the HRS for updating the L2 routing graph continue; } } // determine the searched FN, which comes first when routing towards the neighbor HRMName tFirstNodeBeforeBusToNeighbor = getHRS().getL2LinkDestination(tLinkBetweenCentralFNAndFirstNodeTowardsNeighbor); if (tFirstNodeBeforeBusToNeighbor instanceof L2Address){ // get the L2 address tResult = (L2Address)tFirstNodeBeforeBusToNeighbor; }else{ Logging.err(this, "getL2AddressOfFirstFNTowardsNeighbor() found a first FN (" + tFirstNodeBeforeBusToNeighbor + ") towards the neighbor " + pNeighborName + " but it has the wrong class type"); } }else{ Logging.warn(this, "getL2AddressOfFirstFNTowardsNeighbor() found an empty route to \"neighbor\": " + pNeighborName); } }else{ Logging.warn(this, "Got for neighbor " + pNeighborName + " the route: " + tRoute); //HINT: this could also be a local loop -> throw only a warning } }else{ Logging.warn(this, "getL2AddressOfFirstFNTowardsNeighbor() found an invalid neighbor name"); } return tResult; } /** * This function gets called if the HRMController appl. was started */ @Override protected void started() { mApplicationStarted = true; // register in the global HRMController database synchronized (mRegisteredHRMControllers) { mRegisteredHRMControllers.add(this); } } /** * This function gets called if the HRMController appl. should exit/terminate right now */ @Override public synchronized void exit() { mApplicationStarted = false; Logging.log(this, "\n\n\n############## Exiting.."); Logging.log(this, " ..destroying clusterer-thread"); mProcessorThread.exit(); mProcessorThread = null; Logging.log(this, " ..destroying all clusters/coordinators"); for(int i = 0; i < HRMConfig.Hierarchy.HEIGHT; i++){ LinkedList<Cluster> tClusters = getAllClusters(i); for(Cluster tCluster : tClusters){ tCluster.eventClusterRoleInvalid(); } } synchronized (mCommunicationSessions) { for (ComSession tComSession : mCommunicationSessions){ tComSession.stopConnection(); } } // register in the global HRMController database Logging.log(this, " ..removing from the global HRMController database"); synchronized (mRegisteredHRMControllers) { mRegisteredHRMControllers.remove(this); } } /** * Return if the HRMController application is running * * @return true if the HRMController application is running, otherwise false */ @Override public boolean isRunning() { return mApplicationStarted; } /** * Returns the list of known HRMController instances for this physical simulation machine * * @return the list of HRMController references */ @SuppressWarnings("unchecked") public static LinkedList<HRMController> getALLHRMControllers() { LinkedList<HRMController> tResult = null; synchronized (mRegisteredHRMControllers) { tResult = (LinkedList<HRMController>) mRegisteredHRMControllers.clone(); } return tResult; } /** * Creates a Description, which directs a connection to another HRMController instance * @return the new description */ public Description createHRMControllerDestinationDescription() { Description tResult = new Description(); if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, "Creating a HRMController destination description"); } tResult.set(new DestinationApplicationProperty(HRMController.ROUTING_NAMESPACE, null, null)); return tResult; } /** * Registers a cluster/coordinator to the locally stored abstract routing graph (ARG) * * @param pNode the node (cluster/coordinator) which should be stored in the ARG */ private synchronized void registerNodeARG(ControlEntity pNode) { if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, "REGISTERING NODE ADDRESS (ARG): " + pNode ); } synchronized (mAbstractRoutingGraph) { if(!mAbstractRoutingGraph.contains(pNode)) { mAbstractRoutingGraph.add(pNode); if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, " ..added to ARG"); } }else{ if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, " ..node for ARG already known: " + pNode); } } } } /** * Unregisters a cluster/coordinator from the locally stored abstract routing graph (ARG) * * @param pNode the node (cluster/coordinator) which should be removed from the ARG */ private void unregisterNodeARG(ControlEntity pNode) { if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, "UNREGISTERING NODE ADDRESS (ARG): " + pNode ); } synchronized (mAbstractRoutingGraph) { if(mAbstractRoutingGraph.contains(pNode)) { mAbstractRoutingGraph.remove(pNode); if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, " ..removed from ARG"); } }else{ if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, " ..node for ARG wasn't known: " + pNode); } } } } /** * Registers a logical link between clusters/coordinators to the locally stored abstract routing graph (ARG) * * @param pFrom the starting point of the link * @param pTo the ending point of the link * @param pLink the link between the two nodes */ public void registerLinkARG(AbstractRoutingGraphNode pFrom, AbstractRoutingGraphNode pTo, AbstractRoutingGraphLink pLink) { if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, "REGISTERING LINK (ARG):\n SOURCE=" + pFrom + "\n DEST.=" + pTo + "\n LINK=" + pLink); } synchronized (mAbstractRoutingGraph) { mAbstractRoutingGraph.link(pFrom, pTo, pLink); } } /** * Unregisters a logical link between clusters/coordinators from the locally stored abstract routing graph (ARG) * * @param pFrom the starting point of the link * @param pTo the ending point of the link */ public void unregisterLinkARG(AbstractRoutingGraphNode pFrom, AbstractRoutingGraphNode pTo) { AbstractRoutingGraphLink tLink = getLinkARG(pFrom, pTo); if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, "UNREGISTERING LINK (ARG):\n SOURCE=" + pFrom + "\n DEST.=" + pTo + "\n LINK=" + tLink); } if(tLink != null){ synchronized (mAbstractRoutingGraph) { mAbstractRoutingGraph.unlink(tLink); } } } /** * Determines the link between two clusters/coordinators from the locally stored abstract routing graph (ARG) * * @param pFrom the starting point of the link * @param pTo the ending point of the link * * @return the link between the two nodes */ public AbstractRoutingGraphLink getLinkARG(AbstractRoutingGraphNode pFrom, AbstractRoutingGraphNode pTo) { AbstractRoutingGraphLink tResult = null; List<AbstractRoutingGraphLink> tRoute = null; synchronized (mAbstractRoutingGraph) { tRoute = mAbstractRoutingGraph.getRoute(pFrom, pTo); } if((tRoute != null) && (!tRoute.isEmpty())){ if(tRoute.size() == 1){ tResult = tRoute.get(0); }else{ /** * We haven't found a direct link - we found a multi-hop route instead. */ //Logging.warn(this, "getLinkARG() expected a route with one entry but got: \nSOURCE=" + pFrom + "\nDESTINATION: " + pTo + "\nROUTE: " + tRoute); } } return tResult; } /** * Determines a route in the locally stored abstract routing graph (ARG). * * @param pSource the source of the desired route * @param pDestination the destination of the desired route * * @return the determined route, null if no route could be found */ public List<AbstractRoutingGraphLink> getRouteARG(AbstractRoutingGraphNode pSource, AbstractRoutingGraphNode pDestination) { List<AbstractRoutingGraphLink> tResult = null; if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){ Logging.log(this, "GET ROUTE (ARG) from \"" + pSource + "\" to \"" + pDestination +"\""); } synchronized (mAbstractRoutingGraph) { tResult = mAbstractRoutingGraph.getRoute(pSource, pDestination); } if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){ Logging.log(this, " ..result: " + tResult); } return tResult; } /** * Determines the other end of a link and one known link end * * @param pKnownEnd the known end of the link * @param pLink the link * * @return the other end of the link */ public AbstractRoutingGraphNode getOtherEndOfLinkARG(AbstractRoutingGraphNode pKnownEnd, AbstractRoutingGraphLink pLink) { AbstractRoutingGraphNode tResult = null; if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){ Logging.log(this, "GET OTHER END (ARG) of link \"" + pKnownEnd + "\" connected at \"" + pKnownEnd +"\""); } synchronized (mAbstractRoutingGraph) { tResult = mAbstractRoutingGraph.getOtherEndOfLink(pKnownEnd, pLink); } if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){ Logging.log(this, " ..result: " + tResult); } return tResult; } /** * Determines all known neighbors of a cluster/coordinator, which are stored in the local abstract routing graph (ARG). * * @param pRoot the root node in the ARG * * @return a collection of found neighbor nodes */ public Collection<AbstractRoutingGraphNode> getNeighborsARG(AbstractRoutingGraphNode pRoot) { Collection<AbstractRoutingGraphNode> tResult = null; if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){ Logging.log(this, "GET NEIGHBORS (ARG) from \"" + pRoot + "\""); } synchronized (mAbstractRoutingGraph) { tResult = mAbstractRoutingGraph.getNeighbors(pRoot); } if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){ Logging.log(this, " ..result: " + tResult.size() + " entries:"); int i = 0; for (AbstractRoutingGraphNode tName : tResult){ Logging.log(this, " ..[" + i + "]: " + tName); i++; } } return tResult; } /** * Determines all vertices ordered by their distance from a given root vertex * * @param pRootCluster the root cluster from where the vertices are determined * * @return a list of found vertices */ public List<AbstractRoutingGraphNode> getNeighborClustersOrderedByRadiusInARG(Cluster pRootCluster) { List<AbstractRoutingGraphNode> tResult = null; if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){ Logging.log(this, "GET VERTICES ORDERED BY RADIUS (ARG) from \"" + pRootCluster + "\""); } /** * Query for neighbors stored in within the ARG */ synchronized (mAbstractRoutingGraph) { tResult = mAbstractRoutingGraph.getVerticesInOrderRadius(pRootCluster); } /** * Remove the root cluster */ tResult.remove(pRootCluster); if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){ Logging.log(this, " ..result: " + tResult.size() + " entries:"); int i = 0; for (AbstractRoutingGraphNode tName : tResult){ Logging.log(this, " ..[" + i + "]: " + tName); i++; } } return tResult; } /** * Checks if two nodes in the locally stored abstract routing graph are linked. * * @param pFirst first node * @param pSecond second node * * @return true or false */ public boolean isLinkedARG(ClusterName pFirst, ClusterName pSecond) { boolean tResult = false; if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){ Logging.log(this, "IS LINK (ARG) from \"" + pFirst + "\" to \"" + pSecond +"\""); } synchronized (mAbstractRoutingGraph) { tResult = mAbstractRoutingGraph.isLinked(pFirst, pSecond); } if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){ Logging.log(this, " ..result: " + tResult); } return tResult; } /** * Checks if a node is locally stored in the abstract routing graph * * @param pNodeARG a possible node of the ARG * * @return true or false */ public boolean isKnownARG(ControlEntity pNodeARG) { boolean tResult = false; if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){ Logging.log(this, "IS KNOWN (ARG): \"" + pNodeARG + "\""); } synchronized (mAbstractRoutingGraph) { tResult = mAbstractRoutingGraph.contains(pNodeARG); } if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){ Logging.log(this, " ..result: " + tResult); } return tResult; } /** * Returns the ARG for the GraphViewer. * (only for GUI!) * * @return the ARG */ public AbstractRoutingGraph<AbstractRoutingGraphNode, AbstractRoutingGraphLink> getARGForGraphViewer() { AbstractRoutingGraph<AbstractRoutingGraphNode, AbstractRoutingGraphLink> tResult = null; synchronized (mAbstractRoutingGraph) { tResult = mAbstractRoutingGraph; //TODO: use a new clone() method here } return tResult; } /** * Registers an HRMID to the locally stored hierarchical routing graph (HRG) * * @param pNode the node (HRMID) which should be stored in the HRG * @param pCause the cause for this HRG update */ private synchronized void registerNodeHRG(HRMID pNode, String pCause) { if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, "REGISTERING NODE ADDRESS (HRG): " + pNode ); } if(pNode.isZero()){ throw new RuntimeException(this + " detected a zero HRMID for an HRG registration"); } synchronized (mHierarchicalRoutingGraph) { if(!mHierarchicalRoutingGraph.contains(pNode)) { mDescriptionHRGUpdates += "\n + " + pNode + " <== " + pCause; mHierarchicalRoutingGraph.add(pNode); if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, " ..added to HRG"); } }else{ mDescriptionHRGUpdates += "\n +/- " + pNode + " <== " + pCause; if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, " ..node for HRG already known: " + pNode); } } } } /** * Unregisters an HRMID from the locally stored hierarchical routing graph (HRG) * * @param pNode the node (HRMID) which should be removed from the HRG * @param pCause the cause for this HRG update */ private void unregisterNodeHRG(HRMID pNode, String pCause) { if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, "UNREGISTERING NODE ADDRESS (HRG): " + pNode ); } synchronized (mHierarchicalRoutingGraph) { if(mHierarchicalRoutingGraph.contains(pNode)) { mDescriptionHRGUpdates += "\n - " + pNode + " ==> " + pCause; mHierarchicalRoutingGraph.remove(pNode); if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, " ..removed from HRG"); } }else{ mDescriptionHRGUpdates += "\n -/+ " + pNode + " <== " + pCause; if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, " ..node for HRG wasn't known: " + pNode); } } } } /** * Registers a logical link between HRMIDs to the locally stored hierarchical routing graph (HRG) * * @param pFrom the starting point of the link * @param pTo the ending point of the link * @param pRoutingEntry the routing entry for this link * * @return true if the link is new to the routing graph */ public boolean registerLinkHRG(HRMID pFrom, HRMID pTo, RoutingEntry pRoutingEntry) { boolean tResult = false; if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, "REGISTERING LINK (HRG):\n SOURCE=" + pFrom + "\n DEST.=" + pTo + "\n ROUTE=" + pRoutingEntry); } if(!pFrom.equals(pTo)){ /** * Derive the link */ pRoutingEntry.assignToHRG(mHierarchicalRoutingGraph); AbstractRoutingGraphLink tLink = new AbstractRoutingGraphLink(new Route(pRoutingEntry)); /** * Do the actual linking */ synchronized (mHierarchicalRoutingGraph) { boolean tLinkAlreadyKnown = false; Collection<AbstractRoutingGraphLink> tLinks = mHierarchicalRoutingGraph.getOutEdges(pFrom); if(tLinks != null){ for(AbstractRoutingGraphLink tKnownLink : tLinks){ // check if both links are equal if(tKnownLink.equals(tLink)){ // check of the end points of the already known link are equal to the pFrom/pTo Pair<HRMID> tEndPoints = mHierarchicalRoutingGraph.getEndpoints(tKnownLink); if (((tEndPoints.getFirst().equals(pFrom)) && (tEndPoints.getSecond().equals(pTo))) || ((tEndPoints.getFirst().equals(pTo)) && (tEndPoints.getSecond().equals(pFrom)))){ tKnownLink.incRefCounter(); tLinkAlreadyKnown = true; // it's time to update the HRG-GUI notifyHRGGUI(tKnownLink); } } } } if(!tLinkAlreadyKnown){ mDescriptionHRGUpdates += "\n + " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString(); mHierarchicalRoutingGraph.link(pFrom.clone(), pTo.clone(), tLink); // it's time to update the HRG-GUI notifyHRGGUI(tLink); }else{ /** * The link is already known -> this can occur if both end points are located on this node and both of them try to register the same route */ mDescriptionHRGUpdates += "\n +" + (tLinkAlreadyKnown ? "(REF)" : "") + " " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString(); } tResult = true; } }else{ //Logging.warn(this, "registerLinkHRG() skipped because self-loop detected for: " + pRoutingEntry); } return tResult; } /** * Unregisters a logical link between HRMIDs from the locally stored hierarchical routing graph (HRG) * * @param pFrom the starting point of the link * @param pTo the ending point of the link * @param pRoutingEntry the routing entry of the addressed link */ public boolean unregisterLinkHRG(HRMID pFrom, HRMID pTo, RoutingEntry pRoutingEntry) { boolean tResult = false; if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, "UNREGISTERING LINK (HRG):\n SOURCE=" + pFrom + "\n DEST.=" + pTo + "\n LINK=" + pRoutingEntry); } if(!pFrom.equals(pTo)){ pRoutingEntry.assignToHRG(mHierarchicalRoutingGraph); AbstractRoutingGraphLink tSearchPattern = new AbstractRoutingGraphLink(new Route(pRoutingEntry)); boolean tChangedRefCounter = false; synchronized (mHierarchicalRoutingGraph) { //Logging.warn(this, " ..knowing node: " + pFrom + " as " + mHierarchicalRoutingGraph.containsVertex(pFrom)); // get all outgoing HRG links of "pFrom" Collection<AbstractRoutingGraphLink> tOutLinks = mHierarchicalRoutingGraph.getOutEdges(pFrom); if(tOutLinks != null){ // iterate over all found links for(AbstractRoutingGraphLink tKnownLink : tOutLinks) { //Logging.warn(this, " ..has link: " + tKnownLink); Pair<HRMID> tEndPoints = mHierarchicalRoutingGraph.getEndpoints(tKnownLink); if (((tEndPoints.getFirst().equals(pFrom)) && (tEndPoints.getSecond().equals(pTo))) || ((tEndPoints.getFirst().equals(pTo)) && (tEndPoints.getSecond().equals(pFrom)))){ if(tKnownLink.equals(tSearchPattern)){ //Logging.warn(this, " ..MATCH"); if(tKnownLink.getRefCounter() == 1){ // remove the link mHierarchicalRoutingGraph.unlink(tKnownLink); // it's time to update the HRG-GUI notifyHRGGUI(null); }else{ if(tKnownLink.getRefCounter() < 1){ throw new RuntimeException("Found an HRG link with an invalid ref. counter: " + tKnownLink); } tKnownLink.decRefCounter(); tChangedRefCounter = true; // it's time to update the HRG-GUI notifyHRGGUI(tKnownLink); } // we have a positive result tResult = true; // work is done break; }else{ //Logging.warn(this, " ..NO MATCH"); } } } } } if(!tResult){ /** * The route was already removed -> this can occur if both end points of a link are located on this node and both of them try to unregister the same route */ mDescriptionHRGUpdates += "\n -/+ " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString(); Logging.warn(this, "Haven't found " + pRoutingEntry + " as HRG between " + pFrom + " and " + pTo); - synchronized (mHierarchicalRoutingGraph) { - Collection<HRMID> tNodes = mHierarchicalRoutingGraph.getVertices(); - for(HRMID tKnownNode : tNodes){ - Logging.warn(this, " ..knowing node: " + tKnownNode); - Collection<AbstractRoutingGraphLink> tLinks = mHierarchicalRoutingGraph.getOutEdges(tKnownNode); - for(AbstractRoutingGraphLink tKnownLink : tLinks){ - Logging.warn(this, " ..has link: " + tKnownLink); - if(tKnownLink.equals(tSearchPattern)){ - Logging.err(this, " ..MATCH"); - }else{ - Logging.warn(this, " ..NO MATCH"); + if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ + synchronized (mHierarchicalRoutingGraph) { + Collection<HRMID> tNodes = mHierarchicalRoutingGraph.getVertices(); + for(HRMID tKnownNode : tNodes){ + Logging.warn(this, " ..knowing node: " + tKnownNode); + Collection<AbstractRoutingGraphLink> tLinks = mHierarchicalRoutingGraph.getOutEdges(tKnownNode); + for(AbstractRoutingGraphLink tKnownLink : tLinks){ + Logging.warn(this, " ..has link: " + tKnownLink); + if(tKnownLink.equals(tSearchPattern)){ + Logging.err(this, " ..MATCH"); + }else{ + Logging.warn(this, " ..NO MATCH"); + } } } } } }else{ mDescriptionHRGUpdates += "\n -" + (tChangedRefCounter ? "(REF)" : "") +" " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString(); /** * Iterate over all nodes and delete all of them which don't have any links anymore */ boolean tRemovedSomething = false; synchronized (mHierarchicalRoutingGraph) { boolean tRemovedANode; do{ tRemovedANode = false; Collection<HRMID> tNodes = mHierarchicalRoutingGraph.getVertices(); for(HRMID tKnownNode : tNodes){ Collection<AbstractRoutingGraphLink> tLinks = mHierarchicalRoutingGraph.getOutEdges(tKnownNode); if(tLinks.size() == 0){ // unregister the HRMID in the HRG unregisterNodeHRG(tKnownNode, pRoutingEntry + ", " + this + "::unregisterLinkHRG()_autoDel"); tRemovedANode = true; tRemovedSomething = true; break; } } }while(tRemovedANode); } if(tRemovedSomething){ // it's time to update the HRG-GUI notifyHRGGUI(null); } } }else{ //Logging.warn(this, "unregisterLinkHRG() skipped because self-loop detected for: " + pRoutingEntry); } return tResult; } /** * Returns routes to neighbors of a given HRG node * * @param pHRMID the HRMID of the HRG root node * * @return the routing table */ public RoutingTable getRoutesToNeighborsHRG(HRMID pHRMID) { RoutingTable tResult = new RoutingTable(); synchronized (mHierarchicalRoutingGraph) { //Logging.warn(this, " ..knowing node: " + pFrom + " as " + mHierarchicalRoutingGraph.containsVertex(pFrom)); // get all outgoing HRG links of "pFrom" Collection<AbstractRoutingGraphLink> tOutLinks = mHierarchicalRoutingGraph.getOutEdges(pHRMID); if(tOutLinks != null){ // iterate over all found links for(AbstractRoutingGraphLink tKnownLink : tOutLinks) { Route tKnownLinkRoute = tKnownLink.getRoute(); if(tKnownLinkRoute.size() == 1){ if(tKnownLinkRoute.getFirst() instanceof RoutingEntry){ RoutingEntry tRouteToNeighbor = (RoutingEntry)tKnownLinkRoute.getFirst(); tResult.add(tRouteToNeighbor.clone()); }else{ throw new RuntimeException("getRoutesToNeighborsHRG() detected an unsupported route type: " + tKnownLinkRoute); } }else{ throw new RuntimeException("getRoutesToNeighborsHRG() detected an unsupported route size for: " + tKnownLinkRoute); } } } } return tResult; } /** * Registers a link between two clusters. * * @param pFromHRMID the start of the link * @param pToHRMID the end of the link * @param pRoutingEntry the routing entry for this link */ public void registerCluster2ClusterLinkHRG(HRMID pFromHRMID, HRMID pToHRMID, RoutingEntry pRoutingEntry) { /** * Store/update link in the HRG */ if(registerLinkHRG(pFromHRMID, pToHRMID, pRoutingEntry)){ Logging.log(this, "Stored cluster-2-cluster link between " + pFromHRMID + " and " + pToHRMID + " in the HRG as: " + pRoutingEntry); } } /** * Unregisters a link between two clusters. * * @param pFromHRMID the start of the link * @param pToHRMID the end of the link * @param pRoutingEntry the routing entry for this link */ private void unregisterCluster2ClusterLinkHRG(HRMID pFromHRMID, HRMID pToHRMID, RoutingEntry pRoutingEntry) { /** * Store/update link in the HRG */ if(unregisterLinkHRG(pFromHRMID, pToHRMID, pRoutingEntry)){ Logging.log(this, "Removed cluster-2-cluster link between " + pFromHRMID + " and " + pToHRMID + " from the HRG as: " + pRoutingEntry); } } /** * Determines a route in the locally stored hierarchical routing graph (HRG). * * @param pSource the source of the desired route * @param pDestination the destination of the desired route * * @return the determined route, null if no route could be found */ public List<AbstractRoutingGraphLink> getRouteHRG(HRMID pSource, HRMID pDestination) { List<AbstractRoutingGraphLink> tResult = null; if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){ Logging.log(this, "GET ROUTE (HRG) from \"" + pSource + "\" to \"" + pDestination +"\""); } synchronized (mHierarchicalRoutingGraph) { tResult = mHierarchicalRoutingGraph.getRoute(pSource, pDestination); } if (HRMConfig.DebugOutput.GUI_SHOW_ROUTING){ Logging.log(this, " ..result: " + tResult); } return tResult; } /** * Returns the HRG for the GraphViewer. * (only for GUI!) * * @return the HRG */ public AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink> getHRGForGraphViewer() { AbstractRoutingGraph<HRMID, AbstractRoutingGraphLink> tResult = null; synchronized (mHierarchicalRoutingGraph) { tResult = mHierarchicalRoutingGraph; //TODO: use a new clone() method here } return tResult; } /** * This method is derived from IServerCallback and is called for incoming connection requests by the HRMController application's ServerFN. * Such a incoming connection can either be triggered by an HRMController application or by a probe-routing request * * @param pConnection the incoming connection */ @Override public void newConnection(Connection pConnection) { Logging.log(this, "INCOMING CONNECTION " + pConnection.toString() + " with requirements: " + pConnection.getRequirements()); // get the connection requirements Description tConnectionRequirements = pConnection.getRequirements(); /** * check if the new connection is a probe-routing connection */ ProbeRoutingProperty tPropProbeRouting = (ProbeRoutingProperty) tConnectionRequirements.get(ProbeRoutingProperty.class); // do we have a probe-routing connection? if (tPropProbeRouting == null){ /** * Create the communication session */ Logging.log(this, " ..creating communication session"); ComSession tComSession = new ComSession(this); /** * Start the communication session */ Logging.log(this, " ..starting communication session for the new connection"); tComSession.startConnection(null, pConnection); }else{ /** * We have a probe-routing connection and will print some additional information about the taken route of the connection request */ // get the recorded route from the property LinkedList<HRMID> tRecordedHRMIDs = tPropProbeRouting.getRecordedHops(); Logging.log(this, " ..detected a probe-routing connection(source=" + tPropProbeRouting.getSourceDescription() + " with " + tRecordedHRMIDs.size() + " recorded hops"); // print the recorded route int i = 0; for(HRMID tHRMID : tRecordedHRMIDs){ Logging.log(this, " [" + i + "]: " + tHRMID); i++; } } } /** * Callback for ServerCallback: gets triggered if an error is caused by the server socket * * @param the error cause */ /* (non-Javadoc) * @see de.tuilmenau.ics.fog.application.util.ServerCallback#error(de.tuilmenau.ics.fog.facade.events.ErrorEvent) */ @Override public void error(ErrorEvent pCause) { Logging.log(this, "Got an error message because of \"" + pCause + "\""); } /** * Creates a descriptive string about this object * * @return the descriptive string */ public String toString() { return "HRM controller@" + getNode(); } /** * Determine the name of the central FN of this node * * @return the name of the central FN */ @SuppressWarnings("deprecation") public Name getNodeName() { // get the name of the central FN of this node return getHRS().getCentralFN().getName(); } /** * Determine the L2 address of the central FN of this node * * @return the L2Address of the central FN */ public L2Address getNodeL2Address() { L2Address tResult = null; // get the recursive FoG layer FoGEntity tFoGLayer = (FoGEntity) getNode().getLayer(FoGEntity.class); if(tFoGLayer != null){ // get the central FN of this node L2Address tThisHostL2Address = getHRS().getL2AddressFor(tFoGLayer.getCentralFN()); tResult = tThisHostL2Address; } return tResult; } /** * The global name space which is used to identify the HRM instances on nodes. */ public final static Namespace ROUTING_NAMESPACE = new Namespace("routing"); /** * Stores the identification string for HRM specific routing graph decorations (coordinators & HRMIDs) */ private final static String DECORATION_NAME_COORDINATORS_AND_HRMIDS = "HRM(1) - coordinators & HRMIDs"; /** * Stores the identification string for HRM specific routing graph decorations (node priorities) */ private final static String DECORATION_NAME_NODE_PRIORITIES = "HRM(3) - node priorities"; /** * Stores the identification string for the active HRM infrastructure */ private final static String DECORATION_NAME_ACTIVE_HRM_INFRASTRUCTURE = "HRM(4) - active infrastructure"; /** * Stores the identification string for HRM specific routing graph decorations (coordinators & clusters) */ private final static String DECORATION_NAME_COORDINATORS_AND_CLUSTERS = "HRM(2) - coordinators & clusters"; }
true
true
public boolean unregisterLinkHRG(HRMID pFrom, HRMID pTo, RoutingEntry pRoutingEntry) { boolean tResult = false; if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, "UNREGISTERING LINK (HRG):\n SOURCE=" + pFrom + "\n DEST.=" + pTo + "\n LINK=" + pRoutingEntry); } if(!pFrom.equals(pTo)){ pRoutingEntry.assignToHRG(mHierarchicalRoutingGraph); AbstractRoutingGraphLink tSearchPattern = new AbstractRoutingGraphLink(new Route(pRoutingEntry)); boolean tChangedRefCounter = false; synchronized (mHierarchicalRoutingGraph) { //Logging.warn(this, " ..knowing node: " + pFrom + " as " + mHierarchicalRoutingGraph.containsVertex(pFrom)); // get all outgoing HRG links of "pFrom" Collection<AbstractRoutingGraphLink> tOutLinks = mHierarchicalRoutingGraph.getOutEdges(pFrom); if(tOutLinks != null){ // iterate over all found links for(AbstractRoutingGraphLink tKnownLink : tOutLinks) { //Logging.warn(this, " ..has link: " + tKnownLink); Pair<HRMID> tEndPoints = mHierarchicalRoutingGraph.getEndpoints(tKnownLink); if (((tEndPoints.getFirst().equals(pFrom)) && (tEndPoints.getSecond().equals(pTo))) || ((tEndPoints.getFirst().equals(pTo)) && (tEndPoints.getSecond().equals(pFrom)))){ if(tKnownLink.equals(tSearchPattern)){ //Logging.warn(this, " ..MATCH"); if(tKnownLink.getRefCounter() == 1){ // remove the link mHierarchicalRoutingGraph.unlink(tKnownLink); // it's time to update the HRG-GUI notifyHRGGUI(null); }else{ if(tKnownLink.getRefCounter() < 1){ throw new RuntimeException("Found an HRG link with an invalid ref. counter: " + tKnownLink); } tKnownLink.decRefCounter(); tChangedRefCounter = true; // it's time to update the HRG-GUI notifyHRGGUI(tKnownLink); } // we have a positive result tResult = true; // work is done break; }else{ //Logging.warn(this, " ..NO MATCH"); } } } } } if(!tResult){ /** * The route was already removed -> this can occur if both end points of a link are located on this node and both of them try to unregister the same route */ mDescriptionHRGUpdates += "\n -/+ " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString(); Logging.warn(this, "Haven't found " + pRoutingEntry + " as HRG between " + pFrom + " and " + pTo); synchronized (mHierarchicalRoutingGraph) { Collection<HRMID> tNodes = mHierarchicalRoutingGraph.getVertices(); for(HRMID tKnownNode : tNodes){ Logging.warn(this, " ..knowing node: " + tKnownNode); Collection<AbstractRoutingGraphLink> tLinks = mHierarchicalRoutingGraph.getOutEdges(tKnownNode); for(AbstractRoutingGraphLink tKnownLink : tLinks){ Logging.warn(this, " ..has link: " + tKnownLink); if(tKnownLink.equals(tSearchPattern)){ Logging.err(this, " ..MATCH"); }else{ Logging.warn(this, " ..NO MATCH"); } } } } }else{ mDescriptionHRGUpdates += "\n -" + (tChangedRefCounter ? "(REF)" : "") +" " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString(); /** * Iterate over all nodes and delete all of them which don't have any links anymore */ boolean tRemovedSomething = false; synchronized (mHierarchicalRoutingGraph) { boolean tRemovedANode; do{ tRemovedANode = false; Collection<HRMID> tNodes = mHierarchicalRoutingGraph.getVertices(); for(HRMID tKnownNode : tNodes){ Collection<AbstractRoutingGraphLink> tLinks = mHierarchicalRoutingGraph.getOutEdges(tKnownNode); if(tLinks.size() == 0){ // unregister the HRMID in the HRG unregisterNodeHRG(tKnownNode, pRoutingEntry + ", " + this + "::unregisterLinkHRG()_autoDel"); tRemovedANode = true; tRemovedSomething = true; break; } } }while(tRemovedANode); } if(tRemovedSomething){ // it's time to update the HRG-GUI notifyHRGGUI(null); } } }else{ //Logging.warn(this, "unregisterLinkHRG() skipped because self-loop detected for: " + pRoutingEntry); } return tResult; }
public boolean unregisterLinkHRG(HRMID pFrom, HRMID pTo, RoutingEntry pRoutingEntry) { boolean tResult = false; if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ Logging.log(this, "UNREGISTERING LINK (HRG):\n SOURCE=" + pFrom + "\n DEST.=" + pTo + "\n LINK=" + pRoutingEntry); } if(!pFrom.equals(pTo)){ pRoutingEntry.assignToHRG(mHierarchicalRoutingGraph); AbstractRoutingGraphLink tSearchPattern = new AbstractRoutingGraphLink(new Route(pRoutingEntry)); boolean tChangedRefCounter = false; synchronized (mHierarchicalRoutingGraph) { //Logging.warn(this, " ..knowing node: " + pFrom + " as " + mHierarchicalRoutingGraph.containsVertex(pFrom)); // get all outgoing HRG links of "pFrom" Collection<AbstractRoutingGraphLink> tOutLinks = mHierarchicalRoutingGraph.getOutEdges(pFrom); if(tOutLinks != null){ // iterate over all found links for(AbstractRoutingGraphLink tKnownLink : tOutLinks) { //Logging.warn(this, " ..has link: " + tKnownLink); Pair<HRMID> tEndPoints = mHierarchicalRoutingGraph.getEndpoints(tKnownLink); if (((tEndPoints.getFirst().equals(pFrom)) && (tEndPoints.getSecond().equals(pTo))) || ((tEndPoints.getFirst().equals(pTo)) && (tEndPoints.getSecond().equals(pFrom)))){ if(tKnownLink.equals(tSearchPattern)){ //Logging.warn(this, " ..MATCH"); if(tKnownLink.getRefCounter() == 1){ // remove the link mHierarchicalRoutingGraph.unlink(tKnownLink); // it's time to update the HRG-GUI notifyHRGGUI(null); }else{ if(tKnownLink.getRefCounter() < 1){ throw new RuntimeException("Found an HRG link with an invalid ref. counter: " + tKnownLink); } tKnownLink.decRefCounter(); tChangedRefCounter = true; // it's time to update the HRG-GUI notifyHRGGUI(tKnownLink); } // we have a positive result tResult = true; // work is done break; }else{ //Logging.warn(this, " ..NO MATCH"); } } } } } if(!tResult){ /** * The route was already removed -> this can occur if both end points of a link are located on this node and both of them try to unregister the same route */ mDescriptionHRGUpdates += "\n -/+ " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString(); Logging.warn(this, "Haven't found " + pRoutingEntry + " as HRG between " + pFrom + " and " + pTo); if (HRMConfig.DebugOutput.GUI_SHOW_TOPOLOGY_DETECTION){ synchronized (mHierarchicalRoutingGraph) { Collection<HRMID> tNodes = mHierarchicalRoutingGraph.getVertices(); for(HRMID tKnownNode : tNodes){ Logging.warn(this, " ..knowing node: " + tKnownNode); Collection<AbstractRoutingGraphLink> tLinks = mHierarchicalRoutingGraph.getOutEdges(tKnownNode); for(AbstractRoutingGraphLink tKnownLink : tLinks){ Logging.warn(this, " ..has link: " + tKnownLink); if(tKnownLink.equals(tSearchPattern)){ Logging.err(this, " ..MATCH"); }else{ Logging.warn(this, " ..NO MATCH"); } } } } } }else{ mDescriptionHRGUpdates += "\n -" + (tChangedRefCounter ? "(REF)" : "") +" " + pFrom + " to " + pTo + " ==> " + pRoutingEntry.toString(); /** * Iterate over all nodes and delete all of them which don't have any links anymore */ boolean tRemovedSomething = false; synchronized (mHierarchicalRoutingGraph) { boolean tRemovedANode; do{ tRemovedANode = false; Collection<HRMID> tNodes = mHierarchicalRoutingGraph.getVertices(); for(HRMID tKnownNode : tNodes){ Collection<AbstractRoutingGraphLink> tLinks = mHierarchicalRoutingGraph.getOutEdges(tKnownNode); if(tLinks.size() == 0){ // unregister the HRMID in the HRG unregisterNodeHRG(tKnownNode, pRoutingEntry + ", " + this + "::unregisterLinkHRG()_autoDel"); tRemovedANode = true; tRemovedSomething = true; break; } } }while(tRemovedANode); } if(tRemovedSomething){ // it's time to update the HRG-GUI notifyHRGGUI(null); } } }else{ //Logging.warn(this, "unregisterLinkHRG() skipped because self-loop detected for: " + pRoutingEntry); } return tResult; }
diff --git a/backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/vdsbroker/SysprepHandler.java b/backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/vdsbroker/SysprepHandler.java index 85864c77b..48224a488 100644 --- a/backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/vdsbroker/SysprepHandler.java +++ b/backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/vdsbroker/SysprepHandler.java @@ -1,318 +1,318 @@ package org.ovirt.engine.core.vdsbroker.vdsbroker; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.common.action.SysPrepParams; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigUtil; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.utils.log.Log; import org.ovirt.engine.core.utils.log.LogFactory; import org.ovirt.engine.core.compat.StringBuilderCompat; import org.ovirt.engine.core.compat.StringHelper; import org.ovirt.engine.core.compat.TimeZoneInfo; import org.ovirt.engine.core.dal.dbbroker.generic.DomainsPasswordMap; import org.ovirt.engine.core.utils.FileUtil; public final class SysprepHandler { private static Map<String, String> userPerDomain = new HashMap<String, String>(); private static Map<String, String> passwordPerDomain = new HashMap<String, String>(); public static final java.util.HashMap<String, Integer> timeZoneIndex = new java.util.HashMap<String, Integer>(); // we get a string like "(GMT-04:30) Afghanistan Standard Time" // we use regex to extract the time only and replace it to number // in this sample we get -430 public static String TimzeZoneExtractTimePattern = ".*(GMT[+,-]\\d{2}:\\d{2}).*"; private static Log log = LogFactory.getLog(SysprepHandler.class); static { initTimeZones(); fillUsersMap(); fillPasswordsMap(); } /** * TODO: This code is the exact code as in UsersDomainCacheManagerService, until we have a suitable location that * them both can use. Note that every change in one will probably require the same change in the other */ private static void fillUsersMap() { String userPerDomainEntry = Config.<String> GetValue(ConfigValues.AdUserName); if (!userPerDomainEntry.isEmpty()) { String[] domainUserPairs = userPerDomainEntry.split(","); for (String domainUserPair : domainUserPairs) { String[] parts = domainUserPair.split(":"); String domain = parts[0].trim().toLowerCase(); String userName = parts[1].trim(); userPerDomain.put(domain, userName); } } } /** * TODO: This code is the exact code as in UsersDomainCacheManagerService, until we have a suitable location that * them both can use. Note that every change in one will probably require the same change in the other */ private static void fillPasswordsMap() { passwordPerDomain = Config.<DomainsPasswordMap> GetValue(ConfigValues.AdUserPassword); } public static String GetSysPrep(VM vm, String hostName, String domain, SysPrepParams sysPrepParams) { StringBuilderCompat sysPrepContent = new StringBuilderCompat(); switch (vm.getStaticData().getos()) { case WindowsXP: sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrepXPPath))); sysPrepContent.replace("$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey)); break; case Windows2003: sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K3Path))); sysPrepContent.replace("$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2003)); break; case Windows2003x64: sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K3Path))); sysPrepContent.replace("$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2003x64)); break; case Windows2008: sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K8Path))); sysPrepContent.replace("$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2008)); break; case Windows2008x64: sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K8x64Path))); sysPrepContent.replace("$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2008x64)); break; case Windows2008R2x64: sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrep2K8R2Path))); sysPrepContent.replace("$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKey2008R2)); break; case Windows7: sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrepWindows7Path))); sysPrepContent.replace("$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKeyWindow7)); break; case Windows7x64: sysPrepContent.append(LoadFile(Config.<String> GetValue(ConfigValues.SysPrepWindows7x64Path))); sysPrepContent.replace("$ProductKey$", Config.<String> GetValue(ConfigValues.ProductKeyWindow7x64)); break; default: break; } if (sysPrepContent.length() > 0) { populateSysPrepDomainProperties(sysPrepContent, domain, sysPrepParams); sysPrepContent.replace("$ComputerName$", hostName != null ? hostName : ""); sysPrepContent.replace("$AdminPassword$", Config.<String> GetValue(ConfigValues.LocalAdminPassword)); String timeZone = getTimeZone(vm); sysPrepContent.replace("$TimeZone$", timeZone); sysPrepContent.replace("$OrgName$", Config.<String> GetValue(ConfigValues.OrganizationName)); } return sysPrepContent.toString(); } private static void populateSysPrepDomainProperties(StringBuilderCompat sysPrepContent, String domain, SysPrepParams sysPrepParams) { String domainName; String adminUserName; String adminPassword; if (sysPrepParams == null || StringUtils.isEmpty(sysPrepParams.getSysPrepDomainName())) { domainName = useDefaultIfNull("domain", domain, "", true); } else { domainName = sysPrepParams.getSysPrepDomainName(); } if (sysPrepParams == null || sysPrepParams.getSysPrepUserName() == null || sysPrepParams.getSysPrepPassword() == null) { adminUserName = useDefaultIfNull("user", userPerDomain.get(domainName.toLowerCase()), Config.<String> GetValue(ConfigValues.SysPrepDefaultUser), true); adminPassword = useDefaultIfNull("password", passwordPerDomain.get(domainName.toLowerCase()), Config.<String> GetValue(ConfigValues.SysPrepDefaultPassword), false); } else { adminUserName = sysPrepParams.getSysPrepUserName(); adminPassword = sysPrepParams.getSysPrepPassword(); } // Get values from SysPrepParams - alternative for username,password and domain. sysPrepContent.replace("$JoinDomain$", domainName); sysPrepContent.replace("$DomainAdmin$", adminUserName); sysPrepContent.replace("$DomainAdminPassword$", adminPassword); } private static String useDefaultIfNull(String key, String value, String defaultValue, boolean printDefaultValue) { if (value == null && printDefaultValue) { log.errorFormat("Could not find value for {0}. Going to use default value of: {1}", key, defaultValue); } return value != null ? value : defaultValue; } private static String getTimeZone(VM vm) { String timeZone; // Can be empty if the VM was imported. if (StringHelper.isNullOrEmpty(vm.gettime_zone())) { vm.settime_zone(TimeZoneInfo.Local.getId()); } switch (vm.getStaticData().getos()) { case WindowsXP: case Windows2003: case Windows2003x64: // send correct time zone as sysprep expect to get it (a wierd // number) timeZone = getTimezoneIndexByKey(vm.gettime_zone()); break; case Windows2008: default: timeZone = vm.gettime_zone(); break; } return timeZone; } private static String getSysprepDir() { return Config.<String> GetValue(ConfigValues.DataDir) + java.io.File.separator + "sysprep"; } private static String LoadFile(String fileName) { String content = ""; fileName = ConfigUtil.resolvePath(getSysprepDir(), fileName); if (FileUtil.fileExists(fileName)) { try { content = FileUtil.readAllText(fileName); } catch (RuntimeException e) { log.error("Failed to read sysprep template: " + fileName, e); } } else { log.error("Sysprep template: " + fileName + " not found"); } return content; } // exclude 13 and 158 - not in the sysprep documentation! // {"Arabic Standard Time", 158}, // {"Jerusalem Standard Time", 135}, // {"Mexico Standard Time 2", 13}, // {"Malay Peninsula Standard Time", 215}, // TimeZone reference from Microsoft: // http://msdn.microsoft.com/en-us/library/ms912391(v=winembedded.11).aspx private static void initTimeZones() { timeZoneIndex.put("(GMT+04:30) Afghanistan Standard Time", 175); timeZoneIndex.put("(GMT-09:00) Alaskan Standard Time", 3); timeZoneIndex.put("(GMT+03:00) Arab Standard Time", 150); timeZoneIndex.put("(GMT+04:00) Arabian Standard Time", 165); timeZoneIndex.put("(GMT+03:00) Arabic Standard Time", 158); timeZoneIndex.put("(GMT-04:00) Atlantic Standard Time", 50); //timeZoneIndex.put("(GMT+04:00) Azerbaijan Standard Time", xxx); timeZoneIndex.put("(GMT-10:00) Azores Standard Time", 80); timeZoneIndex.put("(GMT-06:00) Canada Central Standard Time", 25); timeZoneIndex.put("(GMT-01:00) Cape Verde Standard Time", 83); timeZoneIndex.put("(GMT+04:00) Caucasus Standard Time", 170); timeZoneIndex.put("(GMT+09:30) Cen. Australia Standard Time", 250); timeZoneIndex.put("(GMT-06:00) Central America Standard Time", 33); timeZoneIndex.put("(GMT+06:00) Central Asia Standard Time", 195); //timeZoneIndex.put("(GMT-04:00) Central Brazilian Standard Time ", xxx); timeZoneIndex.put("(GMT+01:00) Central Europe Standard Time", 95); timeZoneIndex.put("(GMT+01:00) Central European Standard Time", 100); timeZoneIndex.put("(GMT+11:00) Central Pacific Standard Time", 280); timeZoneIndex.put("(GMT-06:00) Central Standard Time", 20); timeZoneIndex.put("(GMT-06:00) Central Standard Time (Mexico)", 30); timeZoneIndex.put("(GMT+08:00) China Standard Time", 210); timeZoneIndex.put("(GMT-12:00) Dateline Standard Time", 0); timeZoneIndex.put("(GMT+03:00) E. Africa Standard Time", 155); timeZoneIndex.put("(GMT+10:00) E. Australia Standard Time", 260); timeZoneIndex.put("(GMT+02:00) E. Europe Standard Time", 115); timeZoneIndex.put("(GMT-03:00) E. South America Standard Time", 65); timeZoneIndex.put("(GMT-05:00) Eastern Standard Time", 35); timeZoneIndex.put("(GMT+01:00) Egypt Standard Time", 120); timeZoneIndex.put("(GMT+05:00) Ekaterinburg Standard Time", 180); timeZoneIndex.put("(GMT+12:00) Fiji Standard Time", 285); timeZoneIndex.put("(GMT+02:00) FLE Standard Time", 125); timeZoneIndex.put("(GMT+04:00) Georgian Standard Time", 70); timeZoneIndex.put("(GMT) GMT Standard Time", 85); timeZoneIndex.put("(GMT-03:00) Greenland Standard Time", 73); timeZoneIndex.put("(GMT-01:00) Greenwich Standard Time", 90); timeZoneIndex.put("(GMT+02:00) GTB Standard Time", 130); timeZoneIndex.put("(GMT-10:00) Hawaiian Standard Time", 2); timeZoneIndex.put("(GMT+05:00) India Standard Time", 190); timeZoneIndex.put("(GMT+03:00) Iran Standard Time", 160); timeZoneIndex.put("(GMT+02:00) Israel Standard Time", 135); timeZoneIndex.put("(GMT+08:00) Korea Standard Time", 230); timeZoneIndex.put("(GMT-02:00) Mid-Atlantic Standard Time", 75); timeZoneIndex.put("(GMT-07:00) Mountain Standard Time", 10); timeZoneIndex.put("(GMT+06:00) Myanmar Standard Time", 203); timeZoneIndex.put("(GMT+06:00) N. Central Asia Standard Time", 201); timeZoneIndex.put("(GMT+05:00) Nepal Standard Time", 193); timeZoneIndex.put("(GMT+11:00) New Zealand Standard Time", 290); timeZoneIndex.put("(GMT-03:30) Newfoundland Standard Time", 60); timeZoneIndex.put("(GMT+08:00) North Asia East Standard Time", 227); timeZoneIndex.put("(GMT+07:00) North Asia Standard Time", 207); timeZoneIndex.put("(GMT+04:00) Pacific SA Standard Time", 56); timeZoneIndex.put("(GMT-08:00) Pacific Standard Time", 4); timeZoneIndex.put("(GMT+01:00) Romance Standard Time", 105); timeZoneIndex.put("(GMT+03:00) Russian Standard Time", 145); timeZoneIndex.put("(GMT-03:00) SA Eastern Standard Time", 70); timeZoneIndex.put("(GMT-05:00) SA Pacific Standard Time", 45); timeZoneIndex.put("(GMT-04:00) SA Western Standard Time", 55); timeZoneIndex.put("(GMT-11:00) Samoa Standard Time", 1); timeZoneIndex.put("(GMT+07:00) SE Asia Standard Time", 205); timeZoneIndex.put("(GMT+08:00) Singapore Standard Time", 215); timeZoneIndex.put("(GMT+02:00) South Africa Standard Time", 140); timeZoneIndex.put("(GMT+06:00) Sri Lanka Standard Time", 200); timeZoneIndex.put("(GMT+08:00) Taipei Standard Time", 220); timeZoneIndex.put("(GMT+10:00) Tasmania Standard Time", 265); timeZoneIndex.put("(GMT+09:00) Tokyo Standard Time", 235); timeZoneIndex.put("(GMT+13:00) Tonga Standard Time", 300); - timeZoneIndex.put("(GMT+05:00) US Eastern Standard Time", 40); + timeZoneIndex.put("(GMT-05:00) US Eastern Standard Time", 40); timeZoneIndex.put("(GMT-07:00) US Mountain Standard Time", 15); timeZoneIndex.put("(GMT+10:00) Vladivostok Standard Time", 270); timeZoneIndex.put("(GMT+08:00) W. Australia Standard Time", 225); timeZoneIndex.put("(GMT+01:00) W. Central Africa Standard Time", 113); timeZoneIndex.put("(GMT+01:00) W. Europe Standard Time", 110); timeZoneIndex.put("(GMT+05:00) West Asia Standard Time", 185); timeZoneIndex.put("(GMT+10:00) West Pacific Standard Time", 275); timeZoneIndex.put("(GMT+09:00) Yakutsk Standard Time", 240); } // we use: // key = "Afghanistan Standard Time" // value = "(GMT+04:30) Afghanistan Standard Time" public static String getTimezoneKey(String value) { return value.substring(value.indexOf(' ') + 1); } // we get "Afghanistan Standard Time" we return "175" // the "Afghanistan Standard Time" is the vm Key that we get from the method getTimezoneKey() // "175" is the timezone keys that xp/2003 excpect to get, vista/7/2008 gets "Afghanistan Standard Time" public static String getTimezoneIndexByKey(String key) { for(String s: timeZoneIndex.keySet()) { if (getTimezoneKey(s).equals(key)) { return timeZoneIndex.get(s).toString(); } } log.errorFormat("getTimezoneIndexByKey: cannot find timezone key '{0}'", key); return key; } }
true
true
private static void initTimeZones() { timeZoneIndex.put("(GMT+04:30) Afghanistan Standard Time", 175); timeZoneIndex.put("(GMT-09:00) Alaskan Standard Time", 3); timeZoneIndex.put("(GMT+03:00) Arab Standard Time", 150); timeZoneIndex.put("(GMT+04:00) Arabian Standard Time", 165); timeZoneIndex.put("(GMT+03:00) Arabic Standard Time", 158); timeZoneIndex.put("(GMT-04:00) Atlantic Standard Time", 50); //timeZoneIndex.put("(GMT+04:00) Azerbaijan Standard Time", xxx); timeZoneIndex.put("(GMT-10:00) Azores Standard Time", 80); timeZoneIndex.put("(GMT-06:00) Canada Central Standard Time", 25); timeZoneIndex.put("(GMT-01:00) Cape Verde Standard Time", 83); timeZoneIndex.put("(GMT+04:00) Caucasus Standard Time", 170); timeZoneIndex.put("(GMT+09:30) Cen. Australia Standard Time", 250); timeZoneIndex.put("(GMT-06:00) Central America Standard Time", 33); timeZoneIndex.put("(GMT+06:00) Central Asia Standard Time", 195); //timeZoneIndex.put("(GMT-04:00) Central Brazilian Standard Time ", xxx); timeZoneIndex.put("(GMT+01:00) Central Europe Standard Time", 95); timeZoneIndex.put("(GMT+01:00) Central European Standard Time", 100); timeZoneIndex.put("(GMT+11:00) Central Pacific Standard Time", 280); timeZoneIndex.put("(GMT-06:00) Central Standard Time", 20); timeZoneIndex.put("(GMT-06:00) Central Standard Time (Mexico)", 30); timeZoneIndex.put("(GMT+08:00) China Standard Time", 210); timeZoneIndex.put("(GMT-12:00) Dateline Standard Time", 0); timeZoneIndex.put("(GMT+03:00) E. Africa Standard Time", 155); timeZoneIndex.put("(GMT+10:00) E. Australia Standard Time", 260); timeZoneIndex.put("(GMT+02:00) E. Europe Standard Time", 115); timeZoneIndex.put("(GMT-03:00) E. South America Standard Time", 65); timeZoneIndex.put("(GMT-05:00) Eastern Standard Time", 35); timeZoneIndex.put("(GMT+01:00) Egypt Standard Time", 120); timeZoneIndex.put("(GMT+05:00) Ekaterinburg Standard Time", 180); timeZoneIndex.put("(GMT+12:00) Fiji Standard Time", 285); timeZoneIndex.put("(GMT+02:00) FLE Standard Time", 125); timeZoneIndex.put("(GMT+04:00) Georgian Standard Time", 70); timeZoneIndex.put("(GMT) GMT Standard Time", 85); timeZoneIndex.put("(GMT-03:00) Greenland Standard Time", 73); timeZoneIndex.put("(GMT-01:00) Greenwich Standard Time", 90); timeZoneIndex.put("(GMT+02:00) GTB Standard Time", 130); timeZoneIndex.put("(GMT-10:00) Hawaiian Standard Time", 2); timeZoneIndex.put("(GMT+05:00) India Standard Time", 190); timeZoneIndex.put("(GMT+03:00) Iran Standard Time", 160); timeZoneIndex.put("(GMT+02:00) Israel Standard Time", 135); timeZoneIndex.put("(GMT+08:00) Korea Standard Time", 230); timeZoneIndex.put("(GMT-02:00) Mid-Atlantic Standard Time", 75); timeZoneIndex.put("(GMT-07:00) Mountain Standard Time", 10); timeZoneIndex.put("(GMT+06:00) Myanmar Standard Time", 203); timeZoneIndex.put("(GMT+06:00) N. Central Asia Standard Time", 201); timeZoneIndex.put("(GMT+05:00) Nepal Standard Time", 193); timeZoneIndex.put("(GMT+11:00) New Zealand Standard Time", 290); timeZoneIndex.put("(GMT-03:30) Newfoundland Standard Time", 60); timeZoneIndex.put("(GMT+08:00) North Asia East Standard Time", 227); timeZoneIndex.put("(GMT+07:00) North Asia Standard Time", 207); timeZoneIndex.put("(GMT+04:00) Pacific SA Standard Time", 56); timeZoneIndex.put("(GMT-08:00) Pacific Standard Time", 4); timeZoneIndex.put("(GMT+01:00) Romance Standard Time", 105); timeZoneIndex.put("(GMT+03:00) Russian Standard Time", 145); timeZoneIndex.put("(GMT-03:00) SA Eastern Standard Time", 70); timeZoneIndex.put("(GMT-05:00) SA Pacific Standard Time", 45); timeZoneIndex.put("(GMT-04:00) SA Western Standard Time", 55); timeZoneIndex.put("(GMT-11:00) Samoa Standard Time", 1); timeZoneIndex.put("(GMT+07:00) SE Asia Standard Time", 205); timeZoneIndex.put("(GMT+08:00) Singapore Standard Time", 215); timeZoneIndex.put("(GMT+02:00) South Africa Standard Time", 140); timeZoneIndex.put("(GMT+06:00) Sri Lanka Standard Time", 200); timeZoneIndex.put("(GMT+08:00) Taipei Standard Time", 220); timeZoneIndex.put("(GMT+10:00) Tasmania Standard Time", 265); timeZoneIndex.put("(GMT+09:00) Tokyo Standard Time", 235); timeZoneIndex.put("(GMT+13:00) Tonga Standard Time", 300); timeZoneIndex.put("(GMT+05:00) US Eastern Standard Time", 40); timeZoneIndex.put("(GMT-07:00) US Mountain Standard Time", 15); timeZoneIndex.put("(GMT+10:00) Vladivostok Standard Time", 270); timeZoneIndex.put("(GMT+08:00) W. Australia Standard Time", 225); timeZoneIndex.put("(GMT+01:00) W. Central Africa Standard Time", 113); timeZoneIndex.put("(GMT+01:00) W. Europe Standard Time", 110); timeZoneIndex.put("(GMT+05:00) West Asia Standard Time", 185); timeZoneIndex.put("(GMT+10:00) West Pacific Standard Time", 275); timeZoneIndex.put("(GMT+09:00) Yakutsk Standard Time", 240); }
private static void initTimeZones() { timeZoneIndex.put("(GMT+04:30) Afghanistan Standard Time", 175); timeZoneIndex.put("(GMT-09:00) Alaskan Standard Time", 3); timeZoneIndex.put("(GMT+03:00) Arab Standard Time", 150); timeZoneIndex.put("(GMT+04:00) Arabian Standard Time", 165); timeZoneIndex.put("(GMT+03:00) Arabic Standard Time", 158); timeZoneIndex.put("(GMT-04:00) Atlantic Standard Time", 50); //timeZoneIndex.put("(GMT+04:00) Azerbaijan Standard Time", xxx); timeZoneIndex.put("(GMT-10:00) Azores Standard Time", 80); timeZoneIndex.put("(GMT-06:00) Canada Central Standard Time", 25); timeZoneIndex.put("(GMT-01:00) Cape Verde Standard Time", 83); timeZoneIndex.put("(GMT+04:00) Caucasus Standard Time", 170); timeZoneIndex.put("(GMT+09:30) Cen. Australia Standard Time", 250); timeZoneIndex.put("(GMT-06:00) Central America Standard Time", 33); timeZoneIndex.put("(GMT+06:00) Central Asia Standard Time", 195); //timeZoneIndex.put("(GMT-04:00) Central Brazilian Standard Time ", xxx); timeZoneIndex.put("(GMT+01:00) Central Europe Standard Time", 95); timeZoneIndex.put("(GMT+01:00) Central European Standard Time", 100); timeZoneIndex.put("(GMT+11:00) Central Pacific Standard Time", 280); timeZoneIndex.put("(GMT-06:00) Central Standard Time", 20); timeZoneIndex.put("(GMT-06:00) Central Standard Time (Mexico)", 30); timeZoneIndex.put("(GMT+08:00) China Standard Time", 210); timeZoneIndex.put("(GMT-12:00) Dateline Standard Time", 0); timeZoneIndex.put("(GMT+03:00) E. Africa Standard Time", 155); timeZoneIndex.put("(GMT+10:00) E. Australia Standard Time", 260); timeZoneIndex.put("(GMT+02:00) E. Europe Standard Time", 115); timeZoneIndex.put("(GMT-03:00) E. South America Standard Time", 65); timeZoneIndex.put("(GMT-05:00) Eastern Standard Time", 35); timeZoneIndex.put("(GMT+01:00) Egypt Standard Time", 120); timeZoneIndex.put("(GMT+05:00) Ekaterinburg Standard Time", 180); timeZoneIndex.put("(GMT+12:00) Fiji Standard Time", 285); timeZoneIndex.put("(GMT+02:00) FLE Standard Time", 125); timeZoneIndex.put("(GMT+04:00) Georgian Standard Time", 70); timeZoneIndex.put("(GMT) GMT Standard Time", 85); timeZoneIndex.put("(GMT-03:00) Greenland Standard Time", 73); timeZoneIndex.put("(GMT-01:00) Greenwich Standard Time", 90); timeZoneIndex.put("(GMT+02:00) GTB Standard Time", 130); timeZoneIndex.put("(GMT-10:00) Hawaiian Standard Time", 2); timeZoneIndex.put("(GMT+05:00) India Standard Time", 190); timeZoneIndex.put("(GMT+03:00) Iran Standard Time", 160); timeZoneIndex.put("(GMT+02:00) Israel Standard Time", 135); timeZoneIndex.put("(GMT+08:00) Korea Standard Time", 230); timeZoneIndex.put("(GMT-02:00) Mid-Atlantic Standard Time", 75); timeZoneIndex.put("(GMT-07:00) Mountain Standard Time", 10); timeZoneIndex.put("(GMT+06:00) Myanmar Standard Time", 203); timeZoneIndex.put("(GMT+06:00) N. Central Asia Standard Time", 201); timeZoneIndex.put("(GMT+05:00) Nepal Standard Time", 193); timeZoneIndex.put("(GMT+11:00) New Zealand Standard Time", 290); timeZoneIndex.put("(GMT-03:30) Newfoundland Standard Time", 60); timeZoneIndex.put("(GMT+08:00) North Asia East Standard Time", 227); timeZoneIndex.put("(GMT+07:00) North Asia Standard Time", 207); timeZoneIndex.put("(GMT+04:00) Pacific SA Standard Time", 56); timeZoneIndex.put("(GMT-08:00) Pacific Standard Time", 4); timeZoneIndex.put("(GMT+01:00) Romance Standard Time", 105); timeZoneIndex.put("(GMT+03:00) Russian Standard Time", 145); timeZoneIndex.put("(GMT-03:00) SA Eastern Standard Time", 70); timeZoneIndex.put("(GMT-05:00) SA Pacific Standard Time", 45); timeZoneIndex.put("(GMT-04:00) SA Western Standard Time", 55); timeZoneIndex.put("(GMT-11:00) Samoa Standard Time", 1); timeZoneIndex.put("(GMT+07:00) SE Asia Standard Time", 205); timeZoneIndex.put("(GMT+08:00) Singapore Standard Time", 215); timeZoneIndex.put("(GMT+02:00) South Africa Standard Time", 140); timeZoneIndex.put("(GMT+06:00) Sri Lanka Standard Time", 200); timeZoneIndex.put("(GMT+08:00) Taipei Standard Time", 220); timeZoneIndex.put("(GMT+10:00) Tasmania Standard Time", 265); timeZoneIndex.put("(GMT+09:00) Tokyo Standard Time", 235); timeZoneIndex.put("(GMT+13:00) Tonga Standard Time", 300); timeZoneIndex.put("(GMT-05:00) US Eastern Standard Time", 40); timeZoneIndex.put("(GMT-07:00) US Mountain Standard Time", 15); timeZoneIndex.put("(GMT+10:00) Vladivostok Standard Time", 270); timeZoneIndex.put("(GMT+08:00) W. Australia Standard Time", 225); timeZoneIndex.put("(GMT+01:00) W. Central Africa Standard Time", 113); timeZoneIndex.put("(GMT+01:00) W. Europe Standard Time", 110); timeZoneIndex.put("(GMT+05:00) West Asia Standard Time", 185); timeZoneIndex.put("(GMT+10:00) West Pacific Standard Time", 275); timeZoneIndex.put("(GMT+09:00) Yakutsk Standard Time", 240); }
diff --git a/trunk/org/xbill/DNS/Tokenizer.java b/trunk/org/xbill/DNS/Tokenizer.java index 0333748..e5b3282 100644 --- a/trunk/org/xbill/DNS/Tokenizer.java +++ b/trunk/org/xbill/DNS/Tokenizer.java @@ -1,512 +1,513 @@ // Copyright (c) 2003 Brian Wellington ([email protected]) // // Copyright (C) 2003 Nominum, Inc. // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT // OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // package org.xbill.DNS; import java.io.*; import java.util.*; /** * Tokenizer is used to parse DNS records and zones from text format, * * @author Brian Wellington * @author Bob Halley */ public class Tokenizer { private static String delim = " \t\n;()\""; private static String quotes = "\""; /** End of file */ public static final int EOF = 0; /** End of line */ public static final int EOL = 1; /** Whitespace; only returned when wantWhitespace is set */ public static final int WHITESPACE = 2; /** An identifier (unquoted string) */ public static final int IDENTIFIER = 3; /** A quoted string */ public static final int QUOTED_STRING = 4; /** A comment; only returned when wantComment is set */ public static final int COMMENT = 5; private PushbackInputStream is; private boolean ungottenToken; private int multiline; private boolean quoting; private String delimiters; private Token current; private StringBuffer sb; private String filename; private int line; public static class Token { /** The type of token. */ public int type; /** The value of the token, or null for tokens without values. */ public String value; private Token() { type = -1; value = null; } private Token set(int type, StringBuffer value) { if (type < 0) throw new IllegalArgumentException(); this.type = type; this.value = value == null ? null : value.toString(); return this; } /** * Converts the token to a string containing a representation useful * for debugging. */ public String toString() { switch (type) { case EOF: return "<eof>"; case EOL: return "<eol>"; case WHITESPACE: return "<whitespace>"; case IDENTIFIER: return "<identifier: " + value + ">"; case QUOTED_STRING: return "<quoted_string: " + value + ">"; case COMMENT: return "<comment: " + value + ">"; default: return "<unknown>"; } } /** Indicates whether this token contains a string. */ public boolean isString() { return (type == IDENTIFIER || type == QUOTED_STRING); } /** Indicates whether this token contains an EOL or EOF. */ public boolean isEOL() { return (type == EOL || type == EOF); } } /** * Creates a Tokenizer from an arbitrary input stream. * @param is The InputStream to tokenize. */ public Tokenizer(InputStream is) { if (!(is instanceof BufferedInputStream)) is = new BufferedInputStream(is); this.is = new PushbackInputStream(is, 2); ungottenToken = false; multiline = 0; quoting = false; delimiters = delim; current = new Token(); sb = new StringBuffer(); filename = "<none>"; line = 1; } /** * Creates a Tokenizer from a string. * @param s The String to tokenize. */ public Tokenizer(String s) { this(new ByteArrayInputStream(s.getBytes())); } /** * Creates a Tokenizer from a file. * @param f The File to tokenize. */ public Tokenizer(File f) throws FileNotFoundException { this(new FileInputStream(f)); filename = f.getName(); } private int getChar() throws IOException { int c = is.read(); if (c == '\r') { int next = is.read(); if (next != '\n') is.unread(next); c = '\n'; } if (c == '\n') line++; return c; } private void ungetChar(int c) throws IOException { if (c == -1) return; is.unread(c); if (c == '\n') line--; } private int skipWhitespace() throws IOException { int skipped = 0; while (true) { int c = getChar(); if (c != ' ' && c != '\t') { if (!(c == '\n' && multiline > 0)) { ungetChar(c); return skipped; } } skipped++; } } private void fail(String s) throws TextParseException { throw new TextParseException(filename + ":" + line + ": " + s); } private void checkUnbalancedParens() throws TextParseException { if (multiline > 0) fail("unbalanced parentheses"); } /** * Gets the next token from a tokenizer. * @param wantWhitespace If true, leading whitespace will be returned as a * token. * @param wantComment If true, comments are returned as tokens. * @return The next token in the stream. * @throws TextParseException The input was invalid. * @throws IOException An I/O error occurred. */ public Token get(boolean wantWhitespace, boolean wantComment) throws IOException { int type; int c; if (ungottenToken) { ungottenToken = false; if (current.type == WHITESPACE) { if (wantWhitespace) return current; } else if (current.type == COMMENT) { if (wantComment) return current; } else return current; } int skipped = skipWhitespace(); if (skipped > 0 && wantWhitespace) return current.set(WHITESPACE, null); type = IDENTIFIER; sb.setLength(0); while (true) { c = getChar(); if (c == -1 || delimiters.indexOf(c) != -1) { if (c == -1) { if (quoting) fail("newline in quoted string"); else if (sb.length() == 0) return current.set(EOF, null); else return current.set(type, sb); } if (sb.length() == 0) { if (c == '(') { multiline++; skipWhitespace(); continue; } else if (c == ')') { if (multiline <= 0) fail("invalid close " + "parenthesis"); multiline--; skipWhitespace(); continue; } else if (c == '"') { if (!quoting) { quoting = true; delimiters = quotes; type = QUOTED_STRING; } else { quoting = false; delimiters = delim; skipWhitespace(); } continue; } else if (c == '\n') { return current.set(EOL, null); } else if (c == ';') { while (true) { c = getChar(); if (c == '\n' || c == -1) break; sb.append((char)c); } if (wantComment) { ungetChar(c); return current.set(COMMENT, sb); } else if (c == -1) { checkUnbalancedParens(); return current.set(EOF, null); } else if (multiline > 0) { skipWhitespace(); sb.setLength(0); continue; } else return current.set(EOL, null); } else throw new IllegalStateException(); } else ungetChar(c); break; } else if (c == '\\') { c = getChar(); if (c == -1) fail("unterminated escape sequence"); + sb.append('\\'); } sb.append((char)c); } if (sb.length() == 0) { checkUnbalancedParens(); return current.set(EOF, null); } return current.set(type, sb); } /** * Gets the next token from a tokenizer, ignoring whitespace and comments. * @return The next token in the stream. * @throws TextParseException The input was invalid. * @throws IOException An I/O error occurred. */ public Token get() throws IOException { return get(false, false); } /** * Returns a token to the stream, so that it will be returned by the next call * to get(). * @throws IllegalStateException There are already ungotten tokens. */ public void unget() { if (ungottenToken) throw new IllegalStateException ("Cannot unget multiple tokens"); ungottenToken = true; } /** * Gets the next token from a tokenizer and converts it to a string. * @return The next token in the stream, as a string. * @throws TextParseException The input was invalid or not a string. * @throws IOException An I/O error occurred. */ public String getString() throws IOException { Token next = get(); if (!next.isString()) { fail("expected a string"); } return next.value; } /** * Gets the next token from a tokenizer, ensures it is an unquoted string, * and converts it to a string. * @return The next token in the stream, as a string. * @throws TextParseException The input was invalid or not an unquoted string. * @throws IOException An I/O error occurred. */ public String getIdentifier() throws IOException { Token next = get(); if (next.type != IDENTIFIER) { fail("expected an identifier"); } return next.value; } /** * Gets the next token from a tokenizer and converts it to a long. * @return The next token in the stream, as a long. * @throws TextParseException The input was invalid or not a long. * @throws IOException An I/O error occurred. */ public long getLong() throws IOException { String next = getIdentifier(); if (!Character.isDigit(next.charAt(0))) fail("expecting an integer"); try { return Long.parseLong(next); } catch (NumberFormatException e) { fail("expecting an integer"); return 0; } } /** * Gets the next token from a tokenizer and converts it to an unsigned 32 bit * integer. * @return The next token in the stream, as an unsigned 32 bit integer. * @throws TextParseException The input was invalid or not an unsigned 32 * bit integer. * @throws IOException An I/O error occurred. */ public long getUInt32() throws IOException { long l = getLong(); if (l < 0 || l > 0xFFFFFFFFL) fail("expecting an 32 bit unsigned integer"); return l; } /** * Gets the next token from a tokenizer and converts it to an unsigned 16 bit * integer. * @return The next token in the stream, as an unsigned 16 bit integer. * @throws TextParseException The input was invalid or not an unsigned 16 * bit integer. * @throws IOException An I/O error occurred. */ public int getUInt16() throws IOException { long l = getLong(); if (l < 0 || l > 0xFFFFL) fail("expecting an 16 bit unsigned integer"); return (int) l; } /** * Gets the next token from a tokenizer and converts it to an unsigned 8 bit * integer. * @return The next token in the stream, as an unsigned 8 bit integer. * @throws TextParseException The input was invalid or not an unsigned 8 * bit integer. * @throws IOException An I/O error occurred. */ public int getUInt8() throws IOException { long l = getLong(); if (l < 0 || l > 0xFFL) fail("expecting an 8 bit unsigned integer"); return (int) l; } /** * Gets the next token from a tokenizer and converts it to a double. * @return The next token in the stream, as a double. * @throws TextParseException The input was invalid or not a double. * @throws IOException An I/O error occurred. */ public double getDouble() throws IOException { String next = getIdentifier(); if (!Character.isDigit(next.charAt(0))) fail("expecting an integer"); try { return Double.parseDouble(next); } catch (NumberFormatException e) { fail("expecting an floating point value"); return 0; } } /** * Gets the next token from a tokenizer and converts it to an integer * representing a TTL (which may be encoded in the BIND TTL format). * @return The next token in the stream, as a integer. * @throws TextParseException The input was invalid or not a valid TTL. * @throws IOException An I/O error occurred. * @see TTL */ public int getTTL() throws IOException { String next = getIdentifier(); try { return TTL.parseTTL(next); } catch (NumberFormatException e) { fail("invalid TTL: " + next); return 0; } } /** * Gets the next token from a tokenizer and converts it to a name. * @param origin The origin to append to relative names. * @return The next token in the stream, as a name. * @throws TextParseException The input was invalid or not a valid name. * @throws IOException An I/O error occurred. * @throws RelativeNameException The parsed name was relative, even with the * origin. * @see Name */ public Name getName(Name origin) throws IOException { try { Name name = Name.fromString(getIdentifier(), origin); if (!name.isAbsolute()) throw new RelativeNameException(name); return name; } catch (TextParseException e) { fail(e.getMessage()); return null; } } /** * Gets the next token from a tokenizer, which must be an EOL or EOF. * @throws TextParseException The input was invalid or not an EOL or EOF token. * @throws IOException An I/O error occurred. */ public void getEOL() throws IOException { Token next = get(); if (next.type != EOL && next.type != EOF) { fail("expecting EOL or EOF"); } } }
true
true
public Token get(boolean wantWhitespace, boolean wantComment) throws IOException { int type; int c; if (ungottenToken) { ungottenToken = false; if (current.type == WHITESPACE) { if (wantWhitespace) return current; } else if (current.type == COMMENT) { if (wantComment) return current; } else return current; } int skipped = skipWhitespace(); if (skipped > 0 && wantWhitespace) return current.set(WHITESPACE, null); type = IDENTIFIER; sb.setLength(0); while (true) { c = getChar(); if (c == -1 || delimiters.indexOf(c) != -1) { if (c == -1) { if (quoting) fail("newline in quoted string"); else if (sb.length() == 0) return current.set(EOF, null); else return current.set(type, sb); } if (sb.length() == 0) { if (c == '(') { multiline++; skipWhitespace(); continue; } else if (c == ')') { if (multiline <= 0) fail("invalid close " + "parenthesis"); multiline--; skipWhitespace(); continue; } else if (c == '"') { if (!quoting) { quoting = true; delimiters = quotes; type = QUOTED_STRING; } else { quoting = false; delimiters = delim; skipWhitespace(); } continue; } else if (c == '\n') { return current.set(EOL, null); } else if (c == ';') { while (true) { c = getChar(); if (c == '\n' || c == -1) break; sb.append((char)c); } if (wantComment) { ungetChar(c); return current.set(COMMENT, sb); } else if (c == -1) { checkUnbalancedParens(); return current.set(EOF, null); } else if (multiline > 0) { skipWhitespace(); sb.setLength(0); continue; } else return current.set(EOL, null); } else throw new IllegalStateException(); } else ungetChar(c); break; } else if (c == '\\') { c = getChar(); if (c == -1) fail("unterminated escape sequence"); } sb.append((char)c); } if (sb.length() == 0) { checkUnbalancedParens(); return current.set(EOF, null); } return current.set(type, sb); }
public Token get(boolean wantWhitespace, boolean wantComment) throws IOException { int type; int c; if (ungottenToken) { ungottenToken = false; if (current.type == WHITESPACE) { if (wantWhitespace) return current; } else if (current.type == COMMENT) { if (wantComment) return current; } else return current; } int skipped = skipWhitespace(); if (skipped > 0 && wantWhitespace) return current.set(WHITESPACE, null); type = IDENTIFIER; sb.setLength(0); while (true) { c = getChar(); if (c == -1 || delimiters.indexOf(c) != -1) { if (c == -1) { if (quoting) fail("newline in quoted string"); else if (sb.length() == 0) return current.set(EOF, null); else return current.set(type, sb); } if (sb.length() == 0) { if (c == '(') { multiline++; skipWhitespace(); continue; } else if (c == ')') { if (multiline <= 0) fail("invalid close " + "parenthesis"); multiline--; skipWhitespace(); continue; } else if (c == '"') { if (!quoting) { quoting = true; delimiters = quotes; type = QUOTED_STRING; } else { quoting = false; delimiters = delim; skipWhitespace(); } continue; } else if (c == '\n') { return current.set(EOL, null); } else if (c == ';') { while (true) { c = getChar(); if (c == '\n' || c == -1) break; sb.append((char)c); } if (wantComment) { ungetChar(c); return current.set(COMMENT, sb); } else if (c == -1) { checkUnbalancedParens(); return current.set(EOF, null); } else if (multiline > 0) { skipWhitespace(); sb.setLength(0); continue; } else return current.set(EOL, null); } else throw new IllegalStateException(); } else ungetChar(c); break; } else if (c == '\\') { c = getChar(); if (c == -1) fail("unterminated escape sequence"); sb.append('\\'); } sb.append((char)c); } if (sb.length() == 0) { checkUnbalancedParens(); return current.set(EOF, null); } return current.set(type, sb); }
diff --git a/source/de/anomic/http/httpdFileHandler.java b/source/de/anomic/http/httpdFileHandler.java index 810773ef4..ae217dc25 100644 --- a/source/de/anomic/http/httpdFileHandler.java +++ b/source/de/anomic/http/httpdFileHandler.java @@ -1,1005 +1,1006 @@ // httpdFileHandler.java // ----------------------- // (C) by Michael Peter Christen; [email protected] // first published on http://www.anomic.de // Frankfurt, Germany, 2004, 2005 // last major change: 05.10.2005 // // 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 // // Using this software in any meaning (reading, learning, copying, compiling, // running) means that you agree that the Author(s) is (are) not responsible // for cost, loss of data or any harm that may be caused directly or indirectly // by usage of this softare or this documentation. The usage of this software // is on your own risk. The installation and usage (starting/running) of this // software may allow other people or application to access your computer and // any attached devices and is highly dependent on the configuration of the // software which must be done by the user of the software; the author(s) is // (are) also not responsible for proper configuration and usage of the // software, even if provoked by documentation provided together with // the software. // // Any changes to this file according to the GPL as documented in the file // gpl.txt aside this file in the shipment you received can be done to the // lines that follows this copyright notice here, but changes must not be // done inside the copyright notive above. A re-distribution must contain // the intact and unchanged copyright notice. // Contributions and changes to the program code must be marked as such. /* Class documentation: this class provides a file servlet and CGI interface for the httpd server. Whenever this server is addressed to load a local file, this class searches for the file in the local path as configured in the setting property 'rootPath' The servlet loads the file and returns it to the client. Every file can also act as an template for the built-in CGI interface. There is no specific path for CGI functions. CGI functionality is triggered, if for the file to-be-served 'template.html' also a file 'template.class' exists. Then, the class file is called with the GET/POST properties that are attached to the http call. Possible variable hand-over are: - form method GET - form method POST, enctype text/plain - form method POST, enctype multipart/form-data The class that creates the CGI respond must have at least one static method of the form public static java.util.Hashtable respond(java.util.HashMap, serverSwitch) In the HashMap, the GET/POST variables are handed over. The return value is a Property object that contains replacement key/value pairs for the patterns in the template file. The templates must have the form either '#['<name>']#' for single attributes, or '#{'<enumname>'}#' and '#{/'<enumname>'}#' for enumerations of values '#['<value>']#'. A single value in repetitions/enumerations in the template has the property key '_'<enumname><count>'_'<value> Please see also the example files 'test.html' and 'test.java' */ package de.anomic.http; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PushbackInputStream; import java.io.UnsupportedEncodingException; import java.lang.ref.SoftReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URLDecoder; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.logging.Level; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import javax.imageio.ImageIO; import de.anomic.plasma.plasmaParser; import de.anomic.plasma.plasmaSwitchboard; import de.anomic.server.serverByteBuffer; import de.anomic.server.serverClassLoader; import de.anomic.server.serverCore; import de.anomic.server.serverFileUtils; import de.anomic.server.serverObjects; import de.anomic.server.serverSwitch; import de.anomic.server.servletProperties; import de.anomic.server.logging.serverLog; import de.anomic.ymage.ymageMatrix; public final class httpdFileHandler extends httpdAbstractHandler implements httpdHandler { private static final boolean safeServletsMode = false; // if true then all servlets are called synchronized // class variables private static final Properties mimeTable = new Properties(); private static final serverClassLoader provider; private static final HashMap templates = new HashMap(); private static serverSwitch switchboard; private static plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard(); private static File htRootPath = null; private static File htDocsPath = null; private static File htTemplatePath = null; private static String[] defaultFiles = null; private static File htDefaultPath = null; private static File htLocalePath = null; private static final HashMap templateCache; private static final HashMap templateMethodCache; public static boolean useTemplateCache = false; static { useTemplateCache = plasmaSwitchboard.getSwitchboard().getConfig("enableTemplateCache","true").equalsIgnoreCase("true"); templateCache = (useTemplateCache)? new HashMap() : new HashMap(0); templateMethodCache = (useTemplateCache) ? new HashMap() : new HashMap(0); // create a class loader provider = new serverClassLoader(/*this.getClass().getClassLoader()*/); } public httpdFileHandler(serverSwitch switchboard) { // creating a logger this.theLogger = new serverLog("FILEHANDLER"); if (httpdFileHandler.switchboard == null) { httpdFileHandler.switchboard = switchboard; if (mimeTable.size() == 0) { // load the mime table String mimeTablePath = switchboard.getConfig("mimeConfig",""); BufferedInputStream mimeTableInputStream = null; try { serverLog.logConfig("HTTPDFiles", "Loading mime mapping file " + mimeTablePath); mimeTableInputStream = new BufferedInputStream(new FileInputStream(new File(switchboard.getRootPath(), mimeTablePath))); mimeTable.load(mimeTableInputStream); } catch (Exception e) { serverLog.logSevere("HTTPDFiles", "ERROR: path to configuration file or configuration invalid\n" + e); System.exit(1); } finally { if (mimeTableInputStream != null) try { mimeTableInputStream.close(); } catch (Exception e1) {} } } // create default files array initDefaultPath(); // create a htRootPath: system pages if (htRootPath == null) { htRootPath = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot")); if (!(htRootPath.exists())) htRootPath.mkdir(); } // create a htDocsPath: user defined pages if (htDocsPath == null) { htDocsPath = new File(switchboard.getRootPath(), switchboard.getConfig("htDocsPath", "htdocs")); if (!(htDocsPath.exists())) htDocsPath.mkdir(); } // create a htTemplatePath if (htTemplatePath == null) { htTemplatePath = new File(switchboard.getRootPath(), switchboard.getConfig("htTemplatePath","htroot/env/templates")); if (!(htTemplatePath.exists())) htTemplatePath.mkdir(); } //This is now handles by #%env/templates/foo%# //if (templates.size() == 0) templates.putAll(httpTemplate.loadTemplates(htTemplatePath)); // create htLocaleDefault, htLocalePath if (htDefaultPath == null) htDefaultPath = new File(switchboard.getRootPath(), switchboard.getConfig("htDefaultPath","htroot")); if (htLocalePath == null) htLocalePath = new File(switchboard.getConfig("locale.translated_html","DATA/LOCALE/htroot")); } } public static final void initDefaultPath() { // create default files array defaultFiles = switchboard.getConfig("defaultFiles","index.html").split(","); if (defaultFiles.length == 0) defaultFiles = new String[] {"index.html"}; } /** Returns a path to the localized or default file according to the locale.language (from he switchboard) * @param path relative from htroot */ public static File getLocalizedFile(String path){ return getLocalizedFile(path, switchboard.getConfig("locale.language","default")); } /** Returns a path to the localized or default file according to the parameter localeSelection * @param path relative from htroot * @param localeSelection language of localized file; locale.language from switchboard is used if localeSelection.equals("") */ public static File getLocalizedFile(String path, String localeSelection){ if (htDefaultPath == null) htDefaultPath = new File(switchboard.getRootPath(), switchboard.getConfig("htDefaultPath","htroot")); if (htLocalePath == null) htLocalePath = new File(switchboard.getRootPath(), switchboard.getConfig("locale.translated_html","DATA/LOCALE/htroot")); if (!(localeSelection.equals("default"))) { File localePath = new File(htLocalePath, localeSelection + "/" + path); if (localePath.exists()) // avoid "NoSuchFile" troubles if the "localeSelection" is misspelled return localePath; } return new File(htDefaultPath, path); } // private void textMessage(OutputStream out, int retcode, String body) throws IOException { // httpd.sendRespondHeader( // this.connectionProperties, // the connection properties // out, // the output stream // "HTTP/1.1", // the http version that should be used // retcode, // the http status code // null, // the http status message // "text/plain", // the mimetype // body.length(), // the content length // httpc.nowDate(), // the modification date // null, // the expires date // null, // cookies // null, // content encoding // null); // transfer encoding // out.write(body.getBytes()); // out.flush(); // } private httpHeader getDefaultHeaders(String path) { httpHeader headers = new httpHeader(); String ext; int pos; if ((pos = path.lastIndexOf('.')) < 0) { ext = ""; } else { ext = path.substring(pos + 1).toLowerCase(); } headers.put(httpHeader.SERVER, "AnomicHTTPD (www.anomic.de)"); headers.put(httpHeader.DATE, httpc.dateString(httpc.nowDate())); if(!(plasmaParser.mediaExtContains(ext))){ headers.put(httpHeader.PRAGMA, "no-cache"); } return headers; } public void doGet(Properties conProp, httpHeader requestHeader, OutputStream response) throws IOException { doResponse(conProp, requestHeader, response, null); } public void doHead(Properties conProp, httpHeader requestHeader, OutputStream response) throws IOException { doResponse(conProp, requestHeader, response, null); } public void doPost(Properties conProp, httpHeader requestHeader, OutputStream response, PushbackInputStream body) throws IOException { doResponse(conProp, requestHeader, response, body); } public void doResponse(Properties conProp, httpHeader requestHeader, OutputStream out, InputStream body) { this.connectionProperties = conProp; String path = null; try { // getting some connection properties String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD); path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH); String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given String httpVersion= conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER); // check hack attacks in path if (path.indexOf("..") >= 0) { httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null); return; } // url decoding of path try { path = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { // This should never occur assert(false) : "UnsupportedEncodingException: " + e.getMessage(); } // check permission/granted access String authorization = (String) requestHeader.get(httpHeader.AUTHORIZATION); String adminAccountBase64MD5 = switchboard.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, ""); int pos = path.lastIndexOf("."); if ((path.substring(0,(pos==-1)?path.length():pos)).endsWith("_p") && (adminAccountBase64MD5.length() != 0)) { //authentication required //userDB if(sb.userDB.hasAdminRight(authorization, conProp.getProperty("CLIENTIP"), requestHeader.getHeaderCookies())){ //Authentication successful. remove brute-force flag serverCore.bfHost.remove(conProp.getProperty("CLIENTIP")); //static }else if(authorization != null && httpd.staticAdminAuthenticated(authorization.trim().substring(6), switchboard)==4){ //Authentication successful. remove brute-force flag serverCore.bfHost.remove(conProp.getProperty("CLIENTIP")); //no auth }else if (authorization == null) { // no authorization given in response. Ask for that httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\""); //httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); servletProperties tp=new servletProperties(); tp.put("returnto", path); //TODO: separate errorpage Wrong Login / No Login httpd.sendRespondError(conProp, out, 5, 401, "Wrong Authentication", "", new File("proxymsg/authfail.inc"), tp, null, headers); return; } else { // a wrong authentication was given or the userDB user does not have admin access. Ask again String clientIP = conProp.getProperty("CLIENTIP", "unknown-host"); serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'"); Integer attempts = (Integer) serverCore.bfHost.get(clientIP); if (attempts == null) serverCore.bfHost.put(clientIP, new Integer(1)); else serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1)); httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\""); httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); return; } } // parse arguments serverObjects args = new serverObjects(); int argc; if (argsString == null) { // no args here, maybe a POST with multipart extension int length = 0; //System.out.println("HEADER: " + requestHeader.toString()); // DEBUG if (method.equals(httpHeader.METHOD_POST)) { GZIPInputStream gzipBody = null; if (requestHeader.containsKey(httpHeader.CONTENT_LENGTH)) { length = Integer.parseInt((String) requestHeader.get(httpHeader.CONTENT_LENGTH)); } else if (requestHeader.gzip()) { length = -1; gzipBody = new GZIPInputStream(body); } // } else { // httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null); // return; // } // if its a POST, it can be either multipart or as args in the body if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) && (((String) requestHeader.get(httpHeader.CONTENT_TYPE)).toLowerCase().startsWith("multipart"))) { // parse multipart HashMap files = httpd.parseMultipart(requestHeader, args, (gzipBody!=null)?gzipBody:body, length); // integrate these files into the args if (files != null) { Iterator fit = files.entrySet().iterator(); Map.Entry entry; while (fit.hasNext()) { entry = (Map.Entry) fit.next(); args.put(((String) entry.getKey()) + "$file", entry.getValue()); } } argc = Integer.parseInt((String) requestHeader.get("ARGC")); } else { // parse args in body argc = httpd.parseArgs(args, (gzipBody!=null)?gzipBody:body, length); } } else { // no args argsString = null; args = null; argc = 0; } } else { // simple args in URL (stuff after the "?") argc = httpd.parseArgs(args, argsString); } // check for cross site scripting - attacks in request arguments if (argc > 0) { // check all values for occurrences of script values Enumeration e = args.elements(); // enumeration of values Object val; while (e.hasMoreElements()) { val = e.nextElement(); if ((val != null) && (val instanceof String) && (((String) val).indexOf("<script") >= 0)) { // deny request httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null); return; } } } // we are finished with parsing // the result of value hand-over is in args and argc if (path.length() == 0) { httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null); out.flush(); return; } File targetClass=null; // locate the file if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash // a different language can be desired (by i.e. ConfigBasic.html) than the one stored in the locale.language String localeSelection = switchboard.getConfig("locale.language","default"); if (args != null && (args.containsKey("language"))) { // TODO 9.11.06 Bost: a class with information about available languages is needed. // the indexOf(".") is just a workaround because there from ConfigLanguage.html commes "de.lng" and // from ConfigBasic.html comes just "de" in the "language" parameter localeSelection = args.get("language", localeSelection); if (localeSelection.indexOf(".") != -1) localeSelection = localeSelection.substring(0, localeSelection.indexOf(".")); } File targetFile = getLocalizedFile(path, localeSelection); String targetExt = conProp.getProperty("EXT",""); targetClass = rewriteClassFile(new File(htDefaultPath, path)); if (path.endsWith("/")) { String testpath; // attach default file name for (int i = 0; i < defaultFiles.length; i++) { testpath = path + defaultFiles[i]; targetFile = getOverlayedFile(testpath); targetClass=getOverlayedClass(testpath); if (targetFile.exists()) { path = testpath; break; } } //no defaultfile, send a dirlisting if(targetFile == null || !targetFile.exists()){ String dirlistFormat = (args==null)?"html":args.get("format","html"); targetExt = dirlistFormat; // this is needed to set the mime type correctly targetFile = getOverlayedFile("/htdocsdefault/dir." + dirlistFormat); targetClass=getOverlayedClass("/htdocsdefault/dir." + dirlistFormat); if(! (( targetFile != null && targetFile.exists()) && ( targetClass != null && targetClass.exists())) ){ httpd.sendRespondError(this.connectionProperties,out,3,500,"dir." + dirlistFormat + " or dir.class not found.",null,null); } } }else{ //XXX: you cannot share a .png/.gif file with a name like a class in htroot. if ( !(targetFile.exists()) && !((path.endsWith("png")||path.endsWith("gif")||path.endsWith(".stream"))&&targetClass!=null ) ){ targetFile = new File(htDocsPath, path); targetClass = rewriteClassFile(new File(htDocsPath, path)); } } //File targetClass = rewriteClassFile(targetFile); //We need tp here servletProperties tp = new servletProperties(); Date targetDate; boolean nocache = false; if ((targetClass != null) && (path.endsWith("png"))) { // call an image-servlet to produce an on-the-fly - generated image Object img = null; try { requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); // in case that there are no args given, args = null or empty hashmap img = invokeServlet(targetClass, requestHeader, args); } catch (InvocationTargetException e) { this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" + e.getMessage() + " target exception at " + targetClass + ": " + e.getTargetException().toString() + ":" + e.getTargetException().getMessage() + "; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e); targetClass = null; } if (img == null) { // error with image generation; send file-not-found httpd.sendRespondError(this.connectionProperties,out,3,404,"File not Found",null,null); } else { if (img instanceof ymageMatrix) { ymageMatrix yp = (ymageMatrix) img; // send an image to client targetDate = new Date(System.currentTimeMillis()); nocache = true; String mimeType = mimeTable.getProperty(targetExt, "text/html"); // generate an byte array from the generated image serverByteBuffer baos = new serverByteBuffer(); // ymagePNGEncoderJDE jde = new // ymagePNGEncoderJDE((ymageMatrixPainter) yp, // ymagePNGEncoderJDE.FILTER_NONE, 0); // byte[] result = jde.pngEncode(); ImageIO.write(yp.getImage(), targetExt, baos); byte[] result = baos.toByteArray(); baos.close(); baos = null; // write the array to the client httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, null, null, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { //Thread.sleep(200); // see below serverFileUtils.write(result, out); } } if (img instanceof Image) { Image i = (Image) img; // send an image to client targetDate = new Date(System.currentTimeMillis()); nocache = true; String mimeType = mimeTable.getProperty(targetExt, "text/html"); // generate an byte array from the generated image int width = i.getWidth(null); if (width < 0) width = 96; // bad hack int height = i.getHeight(null); if (height < 0) height = 96; // bad hack BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); bi.createGraphics().drawImage(i, 0, 0, width, height, null); serverByteBuffer baos = new serverByteBuffer(); ImageIO.write(bi, targetExt, baos); byte[] result = baos.toByteArray(); baos.close(); baos = null; // write the array to the client httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, null, null, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { //Thread.sleep(200); // see below serverFileUtils.write(result, out); } } } } else if ((targetClass != null) && (path.endsWith(".stream"))) { // call rewrite-class requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); requestHeader.put(httpHeader.CONNECTION_PROP_INPUTSTREAM, body); requestHeader.put(httpHeader.CONNECTION_PROP_OUTPUTSTREAM, out); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null); // in case that there are no args given, args = null or empty hashmap /* servletProperties tp = (servlerObjects) */ invokeServlet(targetClass, requestHeader, args); this.forceConnectionClose(); return; } else if ((targetFile.exists()) && (targetFile.canRead())) { // we have found a file that can be written to the client // if this file uses templates, then we use the template // re-write - method to create an result String mimeType = mimeTable.getProperty(targetExt,"text/html"); boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT","")); if (path.endsWith("html") || path.endsWith("xml") || path.endsWith("rss") || path.endsWith("csv") || path.endsWith("pac") || path.endsWith("src") || path.endsWith("vcf") || path.endsWith("/") || path.equals("/robots.txt")) { /*targetFile = getLocalizedFile(path); if (!(targetFile.exists())) { // try to find that file in the htDocsPath File trialFile = new File(htDocsPath, path); if (trialFile.exists()) targetFile = trialFile; }*/ // call rewrite-class if (targetClass == null) { targetDate = new Date(targetFile.lastModified()); } else { // CGI-class: call the class to create a property for rewriting try { requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); // in case that there are no args given, args = null or empty hashmap - Object tmp = invokeServlet(targetClass, requestHeader, args); - if(tmp instanceof servletProperties){ - tp=(servletProperties)tmp; - }else{ - tp=new servletProperties((serverObjects)tmp); + Object tmp = invokeServlet(targetClass, requestHeader, args); + if (tp == null) { + // if no args given, then tp will be an empty Hashtable object (not null) + tp = new servletProperties(); + } else if (tmp instanceof servletProperties) { + tp = (servletProperties) tmp; + } else { + tp = new servletProperties((serverObjects) tmp); } - // if no args given , then tp will be an empty Hashtable object (not null) - if (tp == null) tp = new servletProperties(); // check if the servlets requests authentification if (tp.containsKey(servletProperties.ACTION_AUTHENTICATE)) { // handle brute-force protection if (authorization != null) { String clientIP = conProp.getProperty("CLIENTIP", "unknown-host"); serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'"); Integer attempts = (Integer) serverCore.bfHost.get(clientIP); if (attempts == null) serverCore.bfHost.put(clientIP, new Integer(1)); else serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1)); } // send authentication request to browser httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get(servletProperties.ACTION_AUTHENTICATE, "") + "\""); httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); return; } else if (tp.containsKey(servletProperties.ACTION_LOCATION)) { String location = tp.get(servletProperties.ACTION_LOCATION, ""); if (location.length() == 0) location = path; httpHeader headers = getDefaultHeaders(path); headers.setCookieVector(tp.getOutgoingHeader().getCookieVector()); //put the cookies into the new header TODO: can we put all headerlines, without trouble? headers.put(httpHeader.LOCATION,location); httpd.sendRespondHeader(conProp,out,httpVersion,302,headers); return; } // add the application version, the uptime and the client name to every rewrite table tp.put(servletProperties.PEER_STAT_VERSION, switchboard.getConfig("version", "")); tp.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - Long.parseLong(switchboard.getConfig("startupTime","0"))) / 1000) / 60); // uptime in minutes tp.put(servletProperties.PEER_STAT_CLIENTNAME, switchboard.getConfig("peerName", "anomic")); //System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug } catch (InvocationTargetException e) { if (e.getCause() instanceof InterruptedException) { throw new InterruptedException(e.getCause().getMessage()); } this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" + e.getMessage() + " target exception at " + targetClass + ": " + e.getTargetException().toString() + ":" + e.getTargetException().getMessage(),e); targetClass = null; throw e; } targetDate = new Date(System.currentTimeMillis()); nocache = true; } // read templates tp.putAll(templates); // rewrite the file InputStream fis = null; // read the file/template byte[] templateContent = null; if (useTemplateCache) { long fileSize = targetFile.length(); if (fileSize <= 512 * 1024) { // read from cache SoftReference ref = (SoftReference) templateCache.get(targetFile); if (ref != null) { templateContent = (byte[]) ref.get(); if (templateContent == null) templateCache.remove(targetFile); } if (templateContent == null) { // loading the content of the template file into // a byte array templateContent = serverFileUtils.read(targetFile); // storing the content into the cache ref = new SoftReference(templateContent); templateCache.put(targetFile, ref); if (this.theLogger.isLoggable(Level.FINEST)) this.theLogger.logFinest("Cache MISS for file " + targetFile); } else { if (this.theLogger.isLoggable(Level.FINEST)) this.theLogger.logFinest("Cache HIT for file " + targetFile); } // creating an inputstream needed by the template // rewrite function fis = new ByteArrayInputStream(templateContent); templateContent = null; } else { // read from file directly fis = new BufferedInputStream(new FileInputStream(targetFile)); } } else { fis = new BufferedInputStream(new FileInputStream(targetFile)); } // write the array to the client // we can do that either in standard mode (whole thing completely) or in chunked mode // since yacy clients do not understand chunked mode, we use this only for communication with the administrator boolean yacyClient = requestHeader.userAgent().startsWith("yacy"); boolean chunked = !method.equals(httpHeader.METHOD_HEAD) && !yacyClient && httpVersion.equals(httpHeader.HTTP_VERSION_1_1); if (chunked) { // send page in chunks and parse SSIs serverByteBuffer o = new serverByteBuffer(); // apply templates httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, -1, targetDate, null, tp.getOutgoingHeader(), null, "chunked", nocache); // send the content in chunked parts, see RFC 2616 section 3.6.1 httpChunkedOutputStream chos = new httpChunkedOutputStream(out); httpSSI.writeSSI(targetFile, o, chos); //chos.write(result); chos.finish(); } else { // send page as whole thing, SSIs are not possible String contentEncoding = (zipContent) ? "gzip" : null; // apply templates serverByteBuffer o = new serverByteBuffer(); if (zipContent) { GZIPOutputStream zippedOut = new GZIPOutputStream(o); httpTemplate.writeTemplate(fis, zippedOut, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); zippedOut.finish(); zippedOut.flush(); zippedOut.close(); zippedOut = null; } else { httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); } if (method.equals(httpHeader.METHOD_HEAD)) { httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, o.length(), targetDate, null, tp.getOutgoingHeader(), contentEncoding, null, nocache); } else { byte[] result = o.toByteArray(); // this interrupts streaming (bad idea!) httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, tp.getOutgoingHeader(), contentEncoding, null, nocache); serverFileUtils.write(result, out); } } } else { // no html int statusCode = 200; int rangeStartOffset = 0; httpHeader header = new httpHeader(); // adding the accept ranges header header.put(httpHeader.ACCEPT_RANGES, "bytes"); // reading the files md5 hash if availabe and use it as ETAG of the resource String targetMD5 = null; File targetMd5File = new File(targetFile + ".md5"); try { if (targetMd5File.exists()) { //String description = null; targetMD5 = new String(serverFileUtils.read(targetMd5File)); pos = targetMD5.indexOf('\n'); if (pos >= 0) { //description = targetMD5.substring(pos + 1); targetMD5 = targetMD5.substring(0, pos); } // using the checksum as ETAG header header.put(httpHeader.ETAG, targetMD5); } } catch (IOException e) { e.printStackTrace(); } if (requestHeader.containsKey(httpHeader.RANGE)) { Object ifRange = requestHeader.ifRange(); if ((ifRange == null)|| (ifRange instanceof Date && targetFile.lastModified() == ((Date)ifRange).getTime()) || (ifRange instanceof String && ifRange.equals(targetMD5))) { String rangeHeaderVal = ((String) requestHeader.get(httpHeader.RANGE)).trim(); if (rangeHeaderVal.startsWith("bytes=")) { String rangesVal = rangeHeaderVal.substring("bytes=".length()); String[] ranges = rangesVal.split(","); if ((ranges.length == 1)&&(ranges[0].endsWith("-"))) { rangeStartOffset = Integer.valueOf(ranges[0].substring(0,ranges[0].length()-1)).intValue(); statusCode = 206; if (header == null) header = new httpHeader(); header.put(httpHeader.CONTENT_RANGE, "bytes " + rangeStartOffset + "-" + (targetFile.length()-1) + "/" + targetFile.length()); } } } } // write the file to the client targetDate = new Date(targetFile.lastModified()); long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset; String contentEncoding = (zipContent)?"gzip":null; String transferEncoding = (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1))?null:(zipContent)?"chunked":null; if (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1) && zipContent) forceConnectionClose(); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, statusCode, null, mimeType, contentLength, targetDate, null, header, contentEncoding, transferEncoding, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { httpChunkedOutputStream chunkedOut = null; GZIPOutputStream zipped = null; OutputStream newOut = out; if (transferEncoding != null) { chunkedOut = new httpChunkedOutputStream(newOut); newOut = chunkedOut; } if (contentEncoding != null) { zipped = new GZIPOutputStream(newOut); newOut = zipped; } serverFileUtils.copyRange(targetFile,newOut,rangeStartOffset); if (zipped != null) { zipped.flush(); zipped.finish(); } if (chunkedOut != null) { chunkedOut.finish(); } } // check mime type again using the result array: these are 'magics' // if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html"); // else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html"); // else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html"); //System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println(); } } else { httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null); return; } } catch (Exception e) { try { // doing some errorhandling ... int httpStatusCode = 400; String httpStatusText = null; StringBuffer errorMessage = new StringBuffer(); Exception errorExc = null; String errorMsg = e.getMessage(); if ( (e instanceof InterruptedException) || ((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted())) ) { errorMessage.append("Interruption detected while processing query."); httpStatusCode = 503; } else { if ((errorMsg != null) && ( errorMsg.startsWith("Broken pipe") || errorMsg.startsWith("Connection reset") || errorMsg.startsWith("Software caused connection abort") )) { // client closed the connection, so we just end silently errorMessage.append("Client unexpectedly closed connection while processing query."); } else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) { errorMessage.append("Connection timed out."); } else { errorMessage.append("Unexpected error while processing query."); httpStatusCode = 500; errorExc = e; } } errorMessage.append("\nSession: ").append(Thread.currentThread().getName()) .append("\nQuery: ").append(path) .append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown")) .append("\nReason: ").append(e.toString()); if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) { // sending back an error message to the client // if we have not already send an http header httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, new String(errorMessage),errorExc); } else { // otherwise we close the connection this.forceConnectionClose(); } // if it is an unexpected error we log it if (httpStatusCode == 500) { this.theLogger.logWarning(new String(errorMessage),e); } } catch (Exception ee) { this.forceConnectionClose(); } } finally { try {out.flush();}catch (Exception e) {} if (((String)requestHeader.get(httpHeader.CONNECTION, "close")).indexOf("keep-alive") == -1) { // wait a little time until everything closes so that clients can read from the streams/sockets try {Thread.sleep(200);} catch (InterruptedException e) {} } } } public File getOverlayedClass(String path) { File targetClass; targetClass=rewriteClassFile(new File(htDefaultPath, path)); //works for default and localized files if(targetClass == null || !targetClass.exists()){ //works for htdocs targetClass=rewriteClassFile(new File(htDocsPath, path)); } return targetClass; } public File getOverlayedFile(String path) { File targetFile; targetFile = getLocalizedFile(path); if (!(targetFile.exists())){ targetFile = new File(htDocsPath, path); } return targetFile; } private void forceConnectionClose() { if (this.connectionProperties != null) { this.connectionProperties.setProperty(httpHeader.CONNECTION_PROP_PERSISTENT,"close"); } } private File rewriteClassFile(File template) { try { String f = template.getCanonicalPath(); int p = f.lastIndexOf("."); if (p < 0) return null; f = f.substring(0, p) + ".class"; //System.out.println("constructed class path " + f); File cf = new File(f); if (cf.exists()) return cf; return null; } catch (IOException e) { return null; } } private final Method rewriteMethod(File classFile) { Method m = null; // now make a class out of the stream try { if (useTemplateCache) { SoftReference ref = (SoftReference) templateMethodCache.get(classFile); if (ref != null) { m = (Method) ref.get(); if (m == null) { templateMethodCache.remove(classFile); } else { this.theLogger.logFine("Cache HIT for file " + classFile); return m; } } } //System.out.println("**DEBUG** loading class file " + classFile); Class c = provider.loadClass(classFile); Class[] params = new Class[] { httpHeader.class, serverObjects.class, serverSwitch.class }; m = c.getMethod("respond", params); if (useTemplateCache) { // storing the method into the cache SoftReference ref = new SoftReference(m); templateMethodCache.put(classFile,ref); this.theLogger.logFine("Cache MISS for file " + classFile); } } catch (ClassNotFoundException e) { System.out.println("INTERNAL ERROR: class " + classFile + " is missing:" + e.getMessage()); } catch (NoSuchMethodException e) { System.out.println("INTERNAL ERROR: method respond not found in class " + classFile + ": " + e.getMessage()); } //System.out.println("found method: " + m.toString()); return m; } public Object invokeServlet(File targetClass, httpHeader request, serverObjects args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { Object result; if (safeServletsMode) synchronized (switchboard) { result = rewriteMethod(targetClass).invoke(null, new Object[] {request, args, switchboard}); } else { result = rewriteMethod(targetClass).invoke(null, new Object[] {request, args, switchboard}); } return result; } public void doConnect(Properties conProp, httpHeader requestHeader, InputStream clientIn, OutputStream clientOut) { throw new UnsupportedOperationException(); } }
false
true
public void doResponse(Properties conProp, httpHeader requestHeader, OutputStream out, InputStream body) { this.connectionProperties = conProp; String path = null; try { // getting some connection properties String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD); path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH); String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given String httpVersion= conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER); // check hack attacks in path if (path.indexOf("..") >= 0) { httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null); return; } // url decoding of path try { path = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { // This should never occur assert(false) : "UnsupportedEncodingException: " + e.getMessage(); } // check permission/granted access String authorization = (String) requestHeader.get(httpHeader.AUTHORIZATION); String adminAccountBase64MD5 = switchboard.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, ""); int pos = path.lastIndexOf("."); if ((path.substring(0,(pos==-1)?path.length():pos)).endsWith("_p") && (adminAccountBase64MD5.length() != 0)) { //authentication required //userDB if(sb.userDB.hasAdminRight(authorization, conProp.getProperty("CLIENTIP"), requestHeader.getHeaderCookies())){ //Authentication successful. remove brute-force flag serverCore.bfHost.remove(conProp.getProperty("CLIENTIP")); //static }else if(authorization != null && httpd.staticAdminAuthenticated(authorization.trim().substring(6), switchboard)==4){ //Authentication successful. remove brute-force flag serverCore.bfHost.remove(conProp.getProperty("CLIENTIP")); //no auth }else if (authorization == null) { // no authorization given in response. Ask for that httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\""); //httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); servletProperties tp=new servletProperties(); tp.put("returnto", path); //TODO: separate errorpage Wrong Login / No Login httpd.sendRespondError(conProp, out, 5, 401, "Wrong Authentication", "", new File("proxymsg/authfail.inc"), tp, null, headers); return; } else { // a wrong authentication was given or the userDB user does not have admin access. Ask again String clientIP = conProp.getProperty("CLIENTIP", "unknown-host"); serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'"); Integer attempts = (Integer) serverCore.bfHost.get(clientIP); if (attempts == null) serverCore.bfHost.put(clientIP, new Integer(1)); else serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1)); httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\""); httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); return; } } // parse arguments serverObjects args = new serverObjects(); int argc; if (argsString == null) { // no args here, maybe a POST with multipart extension int length = 0; //System.out.println("HEADER: " + requestHeader.toString()); // DEBUG if (method.equals(httpHeader.METHOD_POST)) { GZIPInputStream gzipBody = null; if (requestHeader.containsKey(httpHeader.CONTENT_LENGTH)) { length = Integer.parseInt((String) requestHeader.get(httpHeader.CONTENT_LENGTH)); } else if (requestHeader.gzip()) { length = -1; gzipBody = new GZIPInputStream(body); } // } else { // httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null); // return; // } // if its a POST, it can be either multipart or as args in the body if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) && (((String) requestHeader.get(httpHeader.CONTENT_TYPE)).toLowerCase().startsWith("multipart"))) { // parse multipart HashMap files = httpd.parseMultipart(requestHeader, args, (gzipBody!=null)?gzipBody:body, length); // integrate these files into the args if (files != null) { Iterator fit = files.entrySet().iterator(); Map.Entry entry; while (fit.hasNext()) { entry = (Map.Entry) fit.next(); args.put(((String) entry.getKey()) + "$file", entry.getValue()); } } argc = Integer.parseInt((String) requestHeader.get("ARGC")); } else { // parse args in body argc = httpd.parseArgs(args, (gzipBody!=null)?gzipBody:body, length); } } else { // no args argsString = null; args = null; argc = 0; } } else { // simple args in URL (stuff after the "?") argc = httpd.parseArgs(args, argsString); } // check for cross site scripting - attacks in request arguments if (argc > 0) { // check all values for occurrences of script values Enumeration e = args.elements(); // enumeration of values Object val; while (e.hasMoreElements()) { val = e.nextElement(); if ((val != null) && (val instanceof String) && (((String) val).indexOf("<script") >= 0)) { // deny request httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null); return; } } } // we are finished with parsing // the result of value hand-over is in args and argc if (path.length() == 0) { httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null); out.flush(); return; } File targetClass=null; // locate the file if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash // a different language can be desired (by i.e. ConfigBasic.html) than the one stored in the locale.language String localeSelection = switchboard.getConfig("locale.language","default"); if (args != null && (args.containsKey("language"))) { // TODO 9.11.06 Bost: a class with information about available languages is needed. // the indexOf(".") is just a workaround because there from ConfigLanguage.html commes "de.lng" and // from ConfigBasic.html comes just "de" in the "language" parameter localeSelection = args.get("language", localeSelection); if (localeSelection.indexOf(".") != -1) localeSelection = localeSelection.substring(0, localeSelection.indexOf(".")); } File targetFile = getLocalizedFile(path, localeSelection); String targetExt = conProp.getProperty("EXT",""); targetClass = rewriteClassFile(new File(htDefaultPath, path)); if (path.endsWith("/")) { String testpath; // attach default file name for (int i = 0; i < defaultFiles.length; i++) { testpath = path + defaultFiles[i]; targetFile = getOverlayedFile(testpath); targetClass=getOverlayedClass(testpath); if (targetFile.exists()) { path = testpath; break; } } //no defaultfile, send a dirlisting if(targetFile == null || !targetFile.exists()){ String dirlistFormat = (args==null)?"html":args.get("format","html"); targetExt = dirlistFormat; // this is needed to set the mime type correctly targetFile = getOverlayedFile("/htdocsdefault/dir." + dirlistFormat); targetClass=getOverlayedClass("/htdocsdefault/dir." + dirlistFormat); if(! (( targetFile != null && targetFile.exists()) && ( targetClass != null && targetClass.exists())) ){ httpd.sendRespondError(this.connectionProperties,out,3,500,"dir." + dirlistFormat + " or dir.class not found.",null,null); } } }else{ //XXX: you cannot share a .png/.gif file with a name like a class in htroot. if ( !(targetFile.exists()) && !((path.endsWith("png")||path.endsWith("gif")||path.endsWith(".stream"))&&targetClass!=null ) ){ targetFile = new File(htDocsPath, path); targetClass = rewriteClassFile(new File(htDocsPath, path)); } } //File targetClass = rewriteClassFile(targetFile); //We need tp here servletProperties tp = new servletProperties(); Date targetDate; boolean nocache = false; if ((targetClass != null) && (path.endsWith("png"))) { // call an image-servlet to produce an on-the-fly - generated image Object img = null; try { requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); // in case that there are no args given, args = null or empty hashmap img = invokeServlet(targetClass, requestHeader, args); } catch (InvocationTargetException e) { this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" + e.getMessage() + " target exception at " + targetClass + ": " + e.getTargetException().toString() + ":" + e.getTargetException().getMessage() + "; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e); targetClass = null; } if (img == null) { // error with image generation; send file-not-found httpd.sendRespondError(this.connectionProperties,out,3,404,"File not Found",null,null); } else { if (img instanceof ymageMatrix) { ymageMatrix yp = (ymageMatrix) img; // send an image to client targetDate = new Date(System.currentTimeMillis()); nocache = true; String mimeType = mimeTable.getProperty(targetExt, "text/html"); // generate an byte array from the generated image serverByteBuffer baos = new serverByteBuffer(); // ymagePNGEncoderJDE jde = new // ymagePNGEncoderJDE((ymageMatrixPainter) yp, // ymagePNGEncoderJDE.FILTER_NONE, 0); // byte[] result = jde.pngEncode(); ImageIO.write(yp.getImage(), targetExt, baos); byte[] result = baos.toByteArray(); baos.close(); baos = null; // write the array to the client httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, null, null, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { //Thread.sleep(200); // see below serverFileUtils.write(result, out); } } if (img instanceof Image) { Image i = (Image) img; // send an image to client targetDate = new Date(System.currentTimeMillis()); nocache = true; String mimeType = mimeTable.getProperty(targetExt, "text/html"); // generate an byte array from the generated image int width = i.getWidth(null); if (width < 0) width = 96; // bad hack int height = i.getHeight(null); if (height < 0) height = 96; // bad hack BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); bi.createGraphics().drawImage(i, 0, 0, width, height, null); serverByteBuffer baos = new serverByteBuffer(); ImageIO.write(bi, targetExt, baos); byte[] result = baos.toByteArray(); baos.close(); baos = null; // write the array to the client httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, null, null, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { //Thread.sleep(200); // see below serverFileUtils.write(result, out); } } } } else if ((targetClass != null) && (path.endsWith(".stream"))) { // call rewrite-class requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); requestHeader.put(httpHeader.CONNECTION_PROP_INPUTSTREAM, body); requestHeader.put(httpHeader.CONNECTION_PROP_OUTPUTSTREAM, out); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null); // in case that there are no args given, args = null or empty hashmap /* servletProperties tp = (servlerObjects) */ invokeServlet(targetClass, requestHeader, args); this.forceConnectionClose(); return; } else if ((targetFile.exists()) && (targetFile.canRead())) { // we have found a file that can be written to the client // if this file uses templates, then we use the template // re-write - method to create an result String mimeType = mimeTable.getProperty(targetExt,"text/html"); boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT","")); if (path.endsWith("html") || path.endsWith("xml") || path.endsWith("rss") || path.endsWith("csv") || path.endsWith("pac") || path.endsWith("src") || path.endsWith("vcf") || path.endsWith("/") || path.equals("/robots.txt")) { /*targetFile = getLocalizedFile(path); if (!(targetFile.exists())) { // try to find that file in the htDocsPath File trialFile = new File(htDocsPath, path); if (trialFile.exists()) targetFile = trialFile; }*/ // call rewrite-class if (targetClass == null) { targetDate = new Date(targetFile.lastModified()); } else { // CGI-class: call the class to create a property for rewriting try { requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); // in case that there are no args given, args = null or empty hashmap Object tmp = invokeServlet(targetClass, requestHeader, args); if(tmp instanceof servletProperties){ tp=(servletProperties)tmp; }else{ tp=new servletProperties((serverObjects)tmp); } // if no args given , then tp will be an empty Hashtable object (not null) if (tp == null) tp = new servletProperties(); // check if the servlets requests authentification if (tp.containsKey(servletProperties.ACTION_AUTHENTICATE)) { // handle brute-force protection if (authorization != null) { String clientIP = conProp.getProperty("CLIENTIP", "unknown-host"); serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'"); Integer attempts = (Integer) serverCore.bfHost.get(clientIP); if (attempts == null) serverCore.bfHost.put(clientIP, new Integer(1)); else serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1)); } // send authentication request to browser httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get(servletProperties.ACTION_AUTHENTICATE, "") + "\""); httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); return; } else if (tp.containsKey(servletProperties.ACTION_LOCATION)) { String location = tp.get(servletProperties.ACTION_LOCATION, ""); if (location.length() == 0) location = path; httpHeader headers = getDefaultHeaders(path); headers.setCookieVector(tp.getOutgoingHeader().getCookieVector()); //put the cookies into the new header TODO: can we put all headerlines, without trouble? headers.put(httpHeader.LOCATION,location); httpd.sendRespondHeader(conProp,out,httpVersion,302,headers); return; } // add the application version, the uptime and the client name to every rewrite table tp.put(servletProperties.PEER_STAT_VERSION, switchboard.getConfig("version", "")); tp.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - Long.parseLong(switchboard.getConfig("startupTime","0"))) / 1000) / 60); // uptime in minutes tp.put(servletProperties.PEER_STAT_CLIENTNAME, switchboard.getConfig("peerName", "anomic")); //System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug } catch (InvocationTargetException e) { if (e.getCause() instanceof InterruptedException) { throw new InterruptedException(e.getCause().getMessage()); } this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" + e.getMessage() + " target exception at " + targetClass + ": " + e.getTargetException().toString() + ":" + e.getTargetException().getMessage(),e); targetClass = null; throw e; } targetDate = new Date(System.currentTimeMillis()); nocache = true; } // read templates tp.putAll(templates); // rewrite the file InputStream fis = null; // read the file/template byte[] templateContent = null; if (useTemplateCache) { long fileSize = targetFile.length(); if (fileSize <= 512 * 1024) { // read from cache SoftReference ref = (SoftReference) templateCache.get(targetFile); if (ref != null) { templateContent = (byte[]) ref.get(); if (templateContent == null) templateCache.remove(targetFile); } if (templateContent == null) { // loading the content of the template file into // a byte array templateContent = serverFileUtils.read(targetFile); // storing the content into the cache ref = new SoftReference(templateContent); templateCache.put(targetFile, ref); if (this.theLogger.isLoggable(Level.FINEST)) this.theLogger.logFinest("Cache MISS for file " + targetFile); } else { if (this.theLogger.isLoggable(Level.FINEST)) this.theLogger.logFinest("Cache HIT for file " + targetFile); } // creating an inputstream needed by the template // rewrite function fis = new ByteArrayInputStream(templateContent); templateContent = null; } else { // read from file directly fis = new BufferedInputStream(new FileInputStream(targetFile)); } } else { fis = new BufferedInputStream(new FileInputStream(targetFile)); } // write the array to the client // we can do that either in standard mode (whole thing completely) or in chunked mode // since yacy clients do not understand chunked mode, we use this only for communication with the administrator boolean yacyClient = requestHeader.userAgent().startsWith("yacy"); boolean chunked = !method.equals(httpHeader.METHOD_HEAD) && !yacyClient && httpVersion.equals(httpHeader.HTTP_VERSION_1_1); if (chunked) { // send page in chunks and parse SSIs serverByteBuffer o = new serverByteBuffer(); // apply templates httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, -1, targetDate, null, tp.getOutgoingHeader(), null, "chunked", nocache); // send the content in chunked parts, see RFC 2616 section 3.6.1 httpChunkedOutputStream chos = new httpChunkedOutputStream(out); httpSSI.writeSSI(targetFile, o, chos); //chos.write(result); chos.finish(); } else { // send page as whole thing, SSIs are not possible String contentEncoding = (zipContent) ? "gzip" : null; // apply templates serverByteBuffer o = new serverByteBuffer(); if (zipContent) { GZIPOutputStream zippedOut = new GZIPOutputStream(o); httpTemplate.writeTemplate(fis, zippedOut, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); zippedOut.finish(); zippedOut.flush(); zippedOut.close(); zippedOut = null; } else { httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); } if (method.equals(httpHeader.METHOD_HEAD)) { httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, o.length(), targetDate, null, tp.getOutgoingHeader(), contentEncoding, null, nocache); } else { byte[] result = o.toByteArray(); // this interrupts streaming (bad idea!) httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, tp.getOutgoingHeader(), contentEncoding, null, nocache); serverFileUtils.write(result, out); } } } else { // no html int statusCode = 200; int rangeStartOffset = 0; httpHeader header = new httpHeader(); // adding the accept ranges header header.put(httpHeader.ACCEPT_RANGES, "bytes"); // reading the files md5 hash if availabe and use it as ETAG of the resource String targetMD5 = null; File targetMd5File = new File(targetFile + ".md5"); try { if (targetMd5File.exists()) { //String description = null; targetMD5 = new String(serverFileUtils.read(targetMd5File)); pos = targetMD5.indexOf('\n'); if (pos >= 0) { //description = targetMD5.substring(pos + 1); targetMD5 = targetMD5.substring(0, pos); } // using the checksum as ETAG header header.put(httpHeader.ETAG, targetMD5); } } catch (IOException e) { e.printStackTrace(); } if (requestHeader.containsKey(httpHeader.RANGE)) { Object ifRange = requestHeader.ifRange(); if ((ifRange == null)|| (ifRange instanceof Date && targetFile.lastModified() == ((Date)ifRange).getTime()) || (ifRange instanceof String && ifRange.equals(targetMD5))) { String rangeHeaderVal = ((String) requestHeader.get(httpHeader.RANGE)).trim(); if (rangeHeaderVal.startsWith("bytes=")) { String rangesVal = rangeHeaderVal.substring("bytes=".length()); String[] ranges = rangesVal.split(","); if ((ranges.length == 1)&&(ranges[0].endsWith("-"))) { rangeStartOffset = Integer.valueOf(ranges[0].substring(0,ranges[0].length()-1)).intValue(); statusCode = 206; if (header == null) header = new httpHeader(); header.put(httpHeader.CONTENT_RANGE, "bytes " + rangeStartOffset + "-" + (targetFile.length()-1) + "/" + targetFile.length()); } } } } // write the file to the client targetDate = new Date(targetFile.lastModified()); long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset; String contentEncoding = (zipContent)?"gzip":null; String transferEncoding = (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1))?null:(zipContent)?"chunked":null; if (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1) && zipContent) forceConnectionClose(); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, statusCode, null, mimeType, contentLength, targetDate, null, header, contentEncoding, transferEncoding, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { httpChunkedOutputStream chunkedOut = null; GZIPOutputStream zipped = null; OutputStream newOut = out; if (transferEncoding != null) { chunkedOut = new httpChunkedOutputStream(newOut); newOut = chunkedOut; } if (contentEncoding != null) { zipped = new GZIPOutputStream(newOut); newOut = zipped; } serverFileUtils.copyRange(targetFile,newOut,rangeStartOffset); if (zipped != null) { zipped.flush(); zipped.finish(); } if (chunkedOut != null) { chunkedOut.finish(); } } // check mime type again using the result array: these are 'magics' // if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html"); // else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html"); // else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html"); //System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println(); } } else { httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null); return; } } catch (Exception e) { try { // doing some errorhandling ... int httpStatusCode = 400; String httpStatusText = null; StringBuffer errorMessage = new StringBuffer(); Exception errorExc = null; String errorMsg = e.getMessage(); if ( (e instanceof InterruptedException) || ((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted())) ) { errorMessage.append("Interruption detected while processing query."); httpStatusCode = 503; } else { if ((errorMsg != null) && ( errorMsg.startsWith("Broken pipe") || errorMsg.startsWith("Connection reset") || errorMsg.startsWith("Software caused connection abort") )) { // client closed the connection, so we just end silently errorMessage.append("Client unexpectedly closed connection while processing query."); } else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) { errorMessage.append("Connection timed out."); } else { errorMessage.append("Unexpected error while processing query."); httpStatusCode = 500; errorExc = e; } } errorMessage.append("\nSession: ").append(Thread.currentThread().getName()) .append("\nQuery: ").append(path) .append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown")) .append("\nReason: ").append(e.toString()); if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) { // sending back an error message to the client // if we have not already send an http header httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, new String(errorMessage),errorExc); } else { // otherwise we close the connection this.forceConnectionClose(); } // if it is an unexpected error we log it if (httpStatusCode == 500) { this.theLogger.logWarning(new String(errorMessage),e); } } catch (Exception ee) { this.forceConnectionClose(); } } finally { try {out.flush();}catch (Exception e) {} if (((String)requestHeader.get(httpHeader.CONNECTION, "close")).indexOf("keep-alive") == -1) { // wait a little time until everything closes so that clients can read from the streams/sockets try {Thread.sleep(200);} catch (InterruptedException e) {} } } }
public void doResponse(Properties conProp, httpHeader requestHeader, OutputStream out, InputStream body) { this.connectionProperties = conProp; String path = null; try { // getting some connection properties String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD); path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH); String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given String httpVersion= conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER); // check hack attacks in path if (path.indexOf("..") >= 0) { httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null); return; } // url decoding of path try { path = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { // This should never occur assert(false) : "UnsupportedEncodingException: " + e.getMessage(); } // check permission/granted access String authorization = (String) requestHeader.get(httpHeader.AUTHORIZATION); String adminAccountBase64MD5 = switchboard.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, ""); int pos = path.lastIndexOf("."); if ((path.substring(0,(pos==-1)?path.length():pos)).endsWith("_p") && (adminAccountBase64MD5.length() != 0)) { //authentication required //userDB if(sb.userDB.hasAdminRight(authorization, conProp.getProperty("CLIENTIP"), requestHeader.getHeaderCookies())){ //Authentication successful. remove brute-force flag serverCore.bfHost.remove(conProp.getProperty("CLIENTIP")); //static }else if(authorization != null && httpd.staticAdminAuthenticated(authorization.trim().substring(6), switchboard)==4){ //Authentication successful. remove brute-force flag serverCore.bfHost.remove(conProp.getProperty("CLIENTIP")); //no auth }else if (authorization == null) { // no authorization given in response. Ask for that httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\""); //httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); servletProperties tp=new servletProperties(); tp.put("returnto", path); //TODO: separate errorpage Wrong Login / No Login httpd.sendRespondError(conProp, out, 5, 401, "Wrong Authentication", "", new File("proxymsg/authfail.inc"), tp, null, headers); return; } else { // a wrong authentication was given or the userDB user does not have admin access. Ask again String clientIP = conProp.getProperty("CLIENTIP", "unknown-host"); serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'"); Integer attempts = (Integer) serverCore.bfHost.get(clientIP); if (attempts == null) serverCore.bfHost.put(clientIP, new Integer(1)); else serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1)); httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\""); httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); return; } } // parse arguments serverObjects args = new serverObjects(); int argc; if (argsString == null) { // no args here, maybe a POST with multipart extension int length = 0; //System.out.println("HEADER: " + requestHeader.toString()); // DEBUG if (method.equals(httpHeader.METHOD_POST)) { GZIPInputStream gzipBody = null; if (requestHeader.containsKey(httpHeader.CONTENT_LENGTH)) { length = Integer.parseInt((String) requestHeader.get(httpHeader.CONTENT_LENGTH)); } else if (requestHeader.gzip()) { length = -1; gzipBody = new GZIPInputStream(body); } // } else { // httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null); // return; // } // if its a POST, it can be either multipart or as args in the body if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) && (((String) requestHeader.get(httpHeader.CONTENT_TYPE)).toLowerCase().startsWith("multipart"))) { // parse multipart HashMap files = httpd.parseMultipart(requestHeader, args, (gzipBody!=null)?gzipBody:body, length); // integrate these files into the args if (files != null) { Iterator fit = files.entrySet().iterator(); Map.Entry entry; while (fit.hasNext()) { entry = (Map.Entry) fit.next(); args.put(((String) entry.getKey()) + "$file", entry.getValue()); } } argc = Integer.parseInt((String) requestHeader.get("ARGC")); } else { // parse args in body argc = httpd.parseArgs(args, (gzipBody!=null)?gzipBody:body, length); } } else { // no args argsString = null; args = null; argc = 0; } } else { // simple args in URL (stuff after the "?") argc = httpd.parseArgs(args, argsString); } // check for cross site scripting - attacks in request arguments if (argc > 0) { // check all values for occurrences of script values Enumeration e = args.elements(); // enumeration of values Object val; while (e.hasMoreElements()) { val = e.nextElement(); if ((val != null) && (val instanceof String) && (((String) val).indexOf("<script") >= 0)) { // deny request httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null); return; } } } // we are finished with parsing // the result of value hand-over is in args and argc if (path.length() == 0) { httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null); out.flush(); return; } File targetClass=null; // locate the file if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash // a different language can be desired (by i.e. ConfigBasic.html) than the one stored in the locale.language String localeSelection = switchboard.getConfig("locale.language","default"); if (args != null && (args.containsKey("language"))) { // TODO 9.11.06 Bost: a class with information about available languages is needed. // the indexOf(".") is just a workaround because there from ConfigLanguage.html commes "de.lng" and // from ConfigBasic.html comes just "de" in the "language" parameter localeSelection = args.get("language", localeSelection); if (localeSelection.indexOf(".") != -1) localeSelection = localeSelection.substring(0, localeSelection.indexOf(".")); } File targetFile = getLocalizedFile(path, localeSelection); String targetExt = conProp.getProperty("EXT",""); targetClass = rewriteClassFile(new File(htDefaultPath, path)); if (path.endsWith("/")) { String testpath; // attach default file name for (int i = 0; i < defaultFiles.length; i++) { testpath = path + defaultFiles[i]; targetFile = getOverlayedFile(testpath); targetClass=getOverlayedClass(testpath); if (targetFile.exists()) { path = testpath; break; } } //no defaultfile, send a dirlisting if(targetFile == null || !targetFile.exists()){ String dirlistFormat = (args==null)?"html":args.get("format","html"); targetExt = dirlistFormat; // this is needed to set the mime type correctly targetFile = getOverlayedFile("/htdocsdefault/dir." + dirlistFormat); targetClass=getOverlayedClass("/htdocsdefault/dir." + dirlistFormat); if(! (( targetFile != null && targetFile.exists()) && ( targetClass != null && targetClass.exists())) ){ httpd.sendRespondError(this.connectionProperties,out,3,500,"dir." + dirlistFormat + " or dir.class not found.",null,null); } } }else{ //XXX: you cannot share a .png/.gif file with a name like a class in htroot. if ( !(targetFile.exists()) && !((path.endsWith("png")||path.endsWith("gif")||path.endsWith(".stream"))&&targetClass!=null ) ){ targetFile = new File(htDocsPath, path); targetClass = rewriteClassFile(new File(htDocsPath, path)); } } //File targetClass = rewriteClassFile(targetFile); //We need tp here servletProperties tp = new servletProperties(); Date targetDate; boolean nocache = false; if ((targetClass != null) && (path.endsWith("png"))) { // call an image-servlet to produce an on-the-fly - generated image Object img = null; try { requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); // in case that there are no args given, args = null or empty hashmap img = invokeServlet(targetClass, requestHeader, args); } catch (InvocationTargetException e) { this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" + e.getMessage() + " target exception at " + targetClass + ": " + e.getTargetException().toString() + ":" + e.getTargetException().getMessage() + "; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e); targetClass = null; } if (img == null) { // error with image generation; send file-not-found httpd.sendRespondError(this.connectionProperties,out,3,404,"File not Found",null,null); } else { if (img instanceof ymageMatrix) { ymageMatrix yp = (ymageMatrix) img; // send an image to client targetDate = new Date(System.currentTimeMillis()); nocache = true; String mimeType = mimeTable.getProperty(targetExt, "text/html"); // generate an byte array from the generated image serverByteBuffer baos = new serverByteBuffer(); // ymagePNGEncoderJDE jde = new // ymagePNGEncoderJDE((ymageMatrixPainter) yp, // ymagePNGEncoderJDE.FILTER_NONE, 0); // byte[] result = jde.pngEncode(); ImageIO.write(yp.getImage(), targetExt, baos); byte[] result = baos.toByteArray(); baos.close(); baos = null; // write the array to the client httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, null, null, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { //Thread.sleep(200); // see below serverFileUtils.write(result, out); } } if (img instanceof Image) { Image i = (Image) img; // send an image to client targetDate = new Date(System.currentTimeMillis()); nocache = true; String mimeType = mimeTable.getProperty(targetExt, "text/html"); // generate an byte array from the generated image int width = i.getWidth(null); if (width < 0) width = 96; // bad hack int height = i.getHeight(null); if (height < 0) height = 96; // bad hack BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); bi.createGraphics().drawImage(i, 0, 0, width, height, null); serverByteBuffer baos = new serverByteBuffer(); ImageIO.write(bi, targetExt, baos); byte[] result = baos.toByteArray(); baos.close(); baos = null; // write the array to the client httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, null, null, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { //Thread.sleep(200); // see below serverFileUtils.write(result, out); } } } } else if ((targetClass != null) && (path.endsWith(".stream"))) { // call rewrite-class requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); requestHeader.put(httpHeader.CONNECTION_PROP_INPUTSTREAM, body); requestHeader.put(httpHeader.CONNECTION_PROP_OUTPUTSTREAM, out); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null); // in case that there are no args given, args = null or empty hashmap /* servletProperties tp = (servlerObjects) */ invokeServlet(targetClass, requestHeader, args); this.forceConnectionClose(); return; } else if ((targetFile.exists()) && (targetFile.canRead())) { // we have found a file that can be written to the client // if this file uses templates, then we use the template // re-write - method to create an result String mimeType = mimeTable.getProperty(targetExt,"text/html"); boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT","")); if (path.endsWith("html") || path.endsWith("xml") || path.endsWith("rss") || path.endsWith("csv") || path.endsWith("pac") || path.endsWith("src") || path.endsWith("vcf") || path.endsWith("/") || path.equals("/robots.txt")) { /*targetFile = getLocalizedFile(path); if (!(targetFile.exists())) { // try to find that file in the htDocsPath File trialFile = new File(htDocsPath, path); if (trialFile.exists()) targetFile = trialFile; }*/ // call rewrite-class if (targetClass == null) { targetDate = new Date(targetFile.lastModified()); } else { // CGI-class: call the class to create a property for rewriting try { requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); // in case that there are no args given, args = null or empty hashmap Object tmp = invokeServlet(targetClass, requestHeader, args); if (tp == null) { // if no args given, then tp will be an empty Hashtable object (not null) tp = new servletProperties(); } else if (tmp instanceof servletProperties) { tp = (servletProperties) tmp; } else { tp = new servletProperties((serverObjects) tmp); } // check if the servlets requests authentification if (tp.containsKey(servletProperties.ACTION_AUTHENTICATE)) { // handle brute-force protection if (authorization != null) { String clientIP = conProp.getProperty("CLIENTIP", "unknown-host"); serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'"); Integer attempts = (Integer) serverCore.bfHost.get(clientIP); if (attempts == null) serverCore.bfHost.put(clientIP, new Integer(1)); else serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1)); } // send authentication request to browser httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get(servletProperties.ACTION_AUTHENTICATE, "") + "\""); httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); return; } else if (tp.containsKey(servletProperties.ACTION_LOCATION)) { String location = tp.get(servletProperties.ACTION_LOCATION, ""); if (location.length() == 0) location = path; httpHeader headers = getDefaultHeaders(path); headers.setCookieVector(tp.getOutgoingHeader().getCookieVector()); //put the cookies into the new header TODO: can we put all headerlines, without trouble? headers.put(httpHeader.LOCATION,location); httpd.sendRespondHeader(conProp,out,httpVersion,302,headers); return; } // add the application version, the uptime and the client name to every rewrite table tp.put(servletProperties.PEER_STAT_VERSION, switchboard.getConfig("version", "")); tp.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - Long.parseLong(switchboard.getConfig("startupTime","0"))) / 1000) / 60); // uptime in minutes tp.put(servletProperties.PEER_STAT_CLIENTNAME, switchboard.getConfig("peerName", "anomic")); //System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug } catch (InvocationTargetException e) { if (e.getCause() instanceof InterruptedException) { throw new InterruptedException(e.getCause().getMessage()); } this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" + e.getMessage() + " target exception at " + targetClass + ": " + e.getTargetException().toString() + ":" + e.getTargetException().getMessage(),e); targetClass = null; throw e; } targetDate = new Date(System.currentTimeMillis()); nocache = true; } // read templates tp.putAll(templates); // rewrite the file InputStream fis = null; // read the file/template byte[] templateContent = null; if (useTemplateCache) { long fileSize = targetFile.length(); if (fileSize <= 512 * 1024) { // read from cache SoftReference ref = (SoftReference) templateCache.get(targetFile); if (ref != null) { templateContent = (byte[]) ref.get(); if (templateContent == null) templateCache.remove(targetFile); } if (templateContent == null) { // loading the content of the template file into // a byte array templateContent = serverFileUtils.read(targetFile); // storing the content into the cache ref = new SoftReference(templateContent); templateCache.put(targetFile, ref); if (this.theLogger.isLoggable(Level.FINEST)) this.theLogger.logFinest("Cache MISS for file " + targetFile); } else { if (this.theLogger.isLoggable(Level.FINEST)) this.theLogger.logFinest("Cache HIT for file " + targetFile); } // creating an inputstream needed by the template // rewrite function fis = new ByteArrayInputStream(templateContent); templateContent = null; } else { // read from file directly fis = new BufferedInputStream(new FileInputStream(targetFile)); } } else { fis = new BufferedInputStream(new FileInputStream(targetFile)); } // write the array to the client // we can do that either in standard mode (whole thing completely) or in chunked mode // since yacy clients do not understand chunked mode, we use this only for communication with the administrator boolean yacyClient = requestHeader.userAgent().startsWith("yacy"); boolean chunked = !method.equals(httpHeader.METHOD_HEAD) && !yacyClient && httpVersion.equals(httpHeader.HTTP_VERSION_1_1); if (chunked) { // send page in chunks and parse SSIs serverByteBuffer o = new serverByteBuffer(); // apply templates httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, -1, targetDate, null, tp.getOutgoingHeader(), null, "chunked", nocache); // send the content in chunked parts, see RFC 2616 section 3.6.1 httpChunkedOutputStream chos = new httpChunkedOutputStream(out); httpSSI.writeSSI(targetFile, o, chos); //chos.write(result); chos.finish(); } else { // send page as whole thing, SSIs are not possible String contentEncoding = (zipContent) ? "gzip" : null; // apply templates serverByteBuffer o = new serverByteBuffer(); if (zipContent) { GZIPOutputStream zippedOut = new GZIPOutputStream(o); httpTemplate.writeTemplate(fis, zippedOut, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); zippedOut.finish(); zippedOut.flush(); zippedOut.close(); zippedOut = null; } else { httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); } if (method.equals(httpHeader.METHOD_HEAD)) { httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, o.length(), targetDate, null, tp.getOutgoingHeader(), contentEncoding, null, nocache); } else { byte[] result = o.toByteArray(); // this interrupts streaming (bad idea!) httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, tp.getOutgoingHeader(), contentEncoding, null, nocache); serverFileUtils.write(result, out); } } } else { // no html int statusCode = 200; int rangeStartOffset = 0; httpHeader header = new httpHeader(); // adding the accept ranges header header.put(httpHeader.ACCEPT_RANGES, "bytes"); // reading the files md5 hash if availabe and use it as ETAG of the resource String targetMD5 = null; File targetMd5File = new File(targetFile + ".md5"); try { if (targetMd5File.exists()) { //String description = null; targetMD5 = new String(serverFileUtils.read(targetMd5File)); pos = targetMD5.indexOf('\n'); if (pos >= 0) { //description = targetMD5.substring(pos + 1); targetMD5 = targetMD5.substring(0, pos); } // using the checksum as ETAG header header.put(httpHeader.ETAG, targetMD5); } } catch (IOException e) { e.printStackTrace(); } if (requestHeader.containsKey(httpHeader.RANGE)) { Object ifRange = requestHeader.ifRange(); if ((ifRange == null)|| (ifRange instanceof Date && targetFile.lastModified() == ((Date)ifRange).getTime()) || (ifRange instanceof String && ifRange.equals(targetMD5))) { String rangeHeaderVal = ((String) requestHeader.get(httpHeader.RANGE)).trim(); if (rangeHeaderVal.startsWith("bytes=")) { String rangesVal = rangeHeaderVal.substring("bytes=".length()); String[] ranges = rangesVal.split(","); if ((ranges.length == 1)&&(ranges[0].endsWith("-"))) { rangeStartOffset = Integer.valueOf(ranges[0].substring(0,ranges[0].length()-1)).intValue(); statusCode = 206; if (header == null) header = new httpHeader(); header.put(httpHeader.CONTENT_RANGE, "bytes " + rangeStartOffset + "-" + (targetFile.length()-1) + "/" + targetFile.length()); } } } } // write the file to the client targetDate = new Date(targetFile.lastModified()); long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset; String contentEncoding = (zipContent)?"gzip":null; String transferEncoding = (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1))?null:(zipContent)?"chunked":null; if (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1) && zipContent) forceConnectionClose(); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, statusCode, null, mimeType, contentLength, targetDate, null, header, contentEncoding, transferEncoding, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { httpChunkedOutputStream chunkedOut = null; GZIPOutputStream zipped = null; OutputStream newOut = out; if (transferEncoding != null) { chunkedOut = new httpChunkedOutputStream(newOut); newOut = chunkedOut; } if (contentEncoding != null) { zipped = new GZIPOutputStream(newOut); newOut = zipped; } serverFileUtils.copyRange(targetFile,newOut,rangeStartOffset); if (zipped != null) { zipped.flush(); zipped.finish(); } if (chunkedOut != null) { chunkedOut.finish(); } } // check mime type again using the result array: these are 'magics' // if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html"); // else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html"); // else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html"); //System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println(); } } else { httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null); return; } } catch (Exception e) { try { // doing some errorhandling ... int httpStatusCode = 400; String httpStatusText = null; StringBuffer errorMessage = new StringBuffer(); Exception errorExc = null; String errorMsg = e.getMessage(); if ( (e instanceof InterruptedException) || ((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted())) ) { errorMessage.append("Interruption detected while processing query."); httpStatusCode = 503; } else { if ((errorMsg != null) && ( errorMsg.startsWith("Broken pipe") || errorMsg.startsWith("Connection reset") || errorMsg.startsWith("Software caused connection abort") )) { // client closed the connection, so we just end silently errorMessage.append("Client unexpectedly closed connection while processing query."); } else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) { errorMessage.append("Connection timed out."); } else { errorMessage.append("Unexpected error while processing query."); httpStatusCode = 500; errorExc = e; } } errorMessage.append("\nSession: ").append(Thread.currentThread().getName()) .append("\nQuery: ").append(path) .append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown")) .append("\nReason: ").append(e.toString()); if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) { // sending back an error message to the client // if we have not already send an http header httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, new String(errorMessage),errorExc); } else { // otherwise we close the connection this.forceConnectionClose(); } // if it is an unexpected error we log it if (httpStatusCode == 500) { this.theLogger.logWarning(new String(errorMessage),e); } } catch (Exception ee) { this.forceConnectionClose(); } } finally { try {out.flush();}catch (Exception e) {} if (((String)requestHeader.get(httpHeader.CONNECTION, "close")).indexOf("keep-alive") == -1) { // wait a little time until everything closes so that clients can read from the streams/sockets try {Thread.sleep(200);} catch (InterruptedException e) {} } } }
diff --git a/src/test/java/org/neo4j/neode/ConsecutiveIdBasedIterableNodesTest.java b/src/test/java/org/neo4j/neode/ConsecutiveIdBasedIterableNodesTest.java index a0d2526..b133493 100644 --- a/src/test/java/org/neo4j/neode/ConsecutiveIdBasedIterableNodesTest.java +++ b/src/test/java/org/neo4j/neode/ConsecutiveIdBasedIterableNodesTest.java @@ -1,82 +1,82 @@ package org.neo4j.neode; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import java.util.Iterator; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.neode.test.Db; public class ConsecutiveIdBasedIterableNodesTest { @Test public void shouldReturnEmptyIteratorWhenThereAreNoIds() throws Exception { // given ConsecutiveIdBasedIterableNodes nodes = new ConsecutiveIdBasedIterableNodes( Db.impermanentDb() ); // then assertFalse( nodes.iterator().hasNext() ); } @Test public void shouldReturnNodesInIdOrder() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); ConsecutiveIdBasedIterableNodes nodes = new ConsecutiveIdBasedIterableNodes( db ); // when Transaction tx = db.beginTx(); nodes.add( db.createNode() ); nodes.add( db.createNode() ); nodes.add( db.createNode() ); tx.success(); tx.finish(); Iterator<Node> iterator = nodes.iterator(); // then assertEquals( 1L, iterator.next().getId() ); assertEquals( 2L, iterator.next().getId() ); assertEquals( 3L, iterator.next().getId() ); assertFalse( iterator.hasNext() ); } @Test - public void shouldThrowExcpetionIfNextNodeIdIsNotConsecutiveWithCurretnEndNodeId() throws Exception + public void shouldThrowExceptionIfNextNodeIdIsNotConsecutiveWithCurrentEndNodeId() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); ConsecutiveIdBasedIterableNodes nodes = new ConsecutiveIdBasedIterableNodes( db ); Transaction tx = db.beginTx(); nodes.add( db.createNode() ); nodes.add( db.createNode() ); // when db.createNode(); try { nodes.add( db.createNode() ); fail( "Expected IllegalArgumentException" ); } catch ( IllegalArgumentException e ) { // then assertEquals( "Non-consecutive node Id. Expected: 3, Received: 4.", e.getMessage() ); } finally { tx.success(); tx.finish(); } } }
true
true
public void shouldThrowExcpetionIfNextNodeIdIsNotConsecutiveWithCurretnEndNodeId() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); ConsecutiveIdBasedIterableNodes nodes = new ConsecutiveIdBasedIterableNodes( db ); Transaction tx = db.beginTx(); nodes.add( db.createNode() ); nodes.add( db.createNode() ); // when db.createNode(); try { nodes.add( db.createNode() ); fail( "Expected IllegalArgumentException" ); } catch ( IllegalArgumentException e ) { // then assertEquals( "Non-consecutive node Id. Expected: 3, Received: 4.", e.getMessage() ); } finally { tx.success(); tx.finish(); } }
public void shouldThrowExceptionIfNextNodeIdIsNotConsecutiveWithCurrentEndNodeId() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); ConsecutiveIdBasedIterableNodes nodes = new ConsecutiveIdBasedIterableNodes( db ); Transaction tx = db.beginTx(); nodes.add( db.createNode() ); nodes.add( db.createNode() ); // when db.createNode(); try { nodes.add( db.createNode() ); fail( "Expected IllegalArgumentException" ); } catch ( IllegalArgumentException e ) { // then assertEquals( "Non-consecutive node Id. Expected: 3, Received: 4.", e.getMessage() ); } finally { tx.success(); tx.finish(); } }
diff --git a/src/main/java/org/primefaces/extensions/behavior/javascript/JavascriptBehaviorRenderer.java b/src/main/java/org/primefaces/extensions/behavior/javascript/JavascriptBehaviorRenderer.java index 9616f66a..a1de2dbe 100644 --- a/src/main/java/org/primefaces/extensions/behavior/javascript/JavascriptBehaviorRenderer.java +++ b/src/main/java/org/primefaces/extensions/behavior/javascript/JavascriptBehaviorRenderer.java @@ -1,88 +1,88 @@ /* * Copyright 2011 PrimeFaces Extensions. * * 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. * * $Id$ */ package org.primefaces.extensions.behavior.javascript; import javax.faces.component.UIComponent; import javax.faces.component.UIParameter; import javax.faces.component.behavior.ClientBehavior; import javax.faces.component.behavior.ClientBehaviorContext; import javax.faces.context.FacesContext; import javax.faces.render.ClientBehaviorRenderer; import org.primefaces.extensions.util.ComponentUtils; /** * {@link ClientBehaviorRenderer} implementation for the {@link JavascriptBehavior}. * * @author Thomas Andraschko / last modified by $Author$ * @version $Revision$ * @since 0.2 */ public class JavascriptBehaviorRenderer extends ClientBehaviorRenderer { @Override public String getScript(final ClientBehaviorContext behaviorContext, final ClientBehavior behavior) { final JavascriptBehavior javascriptBehavior = (JavascriptBehavior) behavior; if (javascriptBehavior.isDisabled()) { return null; } final FacesContext context = behaviorContext.getFacesContext(); final UIComponent component = behaviorContext.getComponent(); String source = behaviorContext.getSourceId(); if (source == null) { source = component.getClientId(context); } final StringBuilder script = new StringBuilder(); - script.append("PrimeFacesExt.behavior.Javascript({"); + script.append("return PrimeFacesExt.behavior.Javascript({"); script.append("source:'").append(ComponentUtils.escapeComponentId(source)).append("'"); script.append(",event:'").append(behaviorContext.getEventName()).append("'"); script.append(",execute:function(source, event, params, ext){"); script.append(javascriptBehavior.getExecute()).append(";}"); // params boolean paramWritten = false; for (final UIComponent child : component.getChildren()) { if (child instanceof UIParameter) { final UIParameter parameter = (UIParameter) child; if (paramWritten) { script.append(","); } else { paramWritten = true; script.append(",params:{"); } script.append("'"); script.append(parameter.getName()).append("':'").append(parameter.getValue()); script.append("'"); } } if (paramWritten) { script.append("}"); } script.append("}, arguments[1]);"); return script.toString(); } }
true
true
public String getScript(final ClientBehaviorContext behaviorContext, final ClientBehavior behavior) { final JavascriptBehavior javascriptBehavior = (JavascriptBehavior) behavior; if (javascriptBehavior.isDisabled()) { return null; } final FacesContext context = behaviorContext.getFacesContext(); final UIComponent component = behaviorContext.getComponent(); String source = behaviorContext.getSourceId(); if (source == null) { source = component.getClientId(context); } final StringBuilder script = new StringBuilder(); script.append("PrimeFacesExt.behavior.Javascript({"); script.append("source:'").append(ComponentUtils.escapeComponentId(source)).append("'"); script.append(",event:'").append(behaviorContext.getEventName()).append("'"); script.append(",execute:function(source, event, params, ext){"); script.append(javascriptBehavior.getExecute()).append(";}"); // params boolean paramWritten = false; for (final UIComponent child : component.getChildren()) { if (child instanceof UIParameter) { final UIParameter parameter = (UIParameter) child; if (paramWritten) { script.append(","); } else { paramWritten = true; script.append(",params:{"); } script.append("'"); script.append(parameter.getName()).append("':'").append(parameter.getValue()); script.append("'"); } } if (paramWritten) { script.append("}"); } script.append("}, arguments[1]);"); return script.toString(); }
public String getScript(final ClientBehaviorContext behaviorContext, final ClientBehavior behavior) { final JavascriptBehavior javascriptBehavior = (JavascriptBehavior) behavior; if (javascriptBehavior.isDisabled()) { return null; } final FacesContext context = behaviorContext.getFacesContext(); final UIComponent component = behaviorContext.getComponent(); String source = behaviorContext.getSourceId(); if (source == null) { source = component.getClientId(context); } final StringBuilder script = new StringBuilder(); script.append("return PrimeFacesExt.behavior.Javascript({"); script.append("source:'").append(ComponentUtils.escapeComponentId(source)).append("'"); script.append(",event:'").append(behaviorContext.getEventName()).append("'"); script.append(",execute:function(source, event, params, ext){"); script.append(javascriptBehavior.getExecute()).append(";}"); // params boolean paramWritten = false; for (final UIComponent child : component.getChildren()) { if (child instanceof UIParameter) { final UIParameter parameter = (UIParameter) child; if (paramWritten) { script.append(","); } else { paramWritten = true; script.append(",params:{"); } script.append("'"); script.append(parameter.getName()).append("':'").append(parameter.getValue()); script.append("'"); } } if (paramWritten) { script.append("}"); } script.append("}, arguments[1]);"); return script.toString(); }
diff --git a/src/main/java/org/jahia/services/workflow/jbpm/ConnectUsers.java b/src/main/java/org/jahia/services/workflow/jbpm/ConnectUsers.java index 79394c8..35440ed 100644 --- a/src/main/java/org/jahia/services/workflow/jbpm/ConnectUsers.java +++ b/src/main/java/org/jahia/services/workflow/jbpm/ConnectUsers.java @@ -1,83 +1,83 @@ /** * This file is part of Jahia, next-generation open source CMS: * Jahia's next-generation, open source CMS stems from a widely acknowledged vision * of enterprise application convergence - web, search, document, social and portal - * unified by the simplicity of web content management. * * For more information, please visit http://www.jahia.com. * * Copyright (C) 2002-2012 Jahia Solutions Group SA. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * As a special exception to the terms and conditions of version 2.0 of * the GPL (or any later version), you may redistribute this Program in connection * with Free/Libre and Open Source Software ("FLOSS") applications as described * in Jahia's FLOSS exception. You should have received a copy of the text * describing the FLOSS exception, and it is also available here: * http://www.jahia.com/license * * Commercial and Supported Versions of the program (dual licensing): * alternatively, commercial and supported versions of the program may be used * in accordance with the terms and conditions contained in a separate * written agreement between you and Jahia Solutions Group SA. * * If you are unsure which license is appropriate for your use, * please contact the sales department at [email protected]. */ package org.jahia.services.workflow.jbpm; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.jahia.modules.social.SocialService; import org.jahia.services.SpringContextSingleton; import org.jbpm.api.activity.ActivityExecution; import org.jbpm.api.activity.ExternalActivityBehaviour; /** * Action handler for creating a social connection between two users. * * @author Serge Huber */ public class ConnectUsers implements ExternalActivityBehaviour { private static final long serialVersionUID = 483037196668735262L; public void execute(ActivityExecution execution) throws Exception { String from = (String) execution.getVariable("from"); if (StringUtils.isEmpty(from)) { throw new IllegalArgumentException("Expected non-empty parameter value for 'from'. Got: " + from); } String to = (String) execution.getVariable("to"); if (StringUtils.isEmpty(to)) { throw new IllegalArgumentException("Expected non-empty parameter value for 'to'. Got: " + to); } String connectionType = (String) execution.getVariable("connectionType"); - SocialService socialService = (SocialService) SpringContextSingleton.getModuleBean("socialService"); + SocialService socialService = (SocialService) SpringContextSingleton.getBeanInModulesContext("socialService"); if (socialService != null) { socialService.createSocialConnection(from, to, connectionType); } execution.takeDefaultTransition(); } public void signal(ActivityExecution execution, String signalName, Map<String, ?> parameters) throws Exception { // do nothing } }
true
true
public void execute(ActivityExecution execution) throws Exception { String from = (String) execution.getVariable("from"); if (StringUtils.isEmpty(from)) { throw new IllegalArgumentException("Expected non-empty parameter value for 'from'. Got: " + from); } String to = (String) execution.getVariable("to"); if (StringUtils.isEmpty(to)) { throw new IllegalArgumentException("Expected non-empty parameter value for 'to'. Got: " + to); } String connectionType = (String) execution.getVariable("connectionType"); SocialService socialService = (SocialService) SpringContextSingleton.getModuleBean("socialService"); if (socialService != null) { socialService.createSocialConnection(from, to, connectionType); } execution.takeDefaultTransition(); }
public void execute(ActivityExecution execution) throws Exception { String from = (String) execution.getVariable("from"); if (StringUtils.isEmpty(from)) { throw new IllegalArgumentException("Expected non-empty parameter value for 'from'. Got: " + from); } String to = (String) execution.getVariable("to"); if (StringUtils.isEmpty(to)) { throw new IllegalArgumentException("Expected non-empty parameter value for 'to'. Got: " + to); } String connectionType = (String) execution.getVariable("connectionType"); SocialService socialService = (SocialService) SpringContextSingleton.getBeanInModulesContext("socialService"); if (socialService != null) { socialService.createSocialConnection(from, to, connectionType); } execution.takeDefaultTransition(); }
diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestController.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestController.java index 38369b29..11412f7e 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestController.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestController.java @@ -1,1374 +1,1378 @@ package org.springframework.data.rest.webmvc; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.Stack; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicReference; import javax.servlet.http.HttpServletRequest; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.convert.ConversionService; import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.Repository; import org.springframework.data.rest.core.Handler; import org.springframework.data.rest.core.Link; import org.springframework.data.rest.core.SimpleLink; import org.springframework.data.rest.core.convert.DelegatingConversionService; import org.springframework.data.rest.core.util.UriUtils; import org.springframework.data.rest.repository.AttributeMetadata; import org.springframework.data.rest.repository.EntityMetadata; import org.springframework.data.rest.repository.RepositoryConstraintViolationException; import org.springframework.data.rest.repository.RepositoryExporter; import org.springframework.data.rest.repository.RepositoryExporterSupport; import org.springframework.data.rest.repository.RepositoryMetadata; import org.springframework.data.rest.repository.RepositoryNotFoundException; import org.springframework.data.rest.repository.RepositoryQueryMethod; import org.springframework.data.rest.repository.annotation.RestResource; import org.springframework.data.rest.repository.context.AfterDeleteEvent; import org.springframework.data.rest.repository.context.AfterLinkSaveEvent; import org.springframework.data.rest.repository.context.AfterSaveEvent; import org.springframework.data.rest.repository.context.BeforeDeleteEvent; import org.springframework.data.rest.repository.context.BeforeLinkSaveEvent; import org.springframework.data.rest.repository.context.BeforeSaveEvent; import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpMethod; import org.springframework.http.HttpOutputMessage; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.util.UriComponentsBuilder; /** * @author Jon Brisbin <[email protected]> */ public class RepositoryRestController extends RepositoryExporterSupport<RepositoryRestController> implements ApplicationContextAware, InitializingBean { public static final String LOCATION = "Location"; public static final String SELF = "self"; public static final String LINKS = "_links"; public static final Charset DEFAULT_CHARSET = Charset.forName( "UTF-8" ); private static final Logger LOG = LoggerFactory.getLogger( RepositoryRestController.class ); private static final HttpHeaders EMPTY_HEADERS = new HttpHeaders(); private static final List<MediaType> ALL_TYPES = Arrays.asList( MediaType.ALL ); private static final MediaType URI_LIST = new MediaType( "text", "uri-list", UriListHttpMessageConverter.DEFAULT_CHARSET ); private ApplicationContext applicationContext; @Autowired(required = false) private DelegatingConversionService conversionService = new DelegatingConversionService( new DefaultFormattingConversionService() ); @Autowired(required = false) private List<HttpMessageConverter> httpMessageConverters = new ArrayList<HttpMessageConverter>(); private SortedSet<MediaType> availableMediaTypes = new TreeSet<MediaType>(); @Autowired(required = false) private RepositoryRestConfiguration config = RepositoryRestConfiguration.DEFAULT; private Map<String, Handler<Object, Object>> resourceHandlers = Collections.emptyMap(); private ObjectMapper objectMapper = new ObjectMapper(); { List<HttpMessageConverter> httpMessageConverters = new ArrayList<HttpMessageConverter>(); httpMessageConverters.add( 0, new StringHttpMessageConverter() ); httpMessageConverters.add( 0, new ByteArrayHttpMessageConverter() ); httpMessageConverters.add( 0, new FormHttpMessageConverter() ); httpMessageConverters.add( 0, new UriListHttpMessageConverter() ); httpMessageConverters.add( 0, JacksonUtil.createJacksonHttpMessageConverter( objectMapper ) ); setHttpMessageConverters( httpMessageConverters ); } @Override public void setApplicationContext( ApplicationContext applicationContext ) throws BeansException { this.applicationContext = applicationContext; } public ConversionService getConversionService() { return conversionService; } public void setConversionService( ConversionService conversionService ) { if ( null != conversionService ) { this.conversionService.addConversionServices( conversionService ); } } public ConversionService conversionService() { return conversionService; } public RepositoryRestController conversionService( ConversionService conversionService ) { setConversionService( conversionService ); return this; } public List<HttpMessageConverter> getHttpMessageConverters() { return httpMessageConverters; } @SuppressWarnings({"unchecked"}) public void setHttpMessageConverters( List<HttpMessageConverter> httpMessageConverters ) { Assert.notNull( httpMessageConverters ); this.httpMessageConverters = httpMessageConverters; this.availableMediaTypes.clear(); for ( HttpMessageConverter conv : httpMessageConverters ) { availableMediaTypes.addAll( conv.getSupportedMediaTypes() ); } for ( HttpMessageConverter conv : config.getCustomConverters() ) { availableMediaTypes.addAll( conv.getSupportedMediaTypes() ); } } public List<HttpMessageConverter> httpMessageConverters() { return httpMessageConverters; } public RepositoryRestController httpMessageConverters( List<HttpMessageConverter> httpMessageConverters ) { setHttpMessageConverters( httpMessageConverters ); return this; } public RepositoryRestConfiguration getRepositoryRestConfig() { return config; } public RepositoryRestController setRepositoryRestConfig( RepositoryRestConfiguration config ) { this.config = config; return this; } public Map<String, Handler<Object, Object>> getResourceHandlers() { return resourceHandlers; } public RepositoryRestController setResourceHandlers( Map<String, Handler<Object, Object>> resourceHandlers ) { this.resourceHandlers = resourceHandlers; return this; } public Map<String, Handler<Object, Object>> resourceHandlers() { return resourceHandlers; } public RepositoryRestController resourceHandlers( Map<String, Handler<Object, Object>> resourceHandlers ) { setResourceHandlers( resourceHandlers ); return this; } @SuppressWarnings({"unchecked"}) @Override public void afterPropertiesSet() throws Exception { for ( ConversionService convsvc : BeanFactoryUtils.beansOfTypeIncludingAncestors( applicationContext, ConversionService.class ) .values() ) { conversionService.addConversionServices( convsvc ); } } @SuppressWarnings({"unchecked"}) @RequestMapping( value = "/", method = RequestMethod.GET ) @ResponseBody public ResponseEntity<?> listRepositories( ServletServerHttpRequest request, UriComponentsBuilder uriBuilder ) throws IOException { URI baseUri = uriBuilder.build().toUri(); Links links = new Links(); for ( RepositoryExporter repoExporter : repositoryExporters ) { for ( String name : (Set<String>) repoExporter.repositoryNames() ) { RepositoryMetadata repoMeta = repoExporter.repositoryMetadataFor( name ); String rel = repoMeta.rel(); URI path = buildUri( baseUri, name ); links.add( new SimpleLink( rel, path ) ); } } return negotiateResponse( request, HttpStatus.OK, EMPTY_HEADERS, links ); } @SuppressWarnings({"unchecked"}) @RequestMapping( value = "/{repository}", method = RequestMethod.GET ) @ResponseBody public ResponseEntity<?> listEntities( ServletServerHttpRequest request, PagingAndSorting pageSort, UriComponentsBuilder uriBuilder, @PathVariable String repository ) throws IOException { URI baseUri = uriBuilder.build().toUri(); RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Page page = null; Iterator iter; if ( repoMeta.repository() instanceof PagingAndSortingRepository ) { page = ((PagingAndSortingRepository) repoMeta.repository()).findAll( pageSort ); iter = page.iterator(); } else { iter = repoMeta.repository().findAll().iterator(); } Map<String, Object> resultMap = new HashMap<String, Object>(); Links links = new Links(); resultMap.put( LINKS, links.getLinks() ); List resultList = new ArrayList(); resultMap.put( "results", resultList ); boolean returnLinks = shouldReturnLinks( request.getServletRequest().getHeader( "Accept" ) ); if ( null != iter ) { while ( iter.hasNext() ) { Object o = iter.next(); Serializable id = (Serializable) repoMeta.entityMetadata().idAttribute().get( o ); if ( returnLinks ) { links.add( new SimpleLink( repoMeta.rel() + "." + o.getClass().getSimpleName(), buildUri( baseUri, repository, id.toString() ) ) ); } else { Map<String, Object> entityDto = extractPropertiesLinkAware( repoMeta.rel(), o, repoMeta.entityMetadata(), buildUri( baseUri, repository, id.toString() ) ); addSelfLink( baseUri, entityDto, repository, id.toString() ); resultList.add( entityDto ); } } links.add( new SimpleLink( repoMeta.rel() + ".search", buildUri( baseUri, repository, "search" ) ) ); } // Add paging links if ( null != page ) { resultMap.put( "totalCount", page.getTotalElements() ); resultMap.put( "totalPages", page.getTotalPages() ); resultMap.put( "currentPage", page.getNumber() + 1 ); // Copy over parameters UriComponentsBuilder urib = UriComponentsBuilder.fromUri( baseUri ).pathSegment( repository ); for ( String name : ((Map<String, Object>) request.getServletRequest().getParameterMap()).keySet() ) { if ( !config.getPageParamName().equals( name ) && !config.getLimitParamName().equals( name ) && !config.getSortParamName().equals( name ) ) { urib.queryParam( name, request.getServletRequest().getParameter( name ) ); } } URI nextPrevBase = urib.build().toUri(); maybeAddPrevNextLink( nextPrevBase, repoMeta, pageSort, page, !page.isFirstPage() && page.hasPreviousPage(), page.getNumber(), "prev", links ); maybeAddPrevNextLink( nextPrevBase, repoMeta, pageSort, page, !page.isLastPage() && page.hasNextPage(), page.getNumber() + 2, "next", links ); } return negotiateResponse( request, HttpStatus.OK, EMPTY_HEADERS, resultMap ); } @SuppressWarnings({"unchecked"}) @RequestMapping( value = "/{repository}/search", method = RequestMethod.GET ) @ResponseBody public ResponseEntity<?> listQueryMethods( ServletServerHttpRequest request, UriComponentsBuilder uriBuilder, @PathVariable String repository ) throws IOException { URI baseUri = uriBuilder.build().toUri(); RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Links links = new Links(); for ( Map.Entry<String, RepositoryQueryMethod> entry : ((Map<String, RepositoryQueryMethod>) repoMeta.queryMethods()) .entrySet() ) { String rel = repoMeta.rel() + "." + entry.getKey(); URI path = buildUri( baseUri, repository, "search", entry.getKey() ); RestResource resourceAnno = entry.getValue().method().getAnnotation( RestResource.class ); if ( null != resourceAnno ) { if ( StringUtils.hasText( resourceAnno.path() ) ) { path = buildUri( baseUri, repository, "search", resourceAnno.path() ); } if ( StringUtils.hasText( resourceAnno.rel() ) ) { rel = repoMeta.rel() + "." + resourceAnno.rel(); } } links.add( new SimpleLink( rel, path ) ); } return negotiateResponse( request, HttpStatus.OK, EMPTY_HEADERS, links ); } @SuppressWarnings({"unchecked"}) @RequestMapping( value = "/{repository}/search/{query}", method = RequestMethod.GET ) @ResponseBody public ResponseEntity<?> query( ServletServerHttpRequest request, PagingAndSorting pageSort, UriComponentsBuilder uriBuilder, @PathVariable String repository, @PathVariable String query ) throws InvocationTargetException, IllegalAccessException, IOException { URI baseUri = uriBuilder.build().toUri(); Page page = null; RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Repository repo = repoMeta.repository(); RepositoryQueryMethod queryMethod = repoMeta.queryMethod( query ); if ( null == queryMethod ) { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } Class<?>[] paramTypes = queryMethod.paramTypes(); String[] paramNames = queryMethod.paramNames(); Object[] paramVals = new Object[paramTypes.length]; for ( int i = 0; i < paramVals.length; i++ ) { String queryVal = request.getServletRequest().getParameter( paramNames[i] ); if ( String.class.isAssignableFrom( paramTypes[i] ) ) { // Param type is a String paramVals[i] = queryVal; } else if ( Pageable.class.isAssignableFrom( paramTypes[i] ) ) { // Handle paging paramVals[i] = pageSort; } else if ( Sort.class.isAssignableFrom( paramTypes[i] ) ) { // Handle sorting paramVals[i] = (null != pageSort ? pageSort.getSort() : null); } else if ( conversionService.canConvert( String.class, paramTypes[i] ) ) { // There's a converter from String -> param type paramVals[i] = conversionService.convert( queryVal, paramTypes[i] ); } else { // Param type isn't a "simple" type or no converter exists, try JSON try { paramVals[i] = objectMapper.readValue( queryVal, paramTypes[i] ); } catch ( IOException e ) { throw new IllegalArgumentException( e ); } } } Object result = queryMethod.method().invoke( repo, paramVals ); Iterator iter; - if ( result instanceof Collection ) { - iter = ((Collection) result).iterator(); - } else if ( result instanceof Page ) { - page = (Page) result; - iter = page.iterator(); + if ( null != result ) { + if ( result instanceof Collection ) { + iter = ((Collection) result).iterator(); + } else if ( result instanceof Page ) { + page = (Page) result; + iter = page.iterator(); + } else { + List l = new ArrayList(); + l.add( result ); + iter = l.iterator(); + } } else { - List l = new ArrayList(); - l.add( result ); - iter = l.iterator(); + iter = Collections.emptyList().iterator(); } Map<String, Object> resultMap = new HashMap<String, Object>(); Links links = new Links(); resultMap.put( LINKS, links.getLinks() ); List resultList = new ArrayList(); resultMap.put( "results", resultList ); boolean returnLinks = shouldReturnLinks( request.getServletRequest().getHeader( "Accept" ) ); while ( iter.hasNext() ) { Object obj = iter.next(); RepositoryMetadata elemRepoMeta = repositoryMetadataFor( obj.getClass() ); if ( null != elemRepoMeta ) { String id = elemRepoMeta.entityMetadata().idAttribute().get( obj ).toString(); if ( returnLinks ) { String rel = elemRepoMeta.rel() + "." + elemRepoMeta.entityMetadata().type().getSimpleName(); URI path = buildUri( baseUri, repository, id ); links.add( new SimpleLink( rel, path ) ); } else { Map<String, Object> entityDto = extractPropertiesLinkAware( repoMeta.rel(), obj, repoMeta.entityMetadata(), buildUri( baseUri, repository, id ) ); addSelfLink( baseUri, entityDto, repository, id ); resultList.add( entityDto ); } } } // Add paging links if ( null != page ) { resultMap.put( "totalCount", page.getTotalElements() ); resultMap.put( "totalPages", page.getTotalPages() ); resultMap.put( "currentPage", page.getNumber() + 1 ); // Copy over search parameters UriComponentsBuilder urib = UriComponentsBuilder.fromUri( baseUri ).pathSegment( repository, "search", query ); for ( String name : ((Map<String, Object>) request.getServletRequest().getParameterMap()).keySet() ) { if ( !config.getPageParamName().equals( name ) && !config.getLimitParamName().equals( name ) && !config.getSortParamName().equals( name ) ) { urib.queryParam( name, request.getServletRequest().getParameter( name ) ); } } URI nextPrevBase = urib.build().toUri(); maybeAddPrevNextLink( nextPrevBase, repoMeta, pageSort, page, !page.isFirstPage() && page.hasPreviousPage(), page.getNumber(), "prev", links ); maybeAddPrevNextLink( nextPrevBase, repoMeta, pageSort, page, !page.isLastPage() && page.hasNextPage(), page.getNumber() + 2, "next", links ); } else { resultMap.put( "totalCount", resultList.size() ); } return negotiateResponse( request, HttpStatus.OK, EMPTY_HEADERS, resultMap ); } @SuppressWarnings({"unchecked"}) @RequestMapping( value = "/{repository}", method = RequestMethod.POST ) @ResponseBody public ResponseEntity<?> create( ServletServerHttpRequest request, HttpServletRequest servletRequest, UriComponentsBuilder uriBuilder, @PathVariable String repository ) throws IOException { URI baseUri = uriBuilder.build().toUri(); RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); CrudRepository repo = repoMeta.repository(); MediaType incomingMediaType = request.getHeaders().getContentType(); final Object incoming = readIncoming( request, incomingMediaType, repoMeta.entityMetadata().type() ); if ( null == incoming ) { return negotiateResponse( request, HttpStatus.BAD_REQUEST, EMPTY_HEADERS, null ); } else { if ( null != applicationContext ) { applicationContext.publishEvent( new BeforeSaveEvent( incoming ) ); } Object savedEntity = repo.save( incoming ); if ( null != applicationContext ) { applicationContext.publishEvent( new AfterSaveEvent( savedEntity ) ); } String sId = repoMeta.entityMetadata().idAttribute().get( savedEntity ).toString(); URI selfUri = buildUri( baseUri, repository, sId ); HttpHeaders headers = new HttpHeaders(); headers.set( LOCATION, selfUri.toString() ); Object body = null; if ( null != servletRequest.getParameter( "returnBody" ) && "true".equals( servletRequest.getParameter( "returnBody" ) ) ) { Map<String, Object> entityDto = extractPropertiesLinkAware( repoMeta.rel(), savedEntity, repoMeta.entityMetadata(), buildUri( baseUri, repository, sId ) ); addSelfLink( baseUri, entityDto, repository, sId ); body = entityDto; } return negotiateResponse( request, HttpStatus.CREATED, headers, body ); } } @SuppressWarnings({"unchecked"}) @RequestMapping( value = "/{repository}/{id}", method = RequestMethod.GET ) @ResponseBody public ResponseEntity<?> entity( ServletServerHttpRequest request, UriComponentsBuilder uriBuilder, @PathVariable String repository, @PathVariable String id ) throws IOException { URI baseUri = uriBuilder.build().toUri(); RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Serializable serId = stringToSerializable( id, (Class<? extends Serializable>) repoMeta.entityMetadata() .idAttribute() .type() ); CrudRepository repo = repoMeta.repository(); Object entity = repo.findOne( serId ); if ( null == entity ) { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } else { HttpHeaders headers = new HttpHeaders(); if ( null != repoMeta.entityMetadata().versionAttribute() ) { Object version = repoMeta.entityMetadata().versionAttribute().get( entity ); if ( null != version ) { List<String> etags = request.getHeaders().getIfNoneMatch(); for ( String etag : etags ) { if ( ("\"" + version.toString() + "\"").equals( etag ) ) { return negotiateResponse( request, HttpStatus.NOT_MODIFIED, EMPTY_HEADERS, null ); } } headers.set( "ETag", "\"" + version.toString() + "\"" ); } } Map<String, Object> entityDto = extractPropertiesLinkAware( repoMeta.rel(), entity, repoMeta.entityMetadata(), buildUri( baseUri, repository, id ) ); addSelfLink( baseUri, entityDto, repository, id ); return negotiateResponse( request, HttpStatus.OK, headers, entityDto ); } } @SuppressWarnings({"unchecked"}) @RequestMapping( value = "/{repository}/{id}", method = { RequestMethod.PUT, RequestMethod.POST } ) @ResponseBody public ResponseEntity<?> createOrUpdate( ServletServerHttpRequest request, UriComponentsBuilder uriBuilder, @PathVariable String repository, @PathVariable String id ) throws IOException, IllegalAccessException, InstantiationException { URI baseUri = uriBuilder.build().toUri(); RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Serializable serId = stringToSerializable( id, (Class<? extends Serializable>) repoMeta.entityMetadata() .idAttribute() .type() ); CrudRepository repo = repoMeta.repository(); Class<?> domainType = repoMeta.entityMetadata().type(); final MediaType incomingMediaType = request.getHeaders().getContentType(); final Object incoming = readIncoming( request, incomingMediaType, domainType ); if ( null == incoming ) { throw new HttpMessageNotReadableException( "Could not create an instance of " + domainType.getSimpleName() + " from input." ); } else { repoMeta.entityMetadata().idAttribute().set( serId, incoming ); if ( request.getMethod() == HttpMethod.POST ) { if ( null != applicationContext ) { applicationContext.publishEvent( new BeforeSaveEvent( incoming ) ); } Object savedEntity = repo.save( incoming ); if ( null != applicationContext ) { applicationContext.publishEvent( new AfterSaveEvent( savedEntity ) ); } URI selfUri = buildUri( baseUri, repository, id ); HttpHeaders headers = new HttpHeaders(); headers.set( LOCATION, selfUri.toString() ); boolean returnBody = true; if ( null != request.getServletRequest().getParameter( "returnBody" ) ) { returnBody = Boolean.parseBoolean( request.getServletRequest().getParameter( "returnBody" ) ); } return negotiateResponse( request, HttpStatus.CREATED, headers, (returnBody ? savedEntity : null) ); } else { Object entity = repo.findOne( serId ); if ( null == entity ) { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } else { for ( AttributeMetadata attrMeta : (Collection<AttributeMetadata>) repoMeta.entityMetadata() .embeddedAttributes() .values() ) { Object incomingVal = attrMeta.get( incoming ); if ( null != incomingVal ) { attrMeta.set( incomingVal, entity ); } } if ( null != applicationContext ) { applicationContext.publishEvent( new BeforeSaveEvent( entity ) ); } Object savedEntity = repo.save( entity ); if ( null != applicationContext ) { applicationContext.publishEvent( new AfterSaveEvent( savedEntity ) ); } return negotiateResponse( request, HttpStatus.NO_CONTENT, EMPTY_HEADERS, null ); } } } } @SuppressWarnings({"unchecked"}) @RequestMapping( value = "/{repository}/{id}", method = RequestMethod.DELETE ) @ResponseBody public ResponseEntity<?> deleteEntity( ServletServerHttpRequest request, @PathVariable String repository, @PathVariable String id ) throws IOException { RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Serializable serId = stringToSerializable( id, (Class<? extends Serializable>) repoMeta.entityMetadata() .idAttribute() .type() ); CrudRepository repo = repoMeta.repository(); Object entity = repo.findOne( serId ); if ( null == entity ) { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } else { if ( null != applicationContext ) { applicationContext.publishEvent( new BeforeDeleteEvent( entity ) ); } repo.delete( serId ); if ( null != applicationContext ) { applicationContext.publishEvent( new AfterDeleteEvent( entity ) ); } return negotiateResponse( request, HttpStatus.NO_CONTENT, EMPTY_HEADERS, null ); } } @SuppressWarnings({"unchecked"}) @RequestMapping( value = "/{repository}/{id}/{property}", method = RequestMethod.GET ) @ResponseBody public ResponseEntity<?> propertyOfEntity( ServletServerHttpRequest request, UriComponentsBuilder uriBuilder, @PathVariable String repository, @PathVariable String id, @PathVariable String property ) throws IOException { URI baseUri = uriBuilder.build().toUri(); RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Serializable serId = stringToSerializable( id, (Class<? extends Serializable>) repoMeta.entityMetadata() .idAttribute() .type() ); CrudRepository repo = repoMeta.repository(); Object entity = repo.findOne( serId ); if ( null == entity ) { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } else { AttributeMetadata attrMeta = repoMeta.entityMetadata().attribute( property ); if ( null == attrMeta ) { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } else { Class<?> attrType = attrMeta.elementType(); if ( null == attrType ) { attrType = attrMeta.type(); } RepositoryMetadata propRepoMeta = repositoryMetadataFor( attrType ); Object propVal = attrMeta.get( entity ); AttributeMetadata idAttr = propRepoMeta.entityMetadata().idAttribute(); if ( null != propVal ) { Links links = new Links(); if ( propVal instanceof Collection ) { for ( Object o : (Collection) propVal ) { String propValId = idAttr.get( o ).toString(); String rel = repository + "." + entity.getClass().getSimpleName() + "." + attrType.getSimpleName(); URI path = buildUri( baseUri, repository, id, property, propValId ); links.add( new SimpleLink( rel, path ) ); } } else if ( propVal instanceof Map ) { for ( Map.Entry<Object, Object> entry : ((Map<Object, Object>) propVal).entrySet() ) { String propValId = idAttr.get( entry.getValue() ).toString(); URI path = buildUri( baseUri, repository, id, property, propValId ); Object oKey = entry.getKey(); String sKey; if ( ClassUtils.isAssignable( oKey.getClass(), String.class ) ) { sKey = (String) oKey; } else { sKey = conversionService.convert( oKey, String.class ); } String rel = repository + "." + entity.getClass().getSimpleName() + "." + sKey; links.add( new SimpleLink( rel, path ) ); } } else { String propValId = idAttr.get( propVal ).toString(); String rel = repository + "." + entity.getClass().getSimpleName() + "." + property; URI path = buildUri( baseUri, repository, id, property, propValId ); links.add( new SimpleLink( rel, path ) ); } return negotiateResponse( request, HttpStatus.OK, EMPTY_HEADERS, links ); } else { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } } } } @SuppressWarnings({"unchecked"}) @RequestMapping( value = "/{repository}/{id}/{property}", method = { RequestMethod.PUT, RequestMethod.POST } ) @ResponseBody public ResponseEntity<?> updatePropertyOfEntity( final ServletServerHttpRequest request, UriComponentsBuilder uriBuilder, @PathVariable String repository, @PathVariable String id, final @PathVariable String property ) throws IOException { URI baseUri = uriBuilder.build().toUri(); final RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Serializable serId = stringToSerializable( id, (Class<? extends Serializable>) repoMeta.entityMetadata() .idAttribute() .type() ); CrudRepository repo = repoMeta.repository(); final Object entity = repo.findOne( serId ); if ( null == entity ) { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } else { final AttributeMetadata attrMeta = repoMeta.entityMetadata().attribute( property ); if ( null == attrMeta ) { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } else { Object linked = attrMeta.get( entity ); final AtomicReference<String> rel = new AtomicReference<String>(); Handler<Object, ResponseEntity<?>> entityHandler = new Handler<Object, ResponseEntity<?>>() { @Override public ResponseEntity<?> handle( Object linkedEntity ) { if ( attrMeta.isCollectionLike() ) { Collection c = new ArrayList(); Collection current = attrMeta.asCollection( entity ); if ( request.getMethod() == HttpMethod.POST && null != current ) { c.addAll( current ); } c.add( linkedEntity ); attrMeta.set( c, entity ); } else if ( attrMeta.isSetLike() ) { Set s = new HashSet(); Set current = attrMeta.asSet( entity ); if ( request.getMethod() == HttpMethod.POST && null != current ) { s.addAll( current ); } s.add( linkedEntity ); attrMeta.set( s, entity ); } else if ( attrMeta.isMapLike() ) { Map m = new HashMap(); Map current = attrMeta.asMap( entity ); if ( request.getMethod() == HttpMethod.POST && null != current ) { m.putAll( current ); } String key = rel.get(); if ( null == key ) { try { return negotiateResponse( request, HttpStatus.NOT_ACCEPTABLE, EMPTY_HEADERS, null ); } catch ( IOException e ) { throw new RuntimeException( e ); } } else { m.put( rel.get(), linkedEntity ); attrMeta.set( m, entity ); } } else { attrMeta.set( linkedEntity, entity ); } return null; } }; MediaType incomingMediaType = request.getHeaders().getContentType(); if ( incomingMediaType.getSubtype().startsWith( "uri-list" ) ) { BufferedReader in = new BufferedReader( new InputStreamReader( request.getBody() ) ); String line; while ( null != (line = in.readLine()) ) { String sLinkUri = line.trim(); Object o = resolveTopLevelResource( baseUri, sLinkUri ); if ( null != o ) { ResponseEntity<?> possibleResponse = entityHandler.handle( o ); if ( null != possibleResponse ) { return possibleResponse; } } } } else { final Map<String, List<Map<String, String>>> incoming = readIncoming( request, incomingMediaType, Map.class ); for ( Map<String, String> link : incoming.get( LINKS ) ) { String sLinkUri = link.get( "href" ); Object o = resolveTopLevelResource( baseUri, sLinkUri ); rel.set( link.get( "rel" ) ); if ( null != o ) { ResponseEntity<?> possibleResponse = entityHandler.handle( o ); if ( null != possibleResponse ) { return possibleResponse; } } } } if ( null != applicationContext ) { applicationContext.publishEvent( new BeforeSaveEvent( entity ) ); applicationContext.publishEvent( new BeforeLinkSaveEvent( entity, linked ) ); } Object savedEntity = repo.save( entity ); if ( null != applicationContext ) { linked = attrMeta.get( savedEntity ); applicationContext.publishEvent( new AfterLinkSaveEvent( savedEntity, linked ) ); applicationContext.publishEvent( new AfterSaveEvent( savedEntity ) ); } if ( request.getMethod() == HttpMethod.PUT ) { return negotiateResponse( request, HttpStatus.NO_CONTENT, EMPTY_HEADERS, null ); } else { return negotiateResponse( request, HttpStatus.CREATED, EMPTY_HEADERS, null ); } } } } @SuppressWarnings({"unchecked"}) @RequestMapping( value = "/{repository}/{id}/{property}", method = { RequestMethod.DELETE } ) @ResponseBody public ResponseEntity<?> clearLinks( ServletServerHttpRequest request, @PathVariable String repository, @PathVariable String id, @PathVariable String property ) throws IOException { RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Serializable serId = stringToSerializable( id, (Class<? extends Serializable>) repoMeta.entityMetadata() .idAttribute() .type() ); CrudRepository repo = repoMeta.repository(); final Object entity = repo.findOne( serId ); if ( null == entity ) { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } else { AttributeMetadata attrMeta = repoMeta.entityMetadata().attribute( property ); if ( null != attrMeta ) { Object linked = attrMeta.get( entity ); attrMeta.set( null, entity ); if ( null != applicationContext ) { applicationContext.publishEvent( new BeforeLinkSaveEvent( entity, linked ) ); } Object savedEntity = repo.save( entity ); if ( null != applicationContext ) { applicationContext.publishEvent( new AfterLinkSaveEvent( savedEntity, null ) ); } return negotiateResponse( request, HttpStatus.NO_CONTENT, EMPTY_HEADERS, null ); } else { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } } } @SuppressWarnings({"unchecked"}) @RequestMapping( value = "/{repository}/{id}/{property}/{linkedId}", method = { RequestMethod.GET } ) @ResponseBody public ResponseEntity<?> linkedEntity( ServletServerHttpRequest request, UriComponentsBuilder uriBuilder, @PathVariable String repository, @PathVariable String id, @PathVariable String property, @PathVariable String linkedId ) throws IOException { URI baseUri = uriBuilder.build().toUri(); RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Serializable serId = stringToSerializable( id, (Class<? extends Serializable>) repoMeta.entityMetadata() .idAttribute() .type() ); CrudRepository repo = repoMeta.repository(); final Object entity = repo.findOne( serId ); if ( null != entity ) { AttributeMetadata attrMeta = repoMeta.entityMetadata().attribute( property ); if ( null != attrMeta ) { // Find linked entity RepositoryMetadata linkedRepoMeta = repositoryMetadataFor( attrMeta ); if ( null != linkedRepoMeta ) { CrudRepository linkedRepo = linkedRepoMeta.repository(); Serializable sChildId = stringToSerializable( linkedId, (Class<? extends Serializable>) linkedRepoMeta.entityMetadata() .idAttribute() .type() ); Object linkedEntity = linkedRepo.findOne( sChildId ); if ( null != linkedEntity ) { Map<String, Object> entityDto = extractPropertiesLinkAware( linkedRepoMeta.rel(), linkedEntity, linkedRepoMeta.entityMetadata(), buildUri( baseUri, linkedRepoMeta.name(), linkedId ) ); URI selfUri = addSelfLink( baseUri, entityDto, linkedRepoMeta.name(), linkedId ); HttpHeaders headers = new HttpHeaders(); headers.add( "Content-Location", selfUri.toString() ); return negotiateResponse( request, HttpStatus.OK, headers, entityDto ); } } } } return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } @SuppressWarnings({"unchecked"}) @RequestMapping( value = "/{repository}/{id}/{property}/{linkedId}", method = { RequestMethod.DELETE } ) @ResponseBody public ResponseEntity<?> deleteLink( ServletServerHttpRequest request, @PathVariable String repository, @PathVariable String id, @PathVariable String property, @PathVariable String linkedId ) throws IOException { RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Serializable serId = stringToSerializable( id, (Class<? extends Serializable>) repoMeta.entityMetadata() .idAttribute() .type() ); CrudRepository repo = repoMeta.repository(); Object entity = repo.findOne( serId ); if ( null == entity ) { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } else { AttributeMetadata attrMeta = repoMeta.entityMetadata().attribute( property ); if ( null != attrMeta ) { // Find linked entity RepositoryMetadata linkedRepoMeta = repositoryMetadataFor( attrMeta ); if ( null != linkedRepoMeta ) { CrudRepository linkedRepo = linkedRepoMeta.repository(); Serializable sChildId = stringToSerializable( linkedId, (Class<? extends Serializable>) linkedRepoMeta.entityMetadata() .idAttribute() .type() ); Object linkedEntity = linkedRepo.findOne( sChildId ); if ( null != linkedEntity ) { // Remove linked entity from relationship based on property type if ( attrMeta.isCollectionLike() ) { Collection c = attrMeta.asCollection( entity ); if ( null != c ) { c.remove( linkedEntity ); } } else if ( attrMeta.isSetLike() ) { Set s = attrMeta.asSet( entity ); if ( null != s ) { s.remove( linkedEntity ); } } else if ( attrMeta.isMapLike() ) { Object keyToRemove = null; Map<Object, Object> m = attrMeta.asMap( entity ); if ( null != m ) { for ( Map.Entry<Object, Object> entry : m.entrySet() ) { Object val = entry.getValue(); if ( null != val && val.equals( linkedEntity ) ) { keyToRemove = entry.getKey(); break; } } if ( null != keyToRemove ) { m.remove( keyToRemove ); } } } else { attrMeta.set( linkedEntity, entity ); } return negotiateResponse( request, HttpStatus.NO_CONTENT, EMPTY_HEADERS, null ); } } } } return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } @ExceptionHandler(RepositoryNotFoundException.class) @ResponseBody public ResponseEntity handleRepositoryNotFoundFailure( RepositoryNotFoundException e, ServletServerHttpRequest request ) throws IOException { if ( LOG.isWarnEnabled() ) { LOG.warn( "RepositoryNotFoundException: " + e.getMessage() ); } return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } @SuppressWarnings({"unchecked"}) @ExceptionHandler(OptimisticLockingFailureException.class) @ResponseBody public ResponseEntity handleLockingFailure( OptimisticLockingFailureException ex, ServletServerHttpRequest request ) throws IOException { LOG.error( ex.getMessage(), ex ); HttpHeaders headers = new HttpHeaders(); headers.setContentType( MediaType.APPLICATION_JSON ); Map m = new HashMap(); m.put( "message", ex.getMessage() ); return negotiateResponse( request, HttpStatus.CONFLICT, headers, objectMapper.writeValueAsBytes( m ) ); } @SuppressWarnings({"unchecked"}) @ExceptionHandler(RepositoryConstraintViolationException.class) @ResponseBody public ResponseEntity handleValidationFailure( RepositoryConstraintViolationException ex, ServletServerHttpRequest request ) throws IOException { LOG.error( ex.getMessage(), ex ); Map m = new HashMap(); List<String> errors = new ArrayList<String>(); for ( FieldError fe : ex.getErrors().getFieldErrors() ) { errors.add( fe.getDefaultMessage() ); } m.put( "errors", errors ); return negotiateResponse( request, HttpStatus.BAD_REQUEST, EMPTY_HEADERS, m ); } @SuppressWarnings({"unchecked"}) @ExceptionHandler(HttpMessageNotReadableException.class) @ResponseBody public ResponseEntity handleMessageConversionFailure( HttpMessageNotReadableException ex, ServletServerHttpRequest request ) throws IOException { LOG.error( ex.getMessage(), ex ); HttpHeaders headers = new HttpHeaders(); headers.setContentType( MediaType.APPLICATION_JSON ); Map m = new HashMap(); m.put( "message", ex.getMessage() ); return negotiateResponse( request, HttpStatus.BAD_REQUEST, headers, objectMapper.writeValueAsBytes( m ) ); } /* ----------------------------------- Internal helper methods ----------------------------------- */ private static URI buildUri( URI baseUri, String... pathSegments ) { return UriComponentsBuilder.fromUri( baseUri ).pathSegment( pathSegments ).build().toUri(); } @SuppressWarnings({"unchecked"}) private URI addSelfLink( URI baseUri, Map<String, Object> model, String... pathComponents ) { List<Link> links = (List<Link>) model.get( LINKS ); if ( null == links ) { links = new ArrayList<Link>(); model.put( LINKS, links ); } URI selfUri = buildUri( baseUri, pathComponents ); links.add( new SimpleLink( SELF, selfUri ) ); return selfUri; } @SuppressWarnings({"unchecked"}) private void maybeAddPrevNextLink( URI resourceUri, RepositoryMetadata repoMeta, PagingAndSorting pageSort, Page page, boolean addIf, int nextPage, String rel, Links links ) { if ( null != page && addIf ) { UriComponentsBuilder urib = UriComponentsBuilder.fromUri( resourceUri ); urib.queryParam( config.getPageParamName(), nextPage ); // PageRequest is 0-based, so it's already (page - 1) urib.queryParam( config.getLimitParamName(), page.getSize() ); pageSort.addSortParameters( urib ); links.add( new SimpleLink( repoMeta.rel() + "." + rel, urib.build().toUri() ) ); } } @SuppressWarnings({"unchecked"}) private <V extends Serializable> V stringToSerializable( String s, Class<V> targetType ) { if ( ClassUtils.isAssignable( targetType, String.class ) ) { return (V) s; } else { return conversionService.convert( s, targetType ); } } @SuppressWarnings({"unchecked"}) private Object resolveTopLevelResource( URI baseUri, String uri ) { URI href = URI.create( uri ); URI relativeUri = baseUri.relativize( href ); Stack<URI> uris = UriUtils.explode( baseUri, relativeUri ); if ( uris.size() > 1 ) { String repoName = UriUtils.path( uris.get( 0 ) ); String sId = UriUtils.path( uris.get( 1 ) ); RepositoryMetadata repoMeta = repositoryMetadataFor( repoName ); CrudRepository repo = repoMeta.repository(); if ( null == repo ) { return null; } EntityMetadata entityMeta = repoMeta.entityMetadata(); if ( null == entityMeta ) { return null; } Class<? extends Serializable> idType = (Class<? extends Serializable>) entityMeta.idAttribute().type(); Serializable serId = stringToSerializable( sId, idType ); return repo.findOne( serId ); } return null; } @SuppressWarnings({"unchecked"}) private <V> V readIncoming( HttpInputMessage request, MediaType incomingMediaType, Class<V> targetType ) throws IOException { for ( HttpMessageConverter converter : httpMessageConverters ) { if ( converter.canRead( targetType, incomingMediaType ) ) { return (V) converter.read( targetType, request ); } } return null; } @SuppressWarnings({"unchecked"}) private Map<String, Object> extractPropertiesLinkAware( String repoRel, Object entity, EntityMetadata<AttributeMetadata> entityMetadata, URI baseUri ) { final Map<String, Object> entityDto = new HashMap<String, Object>(); for ( Map.Entry<String, AttributeMetadata> attrMeta : entityMetadata.embeddedAttributes().entrySet() ) { String name = attrMeta.getKey(); Object val = attrMeta.getValue().get( entity ); if ( null != val ) { entityDto.put( name, val ); } } for ( String attrName : entityMetadata.linkedAttributes().keySet() ) { URI uri = buildUri( baseUri, attrName ); Link l = new SimpleLink( repoRel + "." + entity.getClass().getSimpleName() + "." + attrName, uri ); List<Link> links = (List<Link>) entityDto.get( LINKS ); if ( null == links ) { links = new ArrayList<Link>(); entityDto.put( LINKS, links ); } links.add( l ); } return entityDto; } private String viewName( String name ) { return "org.springframework.data.rest." + name; } private boolean shouldReturnLinks( String acceptHeader ) { if ( null != acceptHeader ) { List<MediaType> accept = MediaType.parseMediaTypes( acceptHeader ); for ( MediaType mt : accept ) { if ( mt.getSubtype().startsWith( "x-spring-data-verbose" ) ) { return false; } else if ( mt.getSubtype().startsWith( "x-spring-data-compact" ) ) { return true; } else if ( mt.getSubtype().equals( "uri-list" ) ) { return true; } } } return false; } private ResponseEntity<?> noConverterFoundError( Class<?> fromResponseType ) { return new ResponseEntity<String>( String.format( "{\"message\": \"No converter found for class <%s>\"}", fromResponseType ), HttpStatus.INTERNAL_SERVER_ERROR ); } @SuppressWarnings({"unchecked"}) private ResponseEntity<byte[]> negotiateResponse( final ServletServerHttpRequest request, final HttpStatus status, final HttpHeaders headers, final Object resource ) throws IOException { String jsonpParam = request.getServletRequest().getParameter( config.getJsonpParamName() ); String jsonpOnErrParam = null; if ( null != config.getJsonpOnErrParamName() ) { jsonpOnErrParam = request.getServletRequest().getParameter( config.getJsonpOnErrParamName() ); } HttpStatus responseStatus = status; byte[] responseBody = null; if ( null != resource ) { List<MediaType> acceptableTypes = new ArrayList<MediaType>(); if ( !request.getHeaders().getAccept().isEmpty() && !Arrays.equals( request.getHeaders().getAccept().toArray(), ALL_TYPES.toArray() ) ) { acceptableTypes.addAll( request.getHeaders().getAccept() ); } else { acceptableTypes.add( MediaType.APPLICATION_JSON ); } for ( MediaType acceptType : acceptableTypes ) { HttpMessageConverter converterToUse = null; for ( HttpMessageConverter conv : config.getCustomConverters() ) { if ( conv.canWrite( resource.getClass(), acceptType ) ) { converterToUse = conv; break; } } if ( null == converterToUse ) { for ( HttpMessageConverter conv : httpMessageConverters ) { if ( conv.canWrite( resource.getClass(), acceptType ) ) { converterToUse = conv; break; } } } if ( null != converterToUse ) { final ByteArrayOutputStream bout = new ByteArrayOutputStream(); converterToUse.write( resource, acceptType, new HttpOutputMessage() { @Override public OutputStream getBody() throws IOException { return bout; } @Override public HttpHeaders getHeaders() { return headers; } } ); if ( null != jsonpParam || null != jsonpOnErrParam ) { headers.setContentType( JacksonUtil.APPLICATION_JAVASCRIPT ); } responseBody = bout.toByteArray(); } else { responseStatus = HttpStatus.NOT_ACCEPTABLE; headers.setContentType( MediaType.TEXT_PLAIN ); StringBuilder sb = new StringBuilder(); if ( null != jsonpOnErrParam ) { sb.append( "\"" ); } for ( MediaType mt : availableMediaTypes ) { sb.append( mt.toString() ).append( '\n' ); } if ( null != jsonpOnErrParam ) { sb.append( "\"" ); } responseBody = sb.toString().getBytes(); } } } if ( responseStatus.value() > 400 && (null != jsonpOnErrParam) ) { String jsonp = jsonpOnErrParam + "(" + responseStatus.value() + "," + (null == responseBody ? "null" : new String( responseBody )) + ")"; responseBody = jsonp.getBytes(); responseStatus = HttpStatus.OK; } else if ( null != jsonpParam ) { String jsonp = jsonpParam + "(" + (null == responseBody ? "null" : new String( responseBody )) + ")"; responseBody = jsonp.getBytes(); } if ( null == responseBody ) { headers.setContentLength( 0 ); } else { headers.setContentLength( responseBody.length ); } return new ResponseEntity<byte[]>( responseBody, headers, responseStatus ); } }
false
true
public ResponseEntity<?> query( ServletServerHttpRequest request, PagingAndSorting pageSort, UriComponentsBuilder uriBuilder, @PathVariable String repository, @PathVariable String query ) throws InvocationTargetException, IllegalAccessException, IOException { URI baseUri = uriBuilder.build().toUri(); Page page = null; RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Repository repo = repoMeta.repository(); RepositoryQueryMethod queryMethod = repoMeta.queryMethod( query ); if ( null == queryMethod ) { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } Class<?>[] paramTypes = queryMethod.paramTypes(); String[] paramNames = queryMethod.paramNames(); Object[] paramVals = new Object[paramTypes.length]; for ( int i = 0; i < paramVals.length; i++ ) { String queryVal = request.getServletRequest().getParameter( paramNames[i] ); if ( String.class.isAssignableFrom( paramTypes[i] ) ) { // Param type is a String paramVals[i] = queryVal; } else if ( Pageable.class.isAssignableFrom( paramTypes[i] ) ) { // Handle paging paramVals[i] = pageSort; } else if ( Sort.class.isAssignableFrom( paramTypes[i] ) ) { // Handle sorting paramVals[i] = (null != pageSort ? pageSort.getSort() : null); } else if ( conversionService.canConvert( String.class, paramTypes[i] ) ) { // There's a converter from String -> param type paramVals[i] = conversionService.convert( queryVal, paramTypes[i] ); } else { // Param type isn't a "simple" type or no converter exists, try JSON try { paramVals[i] = objectMapper.readValue( queryVal, paramTypes[i] ); } catch ( IOException e ) { throw new IllegalArgumentException( e ); } } } Object result = queryMethod.method().invoke( repo, paramVals ); Iterator iter; if ( result instanceof Collection ) { iter = ((Collection) result).iterator(); } else if ( result instanceof Page ) { page = (Page) result; iter = page.iterator(); } else { List l = new ArrayList(); l.add( result ); iter = l.iterator(); } Map<String, Object> resultMap = new HashMap<String, Object>(); Links links = new Links(); resultMap.put( LINKS, links.getLinks() ); List resultList = new ArrayList(); resultMap.put( "results", resultList ); boolean returnLinks = shouldReturnLinks( request.getServletRequest().getHeader( "Accept" ) ); while ( iter.hasNext() ) { Object obj = iter.next(); RepositoryMetadata elemRepoMeta = repositoryMetadataFor( obj.getClass() ); if ( null != elemRepoMeta ) { String id = elemRepoMeta.entityMetadata().idAttribute().get( obj ).toString(); if ( returnLinks ) { String rel = elemRepoMeta.rel() + "." + elemRepoMeta.entityMetadata().type().getSimpleName(); URI path = buildUri( baseUri, repository, id ); links.add( new SimpleLink( rel, path ) ); } else { Map<String, Object> entityDto = extractPropertiesLinkAware( repoMeta.rel(), obj, repoMeta.entityMetadata(), buildUri( baseUri, repository, id ) ); addSelfLink( baseUri, entityDto, repository, id ); resultList.add( entityDto ); } } } // Add paging links if ( null != page ) { resultMap.put( "totalCount", page.getTotalElements() ); resultMap.put( "totalPages", page.getTotalPages() ); resultMap.put( "currentPage", page.getNumber() + 1 ); // Copy over search parameters UriComponentsBuilder urib = UriComponentsBuilder.fromUri( baseUri ).pathSegment( repository, "search", query ); for ( String name : ((Map<String, Object>) request.getServletRequest().getParameterMap()).keySet() ) { if ( !config.getPageParamName().equals( name ) && !config.getLimitParamName().equals( name ) && !config.getSortParamName().equals( name ) ) { urib.queryParam( name, request.getServletRequest().getParameter( name ) ); } } URI nextPrevBase = urib.build().toUri(); maybeAddPrevNextLink( nextPrevBase, repoMeta, pageSort, page, !page.isFirstPage() && page.hasPreviousPage(), page.getNumber(), "prev", links ); maybeAddPrevNextLink( nextPrevBase, repoMeta, pageSort, page, !page.isLastPage() && page.hasNextPage(), page.getNumber() + 2, "next", links ); } else { resultMap.put( "totalCount", resultList.size() ); } return negotiateResponse( request, HttpStatus.OK, EMPTY_HEADERS, resultMap ); }
public ResponseEntity<?> query( ServletServerHttpRequest request, PagingAndSorting pageSort, UriComponentsBuilder uriBuilder, @PathVariable String repository, @PathVariable String query ) throws InvocationTargetException, IllegalAccessException, IOException { URI baseUri = uriBuilder.build().toUri(); Page page = null; RepositoryMetadata repoMeta = repositoryMetadataFor( repository ); Repository repo = repoMeta.repository(); RepositoryQueryMethod queryMethod = repoMeta.queryMethod( query ); if ( null == queryMethod ) { return negotiateResponse( request, HttpStatus.NOT_FOUND, EMPTY_HEADERS, null ); } Class<?>[] paramTypes = queryMethod.paramTypes(); String[] paramNames = queryMethod.paramNames(); Object[] paramVals = new Object[paramTypes.length]; for ( int i = 0; i < paramVals.length; i++ ) { String queryVal = request.getServletRequest().getParameter( paramNames[i] ); if ( String.class.isAssignableFrom( paramTypes[i] ) ) { // Param type is a String paramVals[i] = queryVal; } else if ( Pageable.class.isAssignableFrom( paramTypes[i] ) ) { // Handle paging paramVals[i] = pageSort; } else if ( Sort.class.isAssignableFrom( paramTypes[i] ) ) { // Handle sorting paramVals[i] = (null != pageSort ? pageSort.getSort() : null); } else if ( conversionService.canConvert( String.class, paramTypes[i] ) ) { // There's a converter from String -> param type paramVals[i] = conversionService.convert( queryVal, paramTypes[i] ); } else { // Param type isn't a "simple" type or no converter exists, try JSON try { paramVals[i] = objectMapper.readValue( queryVal, paramTypes[i] ); } catch ( IOException e ) { throw new IllegalArgumentException( e ); } } } Object result = queryMethod.method().invoke( repo, paramVals ); Iterator iter; if ( null != result ) { if ( result instanceof Collection ) { iter = ((Collection) result).iterator(); } else if ( result instanceof Page ) { page = (Page) result; iter = page.iterator(); } else { List l = new ArrayList(); l.add( result ); iter = l.iterator(); } } else { iter = Collections.emptyList().iterator(); } Map<String, Object> resultMap = new HashMap<String, Object>(); Links links = new Links(); resultMap.put( LINKS, links.getLinks() ); List resultList = new ArrayList(); resultMap.put( "results", resultList ); boolean returnLinks = shouldReturnLinks( request.getServletRequest().getHeader( "Accept" ) ); while ( iter.hasNext() ) { Object obj = iter.next(); RepositoryMetadata elemRepoMeta = repositoryMetadataFor( obj.getClass() ); if ( null != elemRepoMeta ) { String id = elemRepoMeta.entityMetadata().idAttribute().get( obj ).toString(); if ( returnLinks ) { String rel = elemRepoMeta.rel() + "." + elemRepoMeta.entityMetadata().type().getSimpleName(); URI path = buildUri( baseUri, repository, id ); links.add( new SimpleLink( rel, path ) ); } else { Map<String, Object> entityDto = extractPropertiesLinkAware( repoMeta.rel(), obj, repoMeta.entityMetadata(), buildUri( baseUri, repository, id ) ); addSelfLink( baseUri, entityDto, repository, id ); resultList.add( entityDto ); } } } // Add paging links if ( null != page ) { resultMap.put( "totalCount", page.getTotalElements() ); resultMap.put( "totalPages", page.getTotalPages() ); resultMap.put( "currentPage", page.getNumber() + 1 ); // Copy over search parameters UriComponentsBuilder urib = UriComponentsBuilder.fromUri( baseUri ).pathSegment( repository, "search", query ); for ( String name : ((Map<String, Object>) request.getServletRequest().getParameterMap()).keySet() ) { if ( !config.getPageParamName().equals( name ) && !config.getLimitParamName().equals( name ) && !config.getSortParamName().equals( name ) ) { urib.queryParam( name, request.getServletRequest().getParameter( name ) ); } } URI nextPrevBase = urib.build().toUri(); maybeAddPrevNextLink( nextPrevBase, repoMeta, pageSort, page, !page.isFirstPage() && page.hasPreviousPage(), page.getNumber(), "prev", links ); maybeAddPrevNextLink( nextPrevBase, repoMeta, pageSort, page, !page.isLastPage() && page.hasNextPage(), page.getNumber() + 2, "next", links ); } else { resultMap.put( "totalCount", resultList.size() ); } return negotiateResponse( request, HttpStatus.OK, EMPTY_HEADERS, resultMap ); }
diff --git a/simulator/src/java/main/ca/nengo/model/nef/impl/DecodedTermination.java b/simulator/src/java/main/ca/nengo/model/nef/impl/DecodedTermination.java index c2541288..649ccc08 100644 --- a/simulator/src/java/main/ca/nengo/model/nef/impl/DecodedTermination.java +++ b/simulator/src/java/main/ca/nengo/model/nef/impl/DecodedTermination.java @@ -1,486 +1,494 @@ /* 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 "DecodedTermination.java". Description: "A Termination of decoded state vectors onto an NEFEnsemble" The Initial Developer of the Original Code is Bryan Tripp & Centre for Theoretical Neuroscience, University of Waterloo. Copyright (C) 2006-2008. All Rights Reserved. Alternatively, the contents of this file may be used under the terms of the GNU Public License license (the GPL License), in which case the provisions of GPL License are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL License and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL License. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL License. */ package ca.nengo.model.nef.impl; import java.util.Properties; import org.apache.log4j.Logger; import ca.nengo.dynamics.Integrator; import ca.nengo.dynamics.LinearSystem; import ca.nengo.dynamics.impl.CanonicalModel; import ca.nengo.dynamics.impl.LTISystem; import ca.nengo.model.InstantaneousOutput; import ca.nengo.model.Node; import ca.nengo.model.Probeable; import ca.nengo.model.RealOutput; import ca.nengo.model.Resettable; import ca.nengo.model.SimulationException; import ca.nengo.model.StructuralException; import ca.nengo.model.Termination; import ca.nengo.model.Units; import ca.nengo.model.impl.RealOutputImpl; import ca.nengo.model.neuron.SynapticIntegrator; import ca.nengo.util.MU; import ca.nengo.util.TimeSeries; import ca.nengo.util.impl.TimeSeriesImpl; /** * <p>A Termination of decoded state vectors onto an NEFEnsemble. A DecodedTermination * performs a linear transformation on incoming vectors, mapping them into the * space of the NEFEnsemble to which this Termination belongs. A DecodedTermination * also applies linear PSC dynamics (typically exponential decay) to the resulting * vector.</p> * * <p>Non-linear dynamics are not allowed at this level. This is because the vector input * to an NEFEnsemble only has meaning in terms of the decomposition of synaptic weights * into decoding vectors, transformation matrix, and encoding vectors. Linear PSC dynamics * actually apply to currents, but if everything is linear we can re-order the dynamics * and the encoders for convenience (so that the dynamics seem to operate on the * state vectors). In contrast, non-linear dynamics must be modeled within each Neuron, * because all inputs to a non-linear dynamical process must be taken into account before * the effect of any single input is known.</p> * * @author Bryan Tripp */ public class DecodedTermination implements Termination, Resettable, Probeable { private static final long serialVersionUID = 1L; private static Logger ourLogger = Logger.getLogger(DecodedTermination.class); /** * Name of Probeable output state. */ public static final String OUTPUT = "output"; private Node myNode; private String myName; private int myOutputDimension; private float[][] myTransform; private LinearSystem myDynamicsTemplate; private LinearSystem[] myDynamics; private Integrator myIntegrator; private Units[] myNullUnits; private RealOutput myInputValues; private float myTime; private float[] myOutputValues; private boolean myTauMutable; private DecodedTermination myScalingTermination; private float[] myStaticBias; private float myTau; private boolean myModulatory; private float[][] myInitialState; private boolean myValuesSet; /** * @param node The parent Node * @param name The name of this Termination * @param transform A matrix that maps input (which has the dimension of this Termination) * onto the state space represented by the NEFEnsemble to which the Termination belongs * @param dynamics Post-synaptic current dynamics (single-input single-output). Time-varying * dynamics are OK, but non-linear dynamics don't make sense here, because other * Terminations may input onto the same neurons. * @param integrator Numerical integrator with which to solve dynamics * @throws StructuralException If dynamics are not SISO or given transform is not a matrix */ public DecodedTermination(Node node, String name, float[][] transform, LinearSystem dynamics, Integrator integrator) throws StructuralException { if (dynamics.getInputDimension() != 1 || dynamics.getOutputDimension() != 1) { throw new StructuralException("Dynamics must be single-input single-output"); } myOutputDimension = transform.length; setTransform(transform); myNode = node; myName = name; myIntegrator = integrator; //we save a little time by not reporting units to the dynamical system at each step myNullUnits = new Units[dynamics.getInputDimension()]; myOutputValues = new float[transform.length]; myValuesSet = false; setDynamics(dynamics); myScalingTermination = null; } //copies dynamics for to each dimension private synchronized void setDynamics(int dimension) { LinearSystem[] newDynamics = new LinearSystem[dimension]; for (int i = 0; i < newDynamics.length; i++) { try { newDynamics[i] = (LinearSystem) myDynamicsTemplate.clone(); //maintain state if there is state if (myDynamics != null && myDynamics[i] != null) { newDynamics[i].setState(myDynamics[i].getState()); } } catch (CloneNotSupportedException e) { throw new Error("The clone() operation is not supported by the given dynamics object"); } } myDynamics = newDynamics; //zero corresponding initial state if necessary if (myInitialState == null || myInitialState[0].length != newDynamics[0].getState().length) { initInitialState(); } } /** * @param bias Intrinsic bias that is added to inputs to this termination */ public void setStaticBias(float[] bias) { if (bias.length != myTransform.length) { throw new IllegalArgumentException("Bias must have length " + myTransform.length); } myStaticBias = bias; } /** * @return Static bias vector (a copy) */ public float[] getStaticBias() { float[] result = new float[myStaticBias.length]; System.arraycopy(myStaticBias, 0, result, 0, result.length); return result; } /** * @param values Only RealOutput is accepted. * * @see ca.nengo.model.Termination#setValues(ca.nengo.model.InstantaneousOutput) */ public void setValues(InstantaneousOutput values) throws SimulationException { if (values.getDimension() != getDimensions()) { throw new SimulationException("Dimension of input (" + values.getDimension() + ") does not equal dimension of this Termination (" + getDimensions() + ")"); } if ( !(values instanceof RealOutput) ) { throw new SimulationException("Only real-valued input is accepted at a DecodedTermination"); } RealOutput ro = (RealOutput) values; myInputValues = new RealOutputImpl(MU.sum(ro.getValues(), myStaticBias), ro.getUnits(), ro.getTime()); if (!myValuesSet) { myValuesSet = true; } } /** * @param startTime Simulation time at which running is to start * @param endTime Simulation time at which running is to end */ public void run(float startTime, float endTime) throws SimulationException { if (myDynamics == null) { setDynamics(myOutputDimension); } if (!myValuesSet) { ourLogger.warn("Input values not set on termination " + myName + ". Assuming input of zero."); setValues(new RealOutputImpl(new float[getDimensions()], Units.UNK, 0.0f)); } float[][] transform = getTransform(); if (myScalingTermination != null) { float scale = myScalingTermination.getOutput()[0]; transform = MU.prod(transform, scale); } float[] dynamicsInputs = MU.prod(transform, myInputValues.getValues()); float[] result = new float[dynamicsInputs.length]; for (int i = 0; i < myDynamics.length; i++) { float[] inVal = new float[]{dynamicsInputs[i]}; - float[] dxdt = myDynamics[i].f(startTime, inVal); - myDynamics[i].setState(MU.sum(myDynamics[i].getState(), MU.prod(dxdt, endTime-startTime))); - result[i] = myDynamics[i].g(endTime, inVal)[0]; + if(myTau <= endTime-startTime) { + TimeSeries inSeries = new TimeSeriesImpl(new float[]{startTime, endTime}, new float[][]{inVal, inVal}, myNullUnits); + TimeSeries outSeries = myIntegrator.integrate(myDynamics[i], inSeries); + result[i] = outSeries.getValues()[outSeries.getValues().length-1][0]; + } + else { + //save the overhead on the integration, and just do it all in one step + float[] dxdt = myDynamics[i].f(startTime, inVal); + myDynamics[i].setState(MU.sum(myDynamics[i].getState(), MU.prod(dxdt, endTime-startTime))); + result[i] = myDynamics[i].g(endTime, inVal)[0]; + } } myTime = endTime; myOutputValues = result; } /** * This method should be called after run(...). * * @return Output of dynamical system -- of interest at end of run(...) */ public float[] getOutput() { return myOutputValues; } /** * @return Latest input to Termination (pre transform and dynamics) */ public RealOutput getInput() { return myInputValues; } /** * @see ca.nengo.model.Termination#getName() */ public String getName() { return myName; } /** * @see ca.nengo.model.Termination#getDimensions() */ public int getDimensions() { return myTransform[0].length; } /** * @see ca.nengo.model.Resettable#reset(boolean) */ public void reset(boolean randomize) { resetInitialState(); myInputValues = new RealOutputImpl(new float[getDimensions()], Units.UNK, 0); myValuesSet = false; } private void resetInitialState() { for (int i = 0; myDynamics != null && i < myDynamics.length; i++) { float[] state = myInitialState != null ? myInitialState[i] : new float[myDynamics[i].getState().length]; myDynamics[i].setState(state); } } /** * @return Initial states of dynamics (one row per output dimension) */ public float[][] getInitialState() { if (myInitialState == null) { initInitialState(); } return MU.clone(myInitialState); } /** * @param state Initial state of dynamics (dimension of termination output X dimension of dynamics state) */ public void setInitialState(float[][] state) { if (state.length != myDynamics.length) { throw new IllegalArgumentException("Must give one state vector for each output dimension"); } if (!MU.isMatrix(state) || state[0].length != myDynamicsTemplate.getState().length) { throw new IllegalArgumentException("Each state vector must be length " + myDynamicsTemplate.getState().length); } myInitialState = state; resetInitialState(); } private void initInitialState() { myInitialState = new float[myOutputDimension][]; for (int i = 0; i < myOutputDimension; i++) { myInitialState[i] = new float[myDynamics[i].getState().length]; } } /** * @return The matrix that maps input (which has the dimension of this Termination) * onto the state space represented by the NEFEnsemble to which the Termination belongs */ public float[][] getTransform() { return MU.clone(myTransform); } /** * @param transform New transform * @throws StructuralException If the transform is not a matrix or has the wrong size */ public void setTransform(float[][] transform) throws StructuralException { if ( !MU.isMatrix(transform) ) { throw new StructuralException("Given transform is not a matrix"); } if (transform.length != myOutputDimension) { throw new StructuralException("This transform must have " + myOutputDimension + " rows"); } myTransform = transform; if (myStaticBias == null) { myStaticBias = new float[transform[0].length]; } else { float[] newStaticBias = new float[transform[0].length]; System.arraycopy(myStaticBias, 0, newStaticBias, 0, Math.min(myStaticBias.length, newStaticBias.length)); myStaticBias = newStaticBias; } if (myDynamics != null && myDynamics.length != transform.length) { setDynamics(transform.length); } } /** * @param t Termination to use for scaling? */ public void setScaling(DecodedTermination t) { myScalingTermination = t; } /** * @return Termination used for scaling? */ public DecodedTermination getScaling() { return myScalingTermination; } /** * @return The dynamics that govern each dimension of this Termination. Changing the properties * of the return value will change dynamics of all dimensions, effective next run time. */ public LinearSystem getDynamics() { myDynamics = null; //caller may change properties so we'll have to re-clone at next run return myDynamicsTemplate; } /** * @param dynamics New dynamics for each dimension of this Termination (effective immediately). * This method uses a clone of the given dynamics. */ public void setDynamics(LinearSystem dynamics) { try { myDynamicsTemplate = (LinearSystem) dynamics.clone(); setDynamics(myOutputDimension); //PSC time constant can be changed online if dynamics are LTI in controllable-canonical form myTauMutable = (dynamics instanceof LTISystem && CanonicalModel.isControllableCanonical((LTISystem) dynamics)); //find PSC time constant (slowest dynamic mode) if applicable if (dynamics instanceof LTISystem) { myTau = CanonicalModel.getDominantTimeConstant((LTISystem) dynamics); } else { myTau = 0; } } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } /** * @return Slowest time constant of dynamics, if dynamics are LTI, otherwise 0 */ public float getTau() { return myTau; } /** * @param tau New time constant to replace current slowest time constant of dynamics * @throws StructuralException if the dynamics of this Termination are not LTI in controllable * canonical form */ public void setTau(float tau) throws StructuralException { if (!myTauMutable) { throw new StructuralException("This Termination has immutable dynamics " + "(must be LTI in controllable-canonical form to change time constant online"); } setDynamics(CanonicalModel.changeTimeConstant((LTISystem) myDynamicsTemplate, tau)); } /** * @see ca.nengo.model.Termination#getModulatory() */ public boolean getModulatory() { return myModulatory; } /** * @see ca.nengo.model.Termination#setModulatory(boolean) */ public void setModulatory(boolean modulatory) { myModulatory = modulatory; } /** * @see ca.nengo.model.Probeable#getHistory(java.lang.String) */ public TimeSeries getHistory(String stateName) throws SimulationException { if (stateName.equals(OUTPUT)) { return new TimeSeriesImpl(new float[]{myTime}, new float[][]{myOutputValues}, Units.uniform(Units.UNK, myOutputValues.length)); } else { throw new SimulationException("The state '" + stateName + "' is unknown"); } } /** * @see ca.nengo.model.Probeable#listStates() */ public Properties listStates() { Properties p = new Properties(); p.setProperty(OUTPUT, "Output of the termination, after static transform and dynamics"); return p; } /** * @see ca.nengo.model.Termination#getNode() */ public Node getNode() { return myNode; } protected void setNode(Node node) { myNode = node; if(myIntegrator instanceof SynapticIntegrator) ((SynapticIntegrator)myIntegrator).setNode(node); } @Override public DecodedTermination clone() throws CloneNotSupportedException { return this.clone(myNode); } public DecodedTermination clone(Node node) throws CloneNotSupportedException { try { DecodedTermination result = (DecodedTermination)super.clone(); result.setTransform(MU.clone(myTransform)); result.setDynamics((LinearSystem) myDynamicsTemplate.clone()); result.myIntegrator = myIntegrator.clone(); if (myInputValues != null) { result.myInputValues = (RealOutput) myInputValues.clone(); } if (myOutputValues != null) { result.myOutputValues = myOutputValues.clone(); } result.myScalingTermination = myScalingTermination; //refer to same copy result.myStaticBias = myStaticBias.clone(); result.setNode(node); return result; } catch (StructuralException e) { throw new CloneNotSupportedException("Error cloning DecodedTermination: " + e.getMessage()); } } }
true
true
public void run(float startTime, float endTime) throws SimulationException { if (myDynamics == null) { setDynamics(myOutputDimension); } if (!myValuesSet) { ourLogger.warn("Input values not set on termination " + myName + ". Assuming input of zero."); setValues(new RealOutputImpl(new float[getDimensions()], Units.UNK, 0.0f)); } float[][] transform = getTransform(); if (myScalingTermination != null) { float scale = myScalingTermination.getOutput()[0]; transform = MU.prod(transform, scale); } float[] dynamicsInputs = MU.prod(transform, myInputValues.getValues()); float[] result = new float[dynamicsInputs.length]; for (int i = 0; i < myDynamics.length; i++) { float[] inVal = new float[]{dynamicsInputs[i]}; float[] dxdt = myDynamics[i].f(startTime, inVal); myDynamics[i].setState(MU.sum(myDynamics[i].getState(), MU.prod(dxdt, endTime-startTime))); result[i] = myDynamics[i].g(endTime, inVal)[0]; } myTime = endTime; myOutputValues = result; }
public void run(float startTime, float endTime) throws SimulationException { if (myDynamics == null) { setDynamics(myOutputDimension); } if (!myValuesSet) { ourLogger.warn("Input values not set on termination " + myName + ". Assuming input of zero."); setValues(new RealOutputImpl(new float[getDimensions()], Units.UNK, 0.0f)); } float[][] transform = getTransform(); if (myScalingTermination != null) { float scale = myScalingTermination.getOutput()[0]; transform = MU.prod(transform, scale); } float[] dynamicsInputs = MU.prod(transform, myInputValues.getValues()); float[] result = new float[dynamicsInputs.length]; for (int i = 0; i < myDynamics.length; i++) { float[] inVal = new float[]{dynamicsInputs[i]}; if(myTau <= endTime-startTime) { TimeSeries inSeries = new TimeSeriesImpl(new float[]{startTime, endTime}, new float[][]{inVal, inVal}, myNullUnits); TimeSeries outSeries = myIntegrator.integrate(myDynamics[i], inSeries); result[i] = outSeries.getValues()[outSeries.getValues().length-1][0]; } else { //save the overhead on the integration, and just do it all in one step float[] dxdt = myDynamics[i].f(startTime, inVal); myDynamics[i].setState(MU.sum(myDynamics[i].getState(), MU.prod(dxdt, endTime-startTime))); result[i] = myDynamics[i].g(endTime, inVal)[0]; } } myTime = endTime; myOutputValues = result; }
diff --git a/src/main/java/it/antreem/birretta/service/util/SessionFilter.java b/src/main/java/it/antreem/birretta/service/util/SessionFilter.java index dc94ce8..7b490d5 100644 --- a/src/main/java/it/antreem/birretta/service/util/SessionFilter.java +++ b/src/main/java/it/antreem/birretta/service/util/SessionFilter.java @@ -1,255 +1,254 @@ package it.antreem.birretta.service.util; import it.antreem.birretta.service.dao.DaoFactory; import it.antreem.birretta.service.dto.ResultDTO; import it.antreem.birretta.service.model.Session; import it.antreem.birretta.service.model.json.Status; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.jackson.map.ObjectMapper; /** * Filtro per il controllo della sessione attiva e, per ora, unica modalit&agrave; * di autorizzazione per gli utenti. * * @author alessio */ public class SessionFilter implements Filter { private static final boolean log_debug = true; private static final Log log = LogFactory.getLog(SessionFilter.class); // The filter configuration object we are associated with. If // this value is null, this filter instance is not currently // configured. private FilterConfig filterConfig = null; public SessionFilter() { } /** * Controllo che sia attiva una sessione. * Nell'header: 'Cookie: username=<i>username</i>; sid=<i>sid</i>' * * * @param request * @return */ private boolean checkSession(HttpServletRequest request) { // Per le operazioni di login e register non interessa la sessione if (request.getRequestURI().endsWith("/rest/bserv/generaToken") || request.getRequestURI().endsWith("/rest/bserv/saveUser")){ return true; } // Altrimenti per tutto il resto deve esserci una sessione attiva String username=null; String sid=null; log.info(request.getRequestURI()+" query "+request.getQueryString()); //metodi GET parsing if(!(request.getHeader("btUsername")!=null) //vecchia modalità && request.getQueryString()!=null &&request.getQueryString().contains("&")) { log.info("controllo autenticazione metodo GET per "+request.getQueryString()); String[] requestField=request.getQueryString().split("&"); for (String param:requestField) { String name=param.split("=")[0]; - String value=param.split("=")[1]; - if(name.equals("btUsername")) + if(name.equals("btUsername") && param.split("=").length>1) { - username=value; - }else if(name.equals("btSid")) + username=param.split("=")[1]; + }else if(name.equals("btSid")&& param.split("=").length>1) { - sid=value; + sid=param.split("=")[1]; } } } else //metodi post { log.info("controllo autenticazione metodo post/get per "+request.getRequestURI()); username = request.getHeader("btUsername"); sid = request.getHeader("btSid"); } log.info("check: "+username + " - "+ sid); if (username == null || sid == null){ // return false; return true; } Session s = DaoFactory.getInstance().getSessionDao().findSessionByUsername(username); if (s == null || !s.getSid().equals(sid)){ // return false; return true; } else return true; } /** * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param chain The filter chain we are processing * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (log_debug) { log.debug("SessionFilter:doFilter()"); } doBeforeProcessing(request, response); boolean authOk =checkSession((HttpServletRequest) request); if (!authOk) { HttpServletResponse res = (HttpServletResponse) response; res.setContentType("application/json"); PrintWriter pw = res.getWriter(); pw.println("{ \"error\" : { \"code\": \"HTTP401\", \"title\": \"Http 401 Unauthorized\", \"desc\" : \"No active session\", \"actionType\": null } }"); return; } try { chain.doFilter(request, response); } catch (Throwable t) { log.error("Error in doFilter: " + t.getLocalizedMessage(), t); HttpServletResponse res = (HttpServletResponse) response; res.setContentType("application/json"); PrintWriter pw = res.getWriter(); ObjectMapper mapper = new ObjectMapper(); ResultDTO errorResult = new ResultDTO(); Status status = new Status(); status.setCode(999); status.setMsg("Generic server-side error"); status.setSuccess(false); it.antreem.birretta.service.model.json.Response errorResponse = new it.antreem.birretta.service.model.json.Response(status, null, null); errorResult.setResponse(errorResponse); mapper.writeValue(pw, errorResult); res.addHeader("Access-Control-Allow-Headers", "origin,x-requested-with,content-type"); res.addHeader("Access-Control-Allow-Origin", "*"); // pw.println("{ \"error\" : { \"code\": 999, \"title\": \"Generic Error\", \"desc\" : \"Generic server-side error.\", \"actionType\": null } }"); return; } //cross domain.. // ((HttpServletResponse) response).addHeader("Access-Control-Allow-Origin", "*"); // ((HttpServletResponse) response).addHeader("Access-Control-Allow-Headers", "origin,x-requested-with,content-type"); // log.info("send response: "+((HttpServletResponse) response).toString()); doAfterProcessing(request, response); } /** * Return the filter configuration object for this filter. */ public FilterConfig getFilterConfig() { return (this.filterConfig); } /** * Set the filter configuration object for this filter. * * @param filterConfig The filter configuration object */ public void setFilterConfig(FilterConfig filterConfig) { this.filterConfig = filterConfig; } /** * Destroy method for this filter */ @Override public void destroy() { } /** * Init method for this filter */ @Override public void init(FilterConfig filterConfig) { this.filterConfig = filterConfig; if (filterConfig != null) { if (log_debug) { log.debug("SessionFilter:Initializing filter"); } } } /** * Return a String representation of this object. */ @Override public String toString() { if (filterConfig == null) { return ("SessionFilter()"); } StringBuilder sb = new StringBuilder("SessionFilter("); sb.append(filterConfig); sb.append(")"); return (sb.toString()); } private void doBeforeProcessing(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (log_debug) { log.debug("SessionFilter:DoBeforeProcessing"); } // Write code here to process the request and/or response before // the rest of the filter chain is invoked. // For example, a logging filter might log items on the request object, // such as the parameters. /* * for (Enumeration en = request.getParameterNames(); * en.hasMoreElements(); ) { String name = (String)en.nextElement(); * String values[] = request.getParameterValues(name); int n = * values.length; StringBuffer buf = new StringBuffer(); * buf.append(name); buf.append("="); for(int i=0; i < n; i++) { * buf.append(values[i]); if (i < n-1) buf.append(","); } * log(buf.toString()); } */ } private void doAfterProcessing(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (log_debug) { log.debug("SessionFilter:DoAfterProcessing"); } // Write code here to process the request and/or response after // the rest of the filter chain is invoked. // For example, a logging filter might log the attributes on the // request object after the request has been processed. /* * for (Enumeration en = request.getAttributeNames(); * en.hasMoreElements(); ) { String name = (String)en.nextElement(); * Object value = request.getAttribute(name); log("attribute: " + name + * "=" + value.toString()); * * } */ // For example, a filter might append something to the response. /* * PrintWriter respOut = new PrintWriter(response.getWriter()); * respOut.println("<P><B>This has been appended by an intrusive * filter.</B>"); */ } }
false
true
private boolean checkSession(HttpServletRequest request) { // Per le operazioni di login e register non interessa la sessione if (request.getRequestURI().endsWith("/rest/bserv/generaToken") || request.getRequestURI().endsWith("/rest/bserv/saveUser")){ return true; } // Altrimenti per tutto il resto deve esserci una sessione attiva String username=null; String sid=null; log.info(request.getRequestURI()+" query "+request.getQueryString()); //metodi GET parsing if(!(request.getHeader("btUsername")!=null) //vecchia modalità && request.getQueryString()!=null &&request.getQueryString().contains("&")) { log.info("controllo autenticazione metodo GET per "+request.getQueryString()); String[] requestField=request.getQueryString().split("&"); for (String param:requestField) { String name=param.split("=")[0]; String value=param.split("=")[1]; if(name.equals("btUsername")) { username=value; }else if(name.equals("btSid")) { sid=value; } } } else //metodi post { log.info("controllo autenticazione metodo post/get per "+request.getRequestURI()); username = request.getHeader("btUsername"); sid = request.getHeader("btSid"); } log.info("check: "+username + " - "+ sid); if (username == null || sid == null){ // return false; return true; } Session s = DaoFactory.getInstance().getSessionDao().findSessionByUsername(username); if (s == null || !s.getSid().equals(sid)){ // return false; return true; } else return true; }
private boolean checkSession(HttpServletRequest request) { // Per le operazioni di login e register non interessa la sessione if (request.getRequestURI().endsWith("/rest/bserv/generaToken") || request.getRequestURI().endsWith("/rest/bserv/saveUser")){ return true; } // Altrimenti per tutto il resto deve esserci una sessione attiva String username=null; String sid=null; log.info(request.getRequestURI()+" query "+request.getQueryString()); //metodi GET parsing if(!(request.getHeader("btUsername")!=null) //vecchia modalità && request.getQueryString()!=null &&request.getQueryString().contains("&")) { log.info("controllo autenticazione metodo GET per "+request.getQueryString()); String[] requestField=request.getQueryString().split("&"); for (String param:requestField) { String name=param.split("=")[0]; if(name.equals("btUsername") && param.split("=").length>1) { username=param.split("=")[1]; }else if(name.equals("btSid")&& param.split("=").length>1) { sid=param.split("=")[1]; } } } else //metodi post { log.info("controllo autenticazione metodo post/get per "+request.getRequestURI()); username = request.getHeader("btUsername"); sid = request.getHeader("btSid"); } log.info("check: "+username + " - "+ sid); if (username == null || sid == null){ // return false; return true; } Session s = DaoFactory.getInstance().getSessionDao().findSessionByUsername(username); if (s == null || !s.getSid().equals(sid)){ // return false; return true; } else return true; }
diff --git a/sonar-batch/src/main/java/org/sonar/batch/index/ViolationPersister.java b/sonar-batch/src/main/java/org/sonar/batch/index/ViolationPersister.java index 2334c0f871..0b15823d5c 100644 --- a/sonar-batch/src/main/java/org/sonar/batch/index/ViolationPersister.java +++ b/sonar-batch/src/main/java/org/sonar/batch/index/ViolationPersister.java @@ -1,88 +1,88 @@ /* * Sonar, open source software quality management tool. * Copyright (C) 2008-2011 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.batch.index; import org.sonar.api.database.DatabaseSession; import org.sonar.api.database.model.RuleFailureModel; import org.sonar.api.database.model.Snapshot; import org.sonar.api.resources.Project; import org.sonar.api.rules.Rule; import org.sonar.api.rules.RuleFinder; import org.sonar.api.rules.Violation; public final class ViolationPersister { private DatabaseSession session; private ResourcePersister resourcePersister; private RuleFinder ruleFinder; public ViolationPersister(DatabaseSession session, ResourcePersister resourcePersister, RuleFinder ruleFinder) { this.session = session; this.resourcePersister = resourcePersister; this.ruleFinder = ruleFinder; } void saveViolation(Project project, Violation violation) { saveViolation(project, violation, null, null); } public void saveViolation(Project project, Violation violation, RuleFailureModel pastViolation, String checksum) { Snapshot snapshot = resourcePersister.saveResource(project, violation.getResource()); RuleFailureModel model = createModel(violation); if (pastViolation!=null) { model.setCreatedAt(pastViolation.getCreatedAt()); model.setPermanentId(pastViolation.getPermanentId()); model.setSwitchedOff(pastViolation.isSwitchedOff()); } else { // avoid plugins setting date model.setCreatedAt(snapshot.getCreatedAt()); } model.setSnapshotId(snapshot.getId()); model.setChecksum(checksum); - session.save(model); + session.saveWithoutFlush(model); if (model.getPermanentId()==null) { model.setPermanentId(model.getId()); - session.save(model); + session.saveWithoutFlush(model); } // the following fields can have been changed violation.setMessage(model.getMessage());// the message can be changed in the class RuleFailure (truncate + trim) violation.setCreatedAt(model.getCreatedAt()); violation.setSwitchedOff(model.isSwitchedOff()); } public void commit() { session.commit(); } private RuleFailureModel createModel(Violation violation) { RuleFailureModel model = new RuleFailureModel(); Rule rule = ruleFinder.findByKey(violation.getRule().getRepositoryKey(), violation.getRule().getKey()); model.setRuleId(rule.getId()); model.setPriority(violation.getSeverity()); model.setLine(violation.getLineId()); model.setMessage(violation.getMessage()); model.setCost(violation.getCost()); return model; } }
false
true
public void saveViolation(Project project, Violation violation, RuleFailureModel pastViolation, String checksum) { Snapshot snapshot = resourcePersister.saveResource(project, violation.getResource()); RuleFailureModel model = createModel(violation); if (pastViolation!=null) { model.setCreatedAt(pastViolation.getCreatedAt()); model.setPermanentId(pastViolation.getPermanentId()); model.setSwitchedOff(pastViolation.isSwitchedOff()); } else { // avoid plugins setting date model.setCreatedAt(snapshot.getCreatedAt()); } model.setSnapshotId(snapshot.getId()); model.setChecksum(checksum); session.save(model); if (model.getPermanentId()==null) { model.setPermanentId(model.getId()); session.save(model); } // the following fields can have been changed violation.setMessage(model.getMessage());// the message can be changed in the class RuleFailure (truncate + trim) violation.setCreatedAt(model.getCreatedAt()); violation.setSwitchedOff(model.isSwitchedOff()); }
public void saveViolation(Project project, Violation violation, RuleFailureModel pastViolation, String checksum) { Snapshot snapshot = resourcePersister.saveResource(project, violation.getResource()); RuleFailureModel model = createModel(violation); if (pastViolation!=null) { model.setCreatedAt(pastViolation.getCreatedAt()); model.setPermanentId(pastViolation.getPermanentId()); model.setSwitchedOff(pastViolation.isSwitchedOff()); } else { // avoid plugins setting date model.setCreatedAt(snapshot.getCreatedAt()); } model.setSnapshotId(snapshot.getId()); model.setChecksum(checksum); session.saveWithoutFlush(model); if (model.getPermanentId()==null) { model.setPermanentId(model.getId()); session.saveWithoutFlush(model); } // the following fields can have been changed violation.setMessage(model.getMessage());// the message can be changed in the class RuleFailure (truncate + trim) violation.setCreatedAt(model.getCreatedAt()); violation.setSwitchedOff(model.isSwitchedOff()); }
diff --git a/utils/src/main/java/org/apache/mahout/utils/vectors/lucene/Driver.java b/utils/src/main/java/org/apache/mahout/utils/vectors/lucene/Driver.java index dd5c8dae..92c3f838 100644 --- a/utils/src/main/java/org/apache/mahout/utils/vectors/lucene/Driver.java +++ b/utils/src/main/java/org/apache/mahout/utils/vectors/lucene/Driver.java @@ -1,260 +1,260 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.mahout.utils.vectors.lucene; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import org.apache.commons.cli2.CommandLine; import org.apache.commons.cli2.Group; import org.apache.commons.cli2.Option; import org.apache.commons.cli2.OptionException; import org.apache.commons.cli2.builder.ArgumentBuilder; import org.apache.commons.cli2.builder.DefaultOptionBuilder; import org.apache.commons.cli2.builder.GroupBuilder; import org.apache.commons.cli2.commandline.Parser; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.lucene.index.IndexReader; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.mahout.common.CommandLineUtil; import org.apache.mahout.math.VectorWritable; import org.apache.mahout.utils.vectors.TermInfo; import org.apache.mahout.utils.vectors.io.JWriterTermInfoWriter; import org.apache.mahout.utils.vectors.io.JWriterVectorWriter; import org.apache.mahout.utils.vectors.io.SequenceFileVectorWriter; import org.apache.mahout.utils.vectors.io.VectorWriter; import org.apache.mahout.vectorizer.TF; import org.apache.mahout.vectorizer.TFIDF; import org.apache.mahout.vectorizer.Weight; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class Driver { private static final Logger log = LoggerFactory.getLogger(Driver.class); private Driver() { } public static void main(String[] args) throws IOException { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option inputOpt = obuilder.withLongName("dir").withRequired(true).withArgument( abuilder.withName("dir").withMinimum(1).withMaximum(1).create()) .withDescription("The Lucene directory").withShortName("d").create(); Option outputOpt = obuilder.withLongName("output").withRequired(true).withArgument( abuilder.withName("output").withMinimum(1).withMaximum(1).create()).withDescription("The output file") .withShortName("o").create(); Option fieldOpt = obuilder.withLongName("field").withRequired(true).withArgument( abuilder.withName("field").withMinimum(1).withMaximum(1).create()).withDescription( "The field in the index").withShortName("f").create(); Option idFieldOpt = obuilder.withLongName("idField").withRequired(false).withArgument( abuilder.withName("idField").withMinimum(1).withMaximum(1).create()).withDescription( "The field in the index containing the index. If null, then the Lucene internal doc " + "id is used which is prone to error if the underlying index changes").withShortName("i").create(); Option dictOutOpt = obuilder.withLongName("dictOut").withRequired(true).withArgument( abuilder.withName("dictOut").withMinimum(1).withMaximum(1).create()).withDescription( "The output of the dictionary").withShortName("t").create(); Option weightOpt = obuilder.withLongName("weight").withRequired(false).withArgument( abuilder.withName("weight").withMinimum(1).withMaximum(1).create()).withDescription( "The kind of weight to use. Currently TF or TFIDF").withShortName("w").create(); Option delimiterOpt = obuilder.withLongName("delimiter").withRequired(false).withArgument( abuilder.withName("delimiter").withMinimum(1).withMaximum(1).create()).withDescription( - "The delimiter for outputing the dictionary").withShortName("l").create(); + "The delimiter for outputting the dictionary").withShortName("l").create(); Option powerOpt = obuilder.withLongName("norm").withRequired(false).withArgument( abuilder.withName("norm").withMinimum(1).withMaximum(1).create()).withDescription( "The norm to use, expressed as either a double or \"INF\" if you want to use the Infinite norm. " + "Must be greater or equal to 0. The default is not to normalize").withShortName("n").create(); Option maxOpt = obuilder.withLongName("max").withRequired(false).withArgument( abuilder.withName("max").withMinimum(1).withMaximum(1).create()).withDescription( "The maximum number of vectors to output. If not specified, then it will loop over all docs") .withShortName("m").create(); Option outWriterOpt = obuilder.withLongName("outputWriter").withRequired(false).withArgument( abuilder.withName("outputWriter").withMinimum(1).withMaximum(1).create()).withDescription( "The VectorWriter to use, either seq " + "(SequenceFileVectorWriter - default) or file (Writes to a File using JSON format)") .withShortName("e").create(); Option minDFOpt = obuilder.withLongName("minDF").withRequired(false).withArgument( abuilder.withName("minDF").withMinimum(1).withMaximum(1).create()).withDescription( "The minimum document frequency. Default is 1").withShortName("md").create(); Option maxDFPercentOpt = obuilder.withLongName("maxDFPercent").withRequired(false).withArgument( abuilder.withName("maxDFPercent").withMinimum(1).withMaximum(1).create()).withDescription( "The max percentage of docs for the DF. Can be used to remove really high frequency terms." + " Expressed as an integer between 0 and 100. Default is 99.").withShortName("x").create(); Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h") .create(); Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(idFieldOpt).withOption( outputOpt).withOption(delimiterOpt).withOption(helpOpt).withOption(fieldOpt).withOption(maxOpt) .withOption(dictOutOpt).withOption(powerOpt).withOption(outWriterOpt).withOption(maxDFPercentOpt) .withOption(weightOpt).withOption(minDFOpt).create(); try { Parser parser = new Parser(); parser.setGroup(group); CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return; } // Springify all this if (cmdLine.hasOption(inputOpt)) { // Lucene case File file = new File(cmdLine.getValue(inputOpt).toString()); if (!file.isDirectory()) { throw new IllegalArgumentException("Lucene directory: " + file.getAbsolutePath() + " does not exist or is not a directory"); } long maxDocs = Long.MAX_VALUE; if (cmdLine.hasOption(maxOpt)) { maxDocs = Long.parseLong(cmdLine.getValue(maxOpt).toString()); } if (maxDocs < 0) { throw new IllegalArgumentException("maxDocs must be >= 0"); } Directory dir = FSDirectory.open(file); IndexReader reader = IndexReader.open(dir, true); Weight weight; if (cmdLine.hasOption(weightOpt)) { String wString = cmdLine.getValue(weightOpt).toString(); if ("tf".equalsIgnoreCase(wString)) { weight = new TF(); } else if ("tfidf".equalsIgnoreCase(wString)) { weight = new TFIDF(); } else { throw new OptionException(weightOpt); } } else { weight = new TFIDF(); } String field = cmdLine.getValue(fieldOpt).toString(); int minDf = 1; if (cmdLine.hasOption(minDFOpt)) { minDf = Integer.parseInt(cmdLine.getValue(minDFOpt).toString()); } int maxDFPercent = 99; if (cmdLine.hasOption(maxDFPercentOpt)) { maxDFPercent = Integer.parseInt(cmdLine.getValue(maxDFPercentOpt).toString()); } TermInfo termInfo = new CachedTermInfo(reader, field, minDf, maxDFPercent); VectorMapper mapper = new TFDFMapper(reader, weight, termInfo); double norm = LuceneIterable.NO_NORMALIZING; if (cmdLine.hasOption(powerOpt)) { String power = cmdLine.getValue(powerOpt).toString(); if ("INF".equals(power)) { norm = Double.POSITIVE_INFINITY; } else { norm = Double.parseDouble(power); } } String idField = null; if (cmdLine.hasOption(idFieldOpt)) { idField = cmdLine.getValue(idFieldOpt).toString(); } LuceneIterable iterable; if (norm == LuceneIterable.NO_NORMALIZING) { iterable = new LuceneIterable(reader, idField, field, mapper, LuceneIterable.NO_NORMALIZING); } else { iterable = new LuceneIterable(reader, idField, field, mapper, norm); } String outFile = cmdLine.getValue(outputOpt).toString(); log.info("Output File: {}", outFile); VectorWriter vectorWriter; if (cmdLine.hasOption(outWriterOpt)) { String outWriter = cmdLine.getValue(outWriterOpt).toString(); if ("file".equals(outWriter)) { BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); vectorWriter = new JWriterVectorWriter(writer); } else { vectorWriter = getSeqFileWriter(outFile); } } else { vectorWriter = getSeqFileWriter(outFile); } long numDocs = vectorWriter.write(iterable, maxDocs); vectorWriter.close(); log.info("Wrote: {} vectors", numDocs); String delimiter = cmdLine.hasOption(delimiterOpt) ? cmdLine.getValue(delimiterOpt).toString() : "\t"; File dictOutFile = new File(cmdLine.getValue(dictOutOpt).toString()); log.info("Dictionary Output file: {}", dictOutFile); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(dictOutFile), Charset.forName("UTF8"))); JWriterTermInfoWriter tiWriter = new JWriterTermInfoWriter(writer, delimiter, field); tiWriter.write(termInfo); tiWriter.close(); writer.close(); } } catch (OptionException e) { log.error("Exception", e); CommandLineUtil.printHelp(group); } } private static VectorWriter getSeqFileWriter(String outFile) throws IOException { Path path = new Path(outFile); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); // TODO: Make this parameter driven SequenceFile.Writer seqWriter = SequenceFile.createWriter(fs, conf, path, LongWritable.class, VectorWritable.class); return new SequenceFileVectorWriter(seqWriter); } }
true
true
public static void main(String[] args) throws IOException { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option inputOpt = obuilder.withLongName("dir").withRequired(true).withArgument( abuilder.withName("dir").withMinimum(1).withMaximum(1).create()) .withDescription("The Lucene directory").withShortName("d").create(); Option outputOpt = obuilder.withLongName("output").withRequired(true).withArgument( abuilder.withName("output").withMinimum(1).withMaximum(1).create()).withDescription("The output file") .withShortName("o").create(); Option fieldOpt = obuilder.withLongName("field").withRequired(true).withArgument( abuilder.withName("field").withMinimum(1).withMaximum(1).create()).withDescription( "The field in the index").withShortName("f").create(); Option idFieldOpt = obuilder.withLongName("idField").withRequired(false).withArgument( abuilder.withName("idField").withMinimum(1).withMaximum(1).create()).withDescription( "The field in the index containing the index. If null, then the Lucene internal doc " + "id is used which is prone to error if the underlying index changes").withShortName("i").create(); Option dictOutOpt = obuilder.withLongName("dictOut").withRequired(true).withArgument( abuilder.withName("dictOut").withMinimum(1).withMaximum(1).create()).withDescription( "The output of the dictionary").withShortName("t").create(); Option weightOpt = obuilder.withLongName("weight").withRequired(false).withArgument( abuilder.withName("weight").withMinimum(1).withMaximum(1).create()).withDescription( "The kind of weight to use. Currently TF or TFIDF").withShortName("w").create(); Option delimiterOpt = obuilder.withLongName("delimiter").withRequired(false).withArgument( abuilder.withName("delimiter").withMinimum(1).withMaximum(1).create()).withDescription( "The delimiter for outputing the dictionary").withShortName("l").create(); Option powerOpt = obuilder.withLongName("norm").withRequired(false).withArgument( abuilder.withName("norm").withMinimum(1).withMaximum(1).create()).withDescription( "The norm to use, expressed as either a double or \"INF\" if you want to use the Infinite norm. " + "Must be greater or equal to 0. The default is not to normalize").withShortName("n").create(); Option maxOpt = obuilder.withLongName("max").withRequired(false).withArgument( abuilder.withName("max").withMinimum(1).withMaximum(1).create()).withDescription( "The maximum number of vectors to output. If not specified, then it will loop over all docs") .withShortName("m").create(); Option outWriterOpt = obuilder.withLongName("outputWriter").withRequired(false).withArgument( abuilder.withName("outputWriter").withMinimum(1).withMaximum(1).create()).withDescription( "The VectorWriter to use, either seq " + "(SequenceFileVectorWriter - default) or file (Writes to a File using JSON format)") .withShortName("e").create(); Option minDFOpt = obuilder.withLongName("minDF").withRequired(false).withArgument( abuilder.withName("minDF").withMinimum(1).withMaximum(1).create()).withDescription( "The minimum document frequency. Default is 1").withShortName("md").create(); Option maxDFPercentOpt = obuilder.withLongName("maxDFPercent").withRequired(false).withArgument( abuilder.withName("maxDFPercent").withMinimum(1).withMaximum(1).create()).withDescription( "The max percentage of docs for the DF. Can be used to remove really high frequency terms." + " Expressed as an integer between 0 and 100. Default is 99.").withShortName("x").create(); Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h") .create(); Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(idFieldOpt).withOption( outputOpt).withOption(delimiterOpt).withOption(helpOpt).withOption(fieldOpt).withOption(maxOpt) .withOption(dictOutOpt).withOption(powerOpt).withOption(outWriterOpt).withOption(maxDFPercentOpt) .withOption(weightOpt).withOption(minDFOpt).create(); try { Parser parser = new Parser(); parser.setGroup(group); CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return; } // Springify all this if (cmdLine.hasOption(inputOpt)) { // Lucene case File file = new File(cmdLine.getValue(inputOpt).toString()); if (!file.isDirectory()) { throw new IllegalArgumentException("Lucene directory: " + file.getAbsolutePath() + " does not exist or is not a directory"); } long maxDocs = Long.MAX_VALUE; if (cmdLine.hasOption(maxOpt)) { maxDocs = Long.parseLong(cmdLine.getValue(maxOpt).toString()); } if (maxDocs < 0) { throw new IllegalArgumentException("maxDocs must be >= 0"); } Directory dir = FSDirectory.open(file); IndexReader reader = IndexReader.open(dir, true); Weight weight; if (cmdLine.hasOption(weightOpt)) { String wString = cmdLine.getValue(weightOpt).toString(); if ("tf".equalsIgnoreCase(wString)) { weight = new TF(); } else if ("tfidf".equalsIgnoreCase(wString)) { weight = new TFIDF(); } else { throw new OptionException(weightOpt); } } else { weight = new TFIDF(); } String field = cmdLine.getValue(fieldOpt).toString(); int minDf = 1; if (cmdLine.hasOption(minDFOpt)) { minDf = Integer.parseInt(cmdLine.getValue(minDFOpt).toString()); } int maxDFPercent = 99; if (cmdLine.hasOption(maxDFPercentOpt)) { maxDFPercent = Integer.parseInt(cmdLine.getValue(maxDFPercentOpt).toString()); } TermInfo termInfo = new CachedTermInfo(reader, field, minDf, maxDFPercent); VectorMapper mapper = new TFDFMapper(reader, weight, termInfo); double norm = LuceneIterable.NO_NORMALIZING; if (cmdLine.hasOption(powerOpt)) { String power = cmdLine.getValue(powerOpt).toString(); if ("INF".equals(power)) { norm = Double.POSITIVE_INFINITY; } else { norm = Double.parseDouble(power); } } String idField = null; if (cmdLine.hasOption(idFieldOpt)) { idField = cmdLine.getValue(idFieldOpt).toString(); } LuceneIterable iterable; if (norm == LuceneIterable.NO_NORMALIZING) { iterable = new LuceneIterable(reader, idField, field, mapper, LuceneIterable.NO_NORMALIZING); } else { iterable = new LuceneIterable(reader, idField, field, mapper, norm); } String outFile = cmdLine.getValue(outputOpt).toString(); log.info("Output File: {}", outFile); VectorWriter vectorWriter; if (cmdLine.hasOption(outWriterOpt)) { String outWriter = cmdLine.getValue(outWriterOpt).toString(); if ("file".equals(outWriter)) { BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); vectorWriter = new JWriterVectorWriter(writer); } else { vectorWriter = getSeqFileWriter(outFile); } } else { vectorWriter = getSeqFileWriter(outFile); } long numDocs = vectorWriter.write(iterable, maxDocs); vectorWriter.close(); log.info("Wrote: {} vectors", numDocs); String delimiter = cmdLine.hasOption(delimiterOpt) ? cmdLine.getValue(delimiterOpt).toString() : "\t"; File dictOutFile = new File(cmdLine.getValue(dictOutOpt).toString()); log.info("Dictionary Output file: {}", dictOutFile); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(dictOutFile), Charset.forName("UTF8"))); JWriterTermInfoWriter tiWriter = new JWriterTermInfoWriter(writer, delimiter, field); tiWriter.write(termInfo); tiWriter.close(); writer.close(); } } catch (OptionException e) { log.error("Exception", e); CommandLineUtil.printHelp(group); } }
public static void main(String[] args) throws IOException { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option inputOpt = obuilder.withLongName("dir").withRequired(true).withArgument( abuilder.withName("dir").withMinimum(1).withMaximum(1).create()) .withDescription("The Lucene directory").withShortName("d").create(); Option outputOpt = obuilder.withLongName("output").withRequired(true).withArgument( abuilder.withName("output").withMinimum(1).withMaximum(1).create()).withDescription("The output file") .withShortName("o").create(); Option fieldOpt = obuilder.withLongName("field").withRequired(true).withArgument( abuilder.withName("field").withMinimum(1).withMaximum(1).create()).withDescription( "The field in the index").withShortName("f").create(); Option idFieldOpt = obuilder.withLongName("idField").withRequired(false).withArgument( abuilder.withName("idField").withMinimum(1).withMaximum(1).create()).withDescription( "The field in the index containing the index. If null, then the Lucene internal doc " + "id is used which is prone to error if the underlying index changes").withShortName("i").create(); Option dictOutOpt = obuilder.withLongName("dictOut").withRequired(true).withArgument( abuilder.withName("dictOut").withMinimum(1).withMaximum(1).create()).withDescription( "The output of the dictionary").withShortName("t").create(); Option weightOpt = obuilder.withLongName("weight").withRequired(false).withArgument( abuilder.withName("weight").withMinimum(1).withMaximum(1).create()).withDescription( "The kind of weight to use. Currently TF or TFIDF").withShortName("w").create(); Option delimiterOpt = obuilder.withLongName("delimiter").withRequired(false).withArgument( abuilder.withName("delimiter").withMinimum(1).withMaximum(1).create()).withDescription( "The delimiter for outputting the dictionary").withShortName("l").create(); Option powerOpt = obuilder.withLongName("norm").withRequired(false).withArgument( abuilder.withName("norm").withMinimum(1).withMaximum(1).create()).withDescription( "The norm to use, expressed as either a double or \"INF\" if you want to use the Infinite norm. " + "Must be greater or equal to 0. The default is not to normalize").withShortName("n").create(); Option maxOpt = obuilder.withLongName("max").withRequired(false).withArgument( abuilder.withName("max").withMinimum(1).withMaximum(1).create()).withDescription( "The maximum number of vectors to output. If not specified, then it will loop over all docs") .withShortName("m").create(); Option outWriterOpt = obuilder.withLongName("outputWriter").withRequired(false).withArgument( abuilder.withName("outputWriter").withMinimum(1).withMaximum(1).create()).withDescription( "The VectorWriter to use, either seq " + "(SequenceFileVectorWriter - default) or file (Writes to a File using JSON format)") .withShortName("e").create(); Option minDFOpt = obuilder.withLongName("minDF").withRequired(false).withArgument( abuilder.withName("minDF").withMinimum(1).withMaximum(1).create()).withDescription( "The minimum document frequency. Default is 1").withShortName("md").create(); Option maxDFPercentOpt = obuilder.withLongName("maxDFPercent").withRequired(false).withArgument( abuilder.withName("maxDFPercent").withMinimum(1).withMaximum(1).create()).withDescription( "The max percentage of docs for the DF. Can be used to remove really high frequency terms." + " Expressed as an integer between 0 and 100. Default is 99.").withShortName("x").create(); Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h") .create(); Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(idFieldOpt).withOption( outputOpt).withOption(delimiterOpt).withOption(helpOpt).withOption(fieldOpt).withOption(maxOpt) .withOption(dictOutOpt).withOption(powerOpt).withOption(outWriterOpt).withOption(maxDFPercentOpt) .withOption(weightOpt).withOption(minDFOpt).create(); try { Parser parser = new Parser(); parser.setGroup(group); CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return; } // Springify all this if (cmdLine.hasOption(inputOpt)) { // Lucene case File file = new File(cmdLine.getValue(inputOpt).toString()); if (!file.isDirectory()) { throw new IllegalArgumentException("Lucene directory: " + file.getAbsolutePath() + " does not exist or is not a directory"); } long maxDocs = Long.MAX_VALUE; if (cmdLine.hasOption(maxOpt)) { maxDocs = Long.parseLong(cmdLine.getValue(maxOpt).toString()); } if (maxDocs < 0) { throw new IllegalArgumentException("maxDocs must be >= 0"); } Directory dir = FSDirectory.open(file); IndexReader reader = IndexReader.open(dir, true); Weight weight; if (cmdLine.hasOption(weightOpt)) { String wString = cmdLine.getValue(weightOpt).toString(); if ("tf".equalsIgnoreCase(wString)) { weight = new TF(); } else if ("tfidf".equalsIgnoreCase(wString)) { weight = new TFIDF(); } else { throw new OptionException(weightOpt); } } else { weight = new TFIDF(); } String field = cmdLine.getValue(fieldOpt).toString(); int minDf = 1; if (cmdLine.hasOption(minDFOpt)) { minDf = Integer.parseInt(cmdLine.getValue(minDFOpt).toString()); } int maxDFPercent = 99; if (cmdLine.hasOption(maxDFPercentOpt)) { maxDFPercent = Integer.parseInt(cmdLine.getValue(maxDFPercentOpt).toString()); } TermInfo termInfo = new CachedTermInfo(reader, field, minDf, maxDFPercent); VectorMapper mapper = new TFDFMapper(reader, weight, termInfo); double norm = LuceneIterable.NO_NORMALIZING; if (cmdLine.hasOption(powerOpt)) { String power = cmdLine.getValue(powerOpt).toString(); if ("INF".equals(power)) { norm = Double.POSITIVE_INFINITY; } else { norm = Double.parseDouble(power); } } String idField = null; if (cmdLine.hasOption(idFieldOpt)) { idField = cmdLine.getValue(idFieldOpt).toString(); } LuceneIterable iterable; if (norm == LuceneIterable.NO_NORMALIZING) { iterable = new LuceneIterable(reader, idField, field, mapper, LuceneIterable.NO_NORMALIZING); } else { iterable = new LuceneIterable(reader, idField, field, mapper, norm); } String outFile = cmdLine.getValue(outputOpt).toString(); log.info("Output File: {}", outFile); VectorWriter vectorWriter; if (cmdLine.hasOption(outWriterOpt)) { String outWriter = cmdLine.getValue(outWriterOpt).toString(); if ("file".equals(outWriter)) { BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); vectorWriter = new JWriterVectorWriter(writer); } else { vectorWriter = getSeqFileWriter(outFile); } } else { vectorWriter = getSeqFileWriter(outFile); } long numDocs = vectorWriter.write(iterable, maxDocs); vectorWriter.close(); log.info("Wrote: {} vectors", numDocs); String delimiter = cmdLine.hasOption(delimiterOpt) ? cmdLine.getValue(delimiterOpt).toString() : "\t"; File dictOutFile = new File(cmdLine.getValue(dictOutOpt).toString()); log.info("Dictionary Output file: {}", dictOutFile); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(dictOutFile), Charset.forName("UTF8"))); JWriterTermInfoWriter tiWriter = new JWriterTermInfoWriter(writer, delimiter, field); tiWriter.write(termInfo); tiWriter.close(); writer.close(); } } catch (OptionException e) { log.error("Exception", e); CommandLineUtil.printHelp(group); } }
diff --git a/bennu-core/src/myorg/presentationTier/servlets/filters/contentRewrite/RequestChecksumFilter.java b/bennu-core/src/myorg/presentationTier/servlets/filters/contentRewrite/RequestChecksumFilter.java index 924ffde9..ffe6394e 100644 --- a/bennu-core/src/myorg/presentationTier/servlets/filters/contentRewrite/RequestChecksumFilter.java +++ b/bennu-core/src/myorg/presentationTier/servlets/filters/contentRewrite/RequestChecksumFilter.java @@ -1,39 +1,40 @@ /* * @(#)RequestChecksumFilter.java * * Copyright 2009 Instituto Superior Tecnico * Founding Authors: João Figueiredo, Luis Cruz, Paulo Abrantes, Susana Fernandes * * https://fenix-ashes.ist.utl.pt/ * * This file is part of the MyOrg web application infrastructure. * * MyOrg is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version.* * * MyOrg 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 MyOrg. If not, see <http://www.gnu.org/licenses/>. * */ package myorg.presentationTier.servlets.filters.contentRewrite; import javax.servlet.http.HttpServletRequest; public class RequestChecksumFilter extends pt.ist.fenixWebFramework.servlets.filters.contentRewrite.RequestChecksumFilter { @Override protected boolean shoudFilterReques(HttpServletRequest httpServletRequest) { return !httpServletRequest.getRequestURI().endsWith("/home.do") && !httpServletRequest.getRequestURI().endsWith("/isAlive.do") - && (httpServletRequest.getRequestURI().endsWith("/authenticationAction.do") && httpServletRequest - .getQueryString().contains("method=logoutEmptyPage")); + && (httpServletRequest.getRequestURI().endsWith("/authenticationAction.do") + && httpServletRequest.getQueryString() != null && httpServletRequest.getQueryString().contains( + "method=logoutEmptyPage")); } }
true
true
protected boolean shoudFilterReques(HttpServletRequest httpServletRequest) { return !httpServletRequest.getRequestURI().endsWith("/home.do") && !httpServletRequest.getRequestURI().endsWith("/isAlive.do") && (httpServletRequest.getRequestURI().endsWith("/authenticationAction.do") && httpServletRequest .getQueryString().contains("method=logoutEmptyPage")); }
protected boolean shoudFilterReques(HttpServletRequest httpServletRequest) { return !httpServletRequest.getRequestURI().endsWith("/home.do") && !httpServletRequest.getRequestURI().endsWith("/isAlive.do") && (httpServletRequest.getRequestURI().endsWith("/authenticationAction.do") && httpServletRequest.getQueryString() != null && httpServletRequest.getQueryString().contains( "method=logoutEmptyPage")); }
diff --git a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/persistence/XMLWriter.java b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/persistence/XMLWriter.java index e85749313..52ab4cf02 100644 --- a/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/persistence/XMLWriter.java +++ b/bundles/org.eclipse.equinox.p2.core/src/org/eclipse/equinox/internal/p2/persistence/XMLWriter.java @@ -1,292 +1,298 @@ /******************************************************************************* * Copyright (c) 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.equinox.internal.p2.persistence; import java.io.*; import java.util.*; import org.osgi.framework.Version; public class XMLWriter implements XMLConstants { public static class ProcessingInstruction { private String target; private String[] data; // The standard UTF-8 processing instruction public static final String XML_UTF8 = "<?xml version='1.0' encoding='UTF-8'?>"; //$NON-NLS-1$ public ProcessingInstruction(String target, String[] attrs, String[] values) { // Lengths of attributes and values must be the same this.target = target; this.data = new String[attrs.length]; for (int i = 0; i < attrs.length; i++) { data[i] = attributeImage(attrs[i], values[i]); } } public static ProcessingInstruction makeClassVersionInstruction(String target, Class clazz, Version version) { return new ProcessingInstruction(target, new String[] {PI_CLASS_ATTRIBUTE, PI_VERSION_ATTRIBUTE}, new String[] {clazz.getName(), version.toString()}); } public String toString() { StringBuffer sb = new StringBuffer("<?"); //$NON-NLS-1$ sb.append(this.target).append(' '); for (int i = 0; i < data.length; i++) { sb.append(this.data[i]); if (i < data.length - 1) { sb.append(' '); } } sb.append("?>"); //$NON-NLS-1$ return sb.toString(); } } private Stack elements; // XML elements that have not yet been closed private boolean open; // Can attributes be added to the current element? private String indent; // used for each level of indentation private PrintWriter pw; public XMLWriter(OutputStream output, ProcessingInstruction[] piElements) throws UnsupportedEncodingException { this.pw = new PrintWriter(new OutputStreamWriter(output, "UTF8"), false); //$NON-NLS-1$ println(ProcessingInstruction.XML_UTF8); this.elements = new Stack(); this.open = false; this.indent = " "; //$NON-NLS-1$ if (piElements != null) { for (int i = 0; i < piElements.length; i++) { println(piElements[i].toString()); } } } // start a new element public void start(String name) { if (this.open) { println('>'); } indent(); print('<'); print(name); this.elements.push(name); this.open = true; } // end the most recent element with this name public void end(String name) { if (this.elements.empty()) { throw new EndWithoutStartError(); } int index = this.elements.search(name); if (index == -1) { throw new EndWithoutStartError(name); } for (int i = 0; i < index; i += 1) { end(); } } // end the current element public void end() { if (this.elements.empty()) { throw new EndWithoutStartError(); } String name = (String) this.elements.pop(); if (this.open) { println("/>"); //$NON-NLS-1$ } else { printlnIndented("</" + name + '>', false); //$NON-NLS-1$ } this.open = false; } public static String escape(String txt) { StringBuffer buffer = null; for (int i = 0; i < txt.length(); ++i) { String replace; char c = txt.charAt(i); switch (c) { case '<' : replace = "&lt;"; //$NON-NLS-1$ break; case '>' : replace = "&gt;"; //$NON-NLS-1$ break; case '"' : replace = "&quot;"; //$NON-NLS-1$ break; case '\'' : replace = "&apos;"; //$NON-NLS-1$ break; case '&' : replace = "&amp;"; //$NON-NLS-1$ break; default : - if (buffer != null) - buffer.append(c); - continue; + // this is the set of legal xml characters in unicode excluding high surrogates since they cannot be represented with a char + // see http://www.w3.org/TR/REC-xml/#charsets + if ((c >= '\u0020' && c <= '\uD7FF') || c == '\t' || c == '\n' || c == '\r' || (c >= '\uE000' && c <= '\uFFFD')) { + if (buffer != null) + buffer.append(c); + continue; + } + replace = Character.isWhitespace(c) ? " " : null; //$NON-NLS-1$ } if (buffer == null) { buffer = new StringBuffer(txt.length() + 16); buffer.append(txt.substring(0, i)); } - buffer.append(replace); + if (replace != null) + buffer.append(replace); } if (buffer == null) return txt; return buffer.toString(); } // write a boolean attribute if it doesn't have the default value public void attribute(String name, boolean value, boolean defaultValue) { if (value != defaultValue) { attribute(name, value); } } public void attribute(String name, boolean value) { attribute(name, Boolean.toString(value)); } public void attribute(String name, int value) { attribute(name, Integer.toString(value)); } public void attributeOptional(String name, String value) { if (value != null && value.length() > 0) { attribute(name, value); } } public void attribute(String name, Object value) { if (!this.open) { throw new AttributeAfterNestedContentError(); } if (value == null) { return; // optional attribute with no value } print(' '); print(name); print("='"); //$NON-NLS-1$ print(escape(value.toString())); print('\''); } public void cdata(String data) { cdata(data, true); } public void cdata(String data, boolean escape) { if (this.open) { println('>'); this.open = false; } if (data != null) { printlnIndented(data, escape); } } public void flush() { this.pw.flush(); } public void writeProperties(Map properties) { writeProperties(PROPERTIES_ELEMENT, properties); } public void writeProperties(String propertiesElement, Map properties) { if (properties != null && properties.size() > 0) { start(propertiesElement); attribute(COLLECTION_SIZE_ATTRIBUTE, properties.size()); for (Iterator iter = properties.keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); writeProperty(name, (String) properties.get(name)); } end(propertiesElement); } } public void writeProperty(String name, String value) { start(PROPERTY_ELEMENT); attribute(PROPERTY_NAME_ATTRIBUTE, name); attribute(PROPERTY_VALUE_ATTRIBUTE, value); end(); } protected static String attributeImage(String name, String value) { if (value == null) { return ""; // optional attribute with no value } return name + "='" + escape(value) + '\''; //$NON-NLS-1$ } private void println(char c) { this.pw.println(c); } private void println(String s) { this.pw.println(s); } private void println() { this.pw.println(); } private void print(char c) { this.pw.print(c); } private void print(String s) { this.pw.print(s); } private void printlnIndented(String s, boolean escape) { if (s.length() == 0) { println(); } else { indent(); println(escape ? escape(s) : s); } } private void indent() { for (int i = this.elements.size(); i > 0; i -= 1) { print(this.indent); } } public static class AttributeAfterNestedContentError extends Error { private static final long serialVersionUID = 1L; // not serialized } public static class EndWithoutStartError extends Error { private static final long serialVersionUID = 1L; // not serialized private String name; public EndWithoutStartError() { super(); } public EndWithoutStartError(String name) { super(); this.name = name; } public String getName() { return this.name; } } }
false
true
public static String escape(String txt) { StringBuffer buffer = null; for (int i = 0; i < txt.length(); ++i) { String replace; char c = txt.charAt(i); switch (c) { case '<' : replace = "&lt;"; //$NON-NLS-1$ break; case '>' : replace = "&gt;"; //$NON-NLS-1$ break; case '"' : replace = "&quot;"; //$NON-NLS-1$ break; case '\'' : replace = "&apos;"; //$NON-NLS-1$ break; case '&' : replace = "&amp;"; //$NON-NLS-1$ break; default : if (buffer != null) buffer.append(c); continue; } if (buffer == null) { buffer = new StringBuffer(txt.length() + 16); buffer.append(txt.substring(0, i)); } buffer.append(replace); } if (buffer == null) return txt; return buffer.toString(); }
public static String escape(String txt) { StringBuffer buffer = null; for (int i = 0; i < txt.length(); ++i) { String replace; char c = txt.charAt(i); switch (c) { case '<' : replace = "&lt;"; //$NON-NLS-1$ break; case '>' : replace = "&gt;"; //$NON-NLS-1$ break; case '"' : replace = "&quot;"; //$NON-NLS-1$ break; case '\'' : replace = "&apos;"; //$NON-NLS-1$ break; case '&' : replace = "&amp;"; //$NON-NLS-1$ break; default : // this is the set of legal xml characters in unicode excluding high surrogates since they cannot be represented with a char // see http://www.w3.org/TR/REC-xml/#charsets if ((c >= '\u0020' && c <= '\uD7FF') || c == '\t' || c == '\n' || c == '\r' || (c >= '\uE000' && c <= '\uFFFD')) { if (buffer != null) buffer.append(c); continue; } replace = Character.isWhitespace(c) ? " " : null; //$NON-NLS-1$ } if (buffer == null) { buffer = new StringBuffer(txt.length() + 16); buffer.append(txt.substring(0, i)); } if (replace != null) buffer.append(replace); } if (buffer == null) return txt; return buffer.toString(); }