diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/main/java/spr9209/WebController.java b/src/main/java/spr9209/WebController.java index 5a7a5ba..a6e6441 100644 --- a/src/main/java/spr9209/WebController.java +++ b/src/main/java/spr9209/WebController.java @@ -1,55 +1,55 @@ /* * Copyright (c) 1998-2012 Citrix Online LLC * All Rights Reserved Worldwide. * * THIS PROGRAM IS CONFIDENTIAL AND PROPRIETARY TO CITRIX ONLINE * AND CONSTITUTES A VALUABLE TRADE SECRET. Any unauthorized use, * reproduction, modification, or disclosure of this program is * strictly prohibited. Any use of this program by an authorized * licensee is strictly subject to the terms and conditions, * including confidentiality obligations, set forth in the applicable * License and Co-Branding Agreement between Citrix Online LLC and * the licensee. */ package spr9209; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; @Controller public class WebController { @RequestMapping("/request1") public void handleRequest1() { throw new IllegalArgumentException(); } @RequestMapping("/request2") public void handleRequest2() { throw new NullPointerException(); } @RequestMapping("/ping") @ResponseBody public String ping() { return "pong"; } @ExceptionHandler(IllegalArgumentException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public void iaeHandler(HttpServletResponse response) { try { - response.getWriter().println("Handling NullPointerException"); + response.getWriter().println("Handling IllegalArgumentException"); } catch (IOException e) { //ignore } } }
true
true
public void iaeHandler(HttpServletResponse response) { try { response.getWriter().println("Handling NullPointerException"); } catch (IOException e) { //ignore } }
public void iaeHandler(HttpServletResponse response) { try { response.getWriter().println("Handling IllegalArgumentException"); } catch (IOException e) { //ignore } }
diff --git a/src/util/TwoComplement.java b/src/util/TwoComplement.java index 8c56127..8cdb8cb 100644 --- a/src/util/TwoComplement.java +++ b/src/util/TwoComplement.java @@ -1,25 +1,25 @@ package util; public class TwoComplement { public static double to2complement(byte b) { if(b < 0) return (b + (short) 256); return b; } public static byte from2complement(double d) { - if(d > 256.0) - d = 256.0; + if(d >= 255.0) + return -1; if(d < 0.0) - d = 0.0; + return 0; short s = (short) Math.round(d); if(s < 128) return (byte) s; return (byte) (s - 256); } }
false
true
public static byte from2complement(double d) { if(d > 256.0) d = 256.0; if(d < 0.0) d = 0.0; short s = (short) Math.round(d); if(s < 128) return (byte) s; return (byte) (s - 256); }
public static byte from2complement(double d) { if(d >= 255.0) return -1; if(d < 0.0) return 0; short s = (short) Math.round(d); if(s < 128) return (byte) s; return (byte) (s - 256); }
diff --git a/voice-client-example/src/main/java/com/tuenti/voice/example/ui/LoginView.java b/voice-client-example/src/main/java/com/tuenti/voice/example/ui/LoginView.java index 150aa9f..8b5f621 100644 --- a/voice-client-example/src/main/java/com/tuenti/voice/example/ui/LoginView.java +++ b/voice-client-example/src/main/java/com/tuenti/voice/example/ui/LoginView.java @@ -1,138 +1,138 @@ package com.tuenti.voice.example.ui; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.view.View; import android.widget.TextView; import com.tuenti.voice.core.OnConnectionListener; import com.tuenti.voice.core.VoiceActivity; import com.tuenti.voice.core.data.Connection; import com.tuenti.voice.core.service.VoiceClientService; import com.tuenti.voice.example.R; import static android.view.View.OnClickListener; public class LoginView extends VoiceActivity implements OnClickListener, OnConnectionListener { // ------------------------------ FIELDS ------------------------------ // Template Google Settings private static final String MY_USER = ""; private static final String MY_PASS = ""; private Handler mHandler = new Handler(); private SharedPreferences mSettings; // --------------------- GETTER / SETTER METHODS --------------------- private Connection getConnection() { Connection connection = new Connection(); connection.setUsername( MY_USER ); connection.setPassword( MY_PASS ); connection.setStunHost( getStringPref( R.string.stunserver_key, R.string.stunserver_value ) ); connection.setTurnHost( getStringPref( R.string.turnserver_key, R.string.turnserver_value ) ); - connection.setTurnHost( getStringPref( R.string.turn_username_key, R.string.turn_username_value ) ); - connection.setTurnPassword( MY_PASS ); + connection.setTurnUsername( getStringPref( R.string.turn_username_key, R.string.turn_username_value ) ); + connection.setTurnPassword( getStringPref( R.string.turn_password_key, R.string.turn_password_value ) ); connection.setXmppHost( getStringPref( R.string.xmpp_host_key, R.string.xmpp_host_value ) ); connection.setXmppPort( getIntPref( R.string.xmpp_port_key, R.string.xmpp_port_value ) ); connection.setXmppUseSsl( getBooleanPref( R.string.xmpp_use_ssl_key, R.string.xmpp_use_ssl_value ) ); connection.setRelayHost( getStringPref( R.string.relayserver_key, R.string.relayserver_value ) ); return connection; } // ------------------------ INTERFACE METHODS ------------------------ // --------------------- Interface OnClickListener --------------------- public void onClick( View view ) { login( getConnection() ); } // --------------------- Interface OnConnectionListener --------------------- @Override public void onLoggedIn() { changeStatus( "Logged in" ); mHandler.postDelayed( new Runnable() { @Override public void run() { displayRosterView(); } }, 2000 ); } @Override public void onLoggedOut() { changeStatus( "Logged out" ); } @Override public void onLoggingIn() { changeStatus( "Logging in" ); } // -------------------------- OTHER METHODS -------------------------- @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); // start the service Intent intent = new Intent( this, VoiceClientService.class ); startService( intent ); setContentView( R.layout.login_view ); findViewById( R.id.login_btn ).setOnClickListener( this ); // Set default preferences mSettings = PreferenceManager.getDefaultSharedPreferences( this ); } private void changeStatus( final String status ) { runOnUiThread( new Runnable() { @Override public void run() { ( (TextView) findViewById( R.id.status_view ) ).setText( status ); } } ); } private void displayRosterView() { Intent intent = new Intent( this, RosterView.class ); startActivity( intent ); } private boolean getBooleanPref( int key, int defaultValue ) { return Boolean.valueOf( getStringPref( key, defaultValue ) ); } private int getIntPref( int key, int defaultValue ) { return Integer.valueOf( getStringPref( key, defaultValue ) ); } private String getStringPref( int key, int defaultValue ) { return mSettings.getString( getString( key ), getString( defaultValue ) ); } }
true
true
private Connection getConnection() { Connection connection = new Connection(); connection.setUsername( MY_USER ); connection.setPassword( MY_PASS ); connection.setStunHost( getStringPref( R.string.stunserver_key, R.string.stunserver_value ) ); connection.setTurnHost( getStringPref( R.string.turnserver_key, R.string.turnserver_value ) ); connection.setTurnHost( getStringPref( R.string.turn_username_key, R.string.turn_username_value ) ); connection.setTurnPassword( MY_PASS ); connection.setXmppHost( getStringPref( R.string.xmpp_host_key, R.string.xmpp_host_value ) ); connection.setXmppPort( getIntPref( R.string.xmpp_port_key, R.string.xmpp_port_value ) ); connection.setXmppUseSsl( getBooleanPref( R.string.xmpp_use_ssl_key, R.string.xmpp_use_ssl_value ) ); connection.setRelayHost( getStringPref( R.string.relayserver_key, R.string.relayserver_value ) ); return connection; }
private Connection getConnection() { Connection connection = new Connection(); connection.setUsername( MY_USER ); connection.setPassword( MY_PASS ); connection.setStunHost( getStringPref( R.string.stunserver_key, R.string.stunserver_value ) ); connection.setTurnHost( getStringPref( R.string.turnserver_key, R.string.turnserver_value ) ); connection.setTurnUsername( getStringPref( R.string.turn_username_key, R.string.turn_username_value ) ); connection.setTurnPassword( getStringPref( R.string.turn_password_key, R.string.turn_password_value ) ); connection.setXmppHost( getStringPref( R.string.xmpp_host_key, R.string.xmpp_host_value ) ); connection.setXmppPort( getIntPref( R.string.xmpp_port_key, R.string.xmpp_port_value ) ); connection.setXmppUseSsl( getBooleanPref( R.string.xmpp_use_ssl_key, R.string.xmpp_use_ssl_value ) ); connection.setRelayHost( getStringPref( R.string.relayserver_key, R.string.relayserver_value ) ); return connection; }
diff --git a/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/internal/model/delta/DeltaProcessor.java b/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/internal/model/delta/DeltaProcessor.java index ccbf5d390..c159c4778 100644 --- a/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/internal/model/delta/DeltaProcessor.java +++ b/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/internal/model/delta/DeltaProcessor.java @@ -1,1558 +1,1558 @@ /* * Copyright (c) 2011, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.dart.tools.core.internal.model.delta; import com.google.common.io.Closeables; import com.google.dart.compiler.DartCompilationError; import com.google.dart.compiler.DartSource; import com.google.dart.compiler.LibrarySource; import com.google.dart.compiler.SystemLibraryManager; import com.google.dart.compiler.UrlDartSource; import com.google.dart.compiler.UrlLibrarySource; import com.google.dart.compiler.ast.DartDirective; import com.google.dart.compiler.ast.DartImportDirective; import com.google.dart.compiler.ast.DartLibraryDirective; import com.google.dart.compiler.ast.DartResourceDirective; import com.google.dart.compiler.ast.DartSourceDirective; import com.google.dart.compiler.ast.DartUnit; import com.google.dart.indexer.utilities.io.FileUtilities; import com.google.dart.tools.core.DartCore; import com.google.dart.tools.core.internal.model.DartElementImpl; import com.google.dart.tools.core.internal.model.DartLibraryImpl; import com.google.dart.tools.core.internal.model.DartModelManager; import com.google.dart.tools.core.internal.model.DartProjectImpl; import com.google.dart.tools.core.internal.model.DartProjectNature; import com.google.dart.tools.core.internal.model.ModelUpdater; import com.google.dart.tools.core.internal.model.OpenableElementImpl; import com.google.dart.tools.core.internal.model.SystemLibraryManagerProvider; import com.google.dart.tools.core.internal.model.info.DartLibraryInfo; import com.google.dart.tools.core.internal.model.info.OpenableElementInfo; import com.google.dart.tools.core.internal.util.ResourceUtil; import com.google.dart.tools.core.model.CompilationUnit; import com.google.dart.tools.core.model.DartElement; import com.google.dart.tools.core.model.DartElementDelta; import com.google.dart.tools.core.model.DartLibrary; import com.google.dart.tools.core.model.DartModelException; import com.google.dart.tools.core.model.DartProject; import com.google.dart.tools.core.model.DartResource; import com.google.dart.tools.core.model.ElementChangedEvent; import com.google.dart.tools.core.model.ElementChangedListener; import com.google.dart.tools.core.utilities.compiler.DartCompilerUtilities; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.ISafeRunnable; import org.eclipse.core.runtime.SafeRunner; import org.eclipse.core.runtime.URIUtil; import java.io.File; import java.io.IOException; import java.io.Reader; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Instances of the class <code>DeltaProcessor</code> are used by <code>DartModelManager</code> to * convert <code>IResourceDelta</code>s into <code>DartElementDelta</code>s. It also does some * processing on the <code>DartElementImpl</code>s involved (e.g. setting or removing of parents * when elements are added or deleted from the model). * <p> * High level summary of what the delta processor does: * <ul> * <li>reacts to resource deltas</li> * <li>fires corresponding Dart element deltas</li> * <li>deltas also contain non-Dart resources changes</li> * <li>updates the model to reflect the Dart element changes</li> * <li>refresh external archives (delta, model update, indexing)</li> * <li>is thread safe (one delta processor instance per thread, see * DeltaProcessingState#resourceChanged(...))</li> * </ul> * <p> * TODO(jwren) Remove the DEBUG flag and replace with Eclipse-tracing */ public class DeltaProcessor { public enum DirectiveType { IMPORT, SRC, RES } private final static int NON_DART_RESOURCE = -1; public static boolean DEBUG = false; public static boolean VERBOSE = false; // must not collide with ElementChangedEvent event masks public static final int DEFAULT_CHANGE_EVENT = 0; /** * The global state of delta processing. */ private DeltaProcessingState state; /** * The Dart model manager */ private DartModelManager manager; /** * The <code>DartElementDeltaImpl</code> corresponding to the <code>IResourceDelta</code> being * translated. */ private DartElementDeltaImpl currentDelta; /** * The Dart element that was last created (see createElement(IResource)). This is used as a stack * of Dart elements (using getParent() to pop it, and using the various get*(...) to push it. */ private OpenableElementImpl currentElement; /** * Queue of deltas created explicitly by the Dart Model that have yet to be fired. */ public ArrayList<DartElementDelta> dartModelDeltas = new ArrayList<DartElementDelta>(); /** * Queue of reconcile deltas on working copies that have yet to be fired. This is a table form * IWorkingCopy to DartElementDelta */ public HashMap<CompilationUnit, DartElementDelta> reconcileDeltas = new HashMap<CompilationUnit, DartElementDelta>(); /** * Turns delta firing on/off. By default it is on. * * @see #startDeltas() * @see #stopDeltas() */ private boolean isFiring = true; /** * For each call to {@link #resourceChanged(IResourceChangeEvent)}, each project should call * {@link DartProjectImpl#recomputeLibrarySet()} only once. This is a set of the project names for * which such a call was made, and thus is used to determine if the call shouldn't be made a * second time. */ private Set<String> projectHasRecomputedLibrarySet; /** * Used to update the DartModel for <code>DartElementDelta</code>s. */ private final ModelUpdater modelUpdater = new ModelUpdater(); /** * A set of DartProjects whose caches need to be reset */ public HashSet<DartProjectImpl> projectCachesToReset = new HashSet<DartProjectImpl>(); /** * Type of event that should be processed no matter what the real event type is. */ public int overridenEventType = -1; /** * The only constructor for this class. */ public DeltaProcessor(DeltaProcessingState state, DartModelManager manager) { this.state = state; this.manager = manager; } /** * Fire Dart Model delta, flushing them after the fact after post_change notification. If the * firing mode has been turned off, this has no effect. */ public void fire(DartElementDelta customDelta, int eventType) { if (!isFiring) { return; } if (VERBOSE) { System.out.println("-----------------------------------------------------------------------------------------------------------------------");//$NON-NLS-1$ } DartElementDelta deltaToNotify; if (customDelta == null) { deltaToNotify = mergeDeltas(dartModelDeltas); } else { deltaToNotify = customDelta; } // Notification // Important: if any listener reacts to notification by updating the // listeners list or mask, these lists will // be duplicated, so it is necessary to remember original lists in a // variable (since field values may change under us) ElementChangedListener[] listeners; int[] listenerMask; int listenerCount; synchronized (state) { listeners = state.elementChangedListeners; listenerMask = state.elementChangedListenerMasks; listenerCount = state.elementChangedListenerCount; } switch (eventType) { case DEFAULT_CHANGE_EVENT: case ElementChangedEvent.POST_CHANGE: firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount); fireReconcileDelta(listeners, listenerMask, listenerCount); break; } } /** * Flushes all deltas without firing them. */ public void flush() { dartModelDeltas = new ArrayList<DartElementDelta>(); } /** * Registers the given delta with this delta processor. */ public void registerDartModelDelta(DartElementDelta delta) { dartModelDeltas.add(delta); } /** * Traverse the set of projects which have changed namespace, and reset their caches and their * dependents */ public void resetProjectCaches() { if (projectCachesToReset.isEmpty()) { return; } for (DartProjectImpl dartProjectImpl : projectCachesToReset) { dartProjectImpl.resetCaches(); } projectCachesToReset.clear(); } /** * Notification that some resource changes have happened on the platform, and that the Dart Model * should update any required internal structures such that its elements remain consistent. * Translates <code>IResourceDeltas</code> into <code>DartElementDeltas</code>. * <p> * This method is only called from * {@link DeltaProcessingState#resourceChanged(IResourceChangeEvent)} * * @see DeltaProcessingState * @see IResource * @see IResourceDelta * @see IResourceChangeEvent */ public void resourceChanged(IResourceChangeEvent event) { int eventType = overridenEventType == -1 ? event.getType() : overridenEventType; IResource resource = event.getResource(); IResourceDelta delta = event.getDelta(); // reset the contents projectHasRecomputedLibrarySet set projectHasRecomputedLibrarySet = new HashSet<String>(1); switch (eventType) { case IResourceChangeEvent.PRE_CLOSE: if (VERBOSE) { System.out.println("DeltaProcessor.resourceChanged() " + "CLOSE"); } try { if (resource.getType() == IResource.PROJECT) { IProject project = (IProject) resource; if (project.hasNature(DartCore.DART_PROJECT_NATURE)) { DartProjectImpl dartProject = (DartProjectImpl) DartCore.create(project); dartProject.clearLibraryInfo(); } } } catch (CoreException e) { // project doesn't exist or is not open: ignore } return; case IResourceChangeEvent.PRE_DELETE: if (VERBOSE) { System.out.println("DeltaProcessor.resourceChanged() " + "PRE_DELETE"); } try { if (resource.getType() == IResource.PROJECT) { IProject project = (IProject) resource; if (project.hasNature(DartCore.DART_PROJECT_NATURE)) { DartProjectImpl dartProject = (DartProjectImpl) DartCore.create(project); dartProject.close(); removeFromParentInfo(dartProject); } } } catch (CoreException ce) { // project doesn't exist or is not open: ignore } return; case IResourceChangeEvent.PRE_REFRESH: if (VERBOSE) { System.out.println("DeltaProcessor.resourceChanged() " + "PRE_REFRESH"); } return; case IResourceChangeEvent.POST_CHANGE: if (VERBOSE) { System.out.println("DeltaProcessor.resourceChanged() " + "POST_CHANGE"); } try { try { // by calling stopDeltas, isFiring is set to false which prevents the firing of Dart model deltas stopDeltas(); DartElementDelta translatedDelta = processResourceDelta(delta); if (translatedDelta != null) { registerDartModelDelta(translatedDelta); } } finally { // call startDeltas to allow the firing of Dart model deltas startDeltas(); } // fire the delta change events to the listeners fire(null, ElementChangedEvent.POST_CHANGE); } finally { this.state.resetOldDartProjectNames(); } return; case IResourceChangeEvent.PRE_BUILD: if (VERBOSE) { System.out.println("DeltaProcessor.resourceChanged() " + "PRE_BUILD"); } return; case IResourceChangeEvent.POST_BUILD: if (VERBOSE) { System.out.println("DeltaProcessor.resourceChanged() " + "POST_BUILD"); } // DartBuilder.buildFinished(); return; } } /** * Update Dart Model given some delta */ public void updateDartModel(DartElementDelta customDelta) { if (customDelta == null) { for (int i = 0, length = dartModelDeltas.size(); i < length; i++) { DartElementDelta delta = dartModelDeltas.get(i); modelUpdater.processDartDelta(delta); } } else { modelUpdater.processDartDelta(customDelta); } } /** * Adds the given child handle to its parent's cache of children. * * @see #removeFromParentInfo(OpenableElementImpl) */ private void addToParentInfo(OpenableElementImpl child) { OpenableElementImpl parent = (OpenableElementImpl) child.getParent(); if (parent != null && parent.isOpen()) { try { OpenableElementInfo info = (OpenableElementInfo) parent.getElementInfo(); info.addChild(child); } catch (DartModelException e) { // do nothing - we already checked if open } } } /** * Closes the given element, which removes it from the cache of open elements. */ private void close(DartElementImpl element) { try { element.close(); } catch (DartModelException e) { // do nothing } } /** * Generic processing for elements with changed contents: * <ul> * <li>The element is closed such that any subsequent accesses will re-open the element reflecting * its new structure. * <li>An entry is made in the delta reporting a content change (K_CHANGE with F_CONTENT flag * set). * </ul> */ private void contentChanged(DartElementImpl element, IResourceDelta delta) { if (element.getElementType() == DartElement.COMPILATION_UNIT) { currentDelta().changed(element, DartElementDelta.CHANGED); // if this CompilationUnit defines a library, update potential directive differences if (((CompilationUnit) element).definesLibrary()) { // reference the DartLibraryImpl DartLibraryImpl library = (DartLibraryImpl) element.getParent(); // Compute and cache the set of directives in the model, aka: use the referenced library to // see what was in the model just before this delta processor process was triggered. // This cache contains the set of sources in the String path form: // [file:/Users/user/dart/HelloWorld/HelloWorld.dart, file:/Users/user/dart/HelloWorld/A.dart] CachedDirectives oldCachedDirectives = getCachedDirectives(library); // Compute and cache the set of directives in the file, aka: using the parser to compute // what the sets of directives are. // This cache contains the set of sources in the String path form: // [file:/Users/user/dart/HelloWorld/HelloWorld.dart, file:/Users/user/dart/HelloWorld/A.dart] IFile iFile = (IFile) delta.getResource(); UrlDartSource dartSource = null; LibrarySource librarySource = null; CachedDirectives newCachedDirectives = new CachedDirectives(); if (iFile != null && iFile.exists()) { File libFile = new File(iFile.getLocationURI()); librarySource = new UrlLibrarySource(iFile.getLocationURI(), SystemLibraryManagerProvider.getSystemLibraryManager()); dartSource = new UrlDartSource(libFile, librarySource); newCachedDirectives = getCachedDirectives(dartSource, library); } contentChanged_fileDirectives(DirectiveType.SRC, oldCachedDirectives.getSources(), newCachedDirectives.getSources(), library); contentChanged_fileDirectives(DirectiveType.RES, oldCachedDirectives.getResources(), newCachedDirectives.getResources(), library); contentChanged_importDirectives(oldCachedDirectives.getImports(), newCachedDirectives.getImports(), library, librarySource); contentChanged_libraryNameDirective(oldCachedDirectives.getLibraryName(), newCachedDirectives.getLibraryName(), library, librarySource); } } // else, no non-compilation unit resource changes can affect the model } private void contentChanged_fileDirectives(DirectiveType directiveType, Set<String> oldStrSet, Set<String> newStrSet, DartLibraryImpl library) { // Simple assertions, this method can only handle the SRC and RES directive types: Assert.isTrue(directiveType == DirectiveType.SRC || directiveType == DirectiveType.RES); // if we could not compute one of the two sets of sources/resources, return // or if the sets are equal, also return if (newStrSet == null || oldStrSet == null || newStrSet.equals(oldStrSet)) { return; } // for each of the old sources, detect removes for (String oldPathElt : oldStrSet) { if (!newStrSet.contains(oldPathElt)) { // REMOVE URI uri = null; try { // The single argument constructor is valid since oldPathElt comes from a URI#toString() call. uri = new URI(oldPathElt); } catch (URISyntaxException e) { DartCore.logError(e); } if (uri != null) { OpenableElementImpl openableDartElement = null; if (directiveType == DirectiveType.SRC) { openableDartElement = (OpenableElementImpl) library.getCompilationUnit(uri); } else if (directiveType == DirectiveType.RES) { openableDartElement = (OpenableElementImpl) library.getResource(uri); } if (openableDartElement != null) { // make sure to update the model here! removeFromParentInfo(openableDartElement); currentDelta().changed(library, DartElementDelta.CHANGED); currentDelta().removed(openableDartElement); // Next, update the project structure by updating the library set, unless the call has // already been made for the project, in this call to the DeltaProcessor DartProjectImpl dartProject = (DartProjectImpl) library.getDartProject(); if (directiveType == DirectiveType.SRC && !projectHasRecomputedLibrarySet.contains(dartProject.getElementName())) { dartProject.recomputeLibrarySet(); projectHasRecomputedLibrarySet.add(dartProject.getElementName()); } } if (DEBUG) { System.out.println("DeltaProcessor.contentChanged_fileDirectives() REMOVE: " + oldPathElt); } } } } // for each of the new sources, detect adds for (String newPathElt : newStrSet) { if (!oldStrSet.contains(newPathElt)) { // ADD URI uri = null; try { // The single argument constructor is valid since newPathElt comes from a URI#toString() call. uri = new URI(newPathElt); } catch (URISyntaxException e) { DartCore.logError(e); } if (uri != null) { OpenableElementImpl openableDartElement = null; if (directiveType == DirectiveType.SRC) { openableDartElement = (OpenableElementImpl) library.getCompilationUnit(uri); } else if (directiveType == DirectiveType.RES) { openableDartElement = (OpenableElementImpl) library.getResource(uri); } if (openableDartElement != null) { // make sure to update the model here! addToParentInfo(openableDartElement); currentDelta().changed(library, DartElementDelta.CHANGED); currentDelta().added(openableDartElement); // Call the project to have the newly imported source file removed from the list of // top-level library files- unless recomputeLibrarySet has already been called. DartProjectImpl dartProject = (DartProjectImpl) library.getDartProject(); if (directiveType == DirectiveType.SRC && !projectHasRecomputedLibrarySet.contains(dartProject.getElementName())) { IFile iFile = (IFile) openableDartElement.getResource(); dartProject.removeLibraryFile(iFile); } } if (DEBUG) { System.out.println("DeltaProcessor.contentChanged_fileDirectives() ADD: " + newPathElt); } } } } } private void contentChanged_importDirectives(Set<String> oldStrSet, Set<String> newStrSet, DartLibraryImpl library, LibrarySource librarySource) { // if we could not compute one of the two sets of imports, return // or if the sets are equal, also return if (newStrSet == null || oldStrSet == null || newStrSet.equals(oldStrSet)) { return; } // for each of the old sources, detect removes for (String oldPathElt : oldStrSet) { if (!newStrSet.contains(oldPathElt)) { // REMOVE try { URI uri = new URI(oldPathElt); DartLibraryInfo libraryInfo = (DartLibraryInfo) library.getElementInfo(); if (URIUtil.isFileURI(uri)) { IFile libraryIFile = ResourceUtil.getFile(uri); if (libraryIFile != null && libraryIFile.exists() && libraryIFile.isLinked()) { DartProjectImpl project = (DartProjectImpl) DartCore.create(libraryIFile.getProject()); DartLibrary dartLibrary = new DartLibraryImpl(project, libraryIFile, new UrlLibrarySource(uri, SystemLibraryManagerProvider.getSystemLibraryManager())); libraryInfo.removeImport(dartLibrary); currentDelta().changed(library, DartElementDelta.CHANGED); } else { // TODO(jwren) linking of the file is needed, or the imported library file doesn't exist } } else if (SystemLibraryManager.isDartUri(uri)) { // This covers the "dart:dom" use case. LibrarySource importedLibrarySource; try { importedLibrarySource = librarySource.getImportFor(uri.toString()); } catch (IOException e) { DartCore.logError(e); continue; } DartLibrary dartLibrary = new DartLibraryImpl(importedLibrarySource); libraryInfo.removeImport(dartLibrary); currentDelta().changed(library, DartElementDelta.CHANGED); } } catch (DartModelException e) { DartCore.logError(e); } catch (URISyntaxException e) { DartCore.logError(e); } if (DEBUG) { System.out.println("DeltaProcessor.contentChanged_importDirectives() REMOVE: " + oldPathElt); } } } // for each of the new sources, detect adds for (String newPathElt : newStrSet) { if (!oldStrSet.contains(newPathElt)) { // ADD try { URI uri = new URI(newPathElt); DartLibraryInfo libraryInfo = (DartLibraryInfo) library.getElementInfo(); if (URIUtil.isFileURI(uri)) { IFile libraryIFile = ResourceUtil.getFile(uri); if (libraryIFile != null && libraryIFile.exists() && libraryIFile.isLinked()) { DartProjectImpl project = (DartProjectImpl) DartCore.create(libraryIFile.getProject()); DartLibrary dartLibrary = new DartLibraryImpl(project, libraryIFile, new UrlLibrarySource(uri, SystemLibraryManagerProvider.getSystemLibraryManager())); libraryInfo.addImport(dartLibrary); currentDelta().changed(dartLibrary, DartElementDelta.CHANGED); } else { // TODO(jwren) linking of the file is needed, or the imported library file doesn't exist } } else if (SystemLibraryManager.isDartUri(uri)) { // This covers the "dart:dom" use case. LibrarySource importedLibrarySource; try { // TODO(jwren) currently, if the user types in something that isn't valid, // (i.e. "dart:A"), then an exception is thrown, the exception is being logged as an // info below. // See http://code.google.com/p/dart/issues/detail?id=203 importedLibrarySource = librarySource.getImportFor(uri.toString()); } catch (IOException e) { DartCore.logInformation("The URI " + uri.toString() + " could not be computed as a valid library import for this library: " + librarySource.getName() + ".", e); continue; } try { if (importedLibrarySource.exists()) { DartLibrary dartLibrary = new DartLibraryImpl(importedLibrarySource); libraryInfo.addImport(dartLibrary); currentDelta().changed(library, DartElementDelta.CHANGED); } } catch (Exception exception) { // The library is not valid, so we don't add it. } } } catch (DartModelException e) { DartCore.logError(e); } catch (URISyntaxException e) { DartCore.logError(e); } if (DEBUG) { System.out.println("DeltaProcessor.contentChanged_importDirectives() ADD: " + newPathElt); } } } } private void contentChanged_libraryNameDirective(String oldLibraryName, String newLibraryName, DartLibraryImpl library, LibrarySource librarySource) { // if we could not compute one of the two library names, return // or if the sets are equal, also return if (oldLibraryName == null || newLibraryName == null || oldLibraryName.equals(newLibraryName)) { return; } // else, !oldLibraryName.equals(newLibraryName) DartLibraryInfo libraryInfo; try { libraryInfo = (DartLibraryInfo) library.getElementInfo(); libraryInfo.setName(newLibraryName); currentDelta().changed(library, DartElementDelta.CHANGED); } catch (DartModelException e) { DartCore.logError(e); } } /** * Called by {@link #updateCurrentDelta(IResourceDelta, int)}, the {@link DartElement} generated * by this method is used when the creating the {@link DartElementDelta} elements. * <p> * Creates the {@link DartElement} openable corresponding to this resource. Returns * <code>null</code> if none was found. */ private OpenableElementImpl createElement(IResource resource, int elementType) { if (resource == null) { return null; } //IPath path = resource.getFullPath(); DartElement element = null; switch (elementType) { case DartElement.DART_PROJECT: // note that non-Dart resources rooted at the project level will also // enter this code with // an elementType DART_PROJECT (see #elementType(...)). if (resource instanceof IProject) { if (currentElement != null && currentElement.getElementType() == DartElement.DART_PROJECT && ((DartProject) currentElement).getProject().equals(resource)) { return currentElement; } IProject proj = (IProject) resource; // The following, commented out code, checks that the project has a Dart nature, since all // projects in the DartEditor are DartProjects, this check has been removed for the time being. //if (DartProjectNature.hasDartNature(proj)) { element = DartCore.create(proj); //} else { // Dart project may have been been closed or removed (look for // element amongst old Dart projects list). // element = state.findDartProject(proj.getName()); //} } break; case DartElement.COMPILATION_UNIT: // Note: this element could be a compilation unit or library (if it is a defining compilation unit) element = DartCore.create(resource); if (element instanceof DartLibrary) { try { element = ((DartLibrary) element).getDefiningCompilationUnit(); } catch (DartModelException exception) { element = null; } } // if the element is null, then this must be a new dart file, create a new DartLibrary if (element == null && resource instanceof IFile) { DartProjectImpl dartProject = (DartProjectImpl) DartCore.create(resource.getProject()); element = new DartLibraryImpl(dartProject, (IFile) resource); } break; case DartElement.HTML_FILE: element = DartCore.create(resource); break; } if (element == null) { return null; } currentElement = (OpenableElementImpl) element; return currentElement; } private DartElementDeltaImpl currentDelta() { if (currentDelta == null) { currentDelta = new DartElementDeltaImpl(manager.getDartModel()); } return currentDelta; } /** * Processing for an element that has been added: * <ul> * <li>If the element is a project, do nothing, and do not process children, as when a project is * created it does not yet have any natures - specifically a Dart nature. * <li>If the element is not a project, process it as added (see <code>basicElementAdded</code>. * </ul> */ private void elementAdded(OpenableElementImpl element, IResourceDelta delta) { int elementType = element.getElementType(); // if a project element if (elementType == DartElement.DART_PROJECT) { // project add is handled by DartProjectNature.configure() because // when a project is created, it does not yet have a Dart nature IProject project = (IProject) delta.getResource(); // if this project is a Dart project if (delta != null && project != null && DartProjectNature.hasDartNature(project)) { ////////// //try { //project.create(project.getDescription(), new NullProgressMonitor()); //project.open(IResource.BACKGROUND_REFRESH, new NullProgressMonitor()); //} catch (CoreException e) { // e.printStackTrace(); //} ////////// addToParentInfo(element); if ((delta.getFlags() & IResourceDelta.MOVED_FROM) != 0) { DartElementImpl movedFromElement = (DartElementImpl) element.getDartModel().getDartProject( delta.getMovedFromPath().lastSegment()); currentDelta().movedTo(element, movedFromElement); } else { // Force the project to be closed as it might have been opened // before the resource modification came in and it might have a new // child // For example, in an IWorkspaceRunnable: // 1. create a Dart project P (where P=src) // 2. open project P // 3. add folder f in P's pkg fragment root // When the resource delta comes in, only the addition of P is // notified, // but the pkg fragment root of project P is already opened, thus its // children are not recomputed // and it appears to contain only the default package. close(element); currentDelta().added(element); } // remember that the project's cache must be reset resetThisProjectCache((DartProjectImpl) element); } } else { // else, not a project // if a regular, (non-move) add if (delta == null || (delta.getFlags() & IResourceDelta.MOVED_FROM) == 0) { // regular element addition if (isPrimaryWorkingCopy(element, elementType)) { // filter out changes to primary compilation unit in working copy mode // just report a change to the resource (see // https://bugs.eclipse.org/bugs/show_bug.cgi?id=59500) currentDelta().changed(element, DartElementDelta.F_PRIMARY_RESOURCE); } else { addToParentInfo(element); // Force the element to be closed as it might have been opened // before the resource modification came in and it might have a new // child // For example, in an IWorkspaceRunnable: // 1. create a package fragment p using a Dart model operation // 2. open package p // 3. add file X.dart in folder p // When the resource delta comes in, only the addition of p is // notified, // but the package p is already opened, thus its children are not // recomputed // and it appears empty. close(element); currentDelta().added(element); } } else { // element is moved // TODO This case is not yet supported. // addToParentInfo(element); // close(element); // // IPath movedFromPath = delta.getMovedFromPath(); // IResource res = delta.getResource(); // IResource movedFromRes; // if (res instanceof IFile) { // movedFromRes = res.getWorkspace().getRoot().getFile(movedFromPath); // } else { // movedFromRes = res.getWorkspace().getRoot().getFolder(movedFromPath); // } // // // find the element type of the moved from element // IPath rootPath = externalPath(movedFromRes); // RootInfo movedFromInfo = enclosingRootInfo(rootPath, IResourceDelta.REMOVED); // int movedFromType = elementType(movedFromRes, IResourceDelta.REMOVED, // element.getParent().getElementType(), movedFromInfo); // // // reset current element as it might be inside a nested root // // (popUntilPrefixOf() may use the outer root) // currentElement = null; // // // create the moved from element // DartElementImpl movedFromElement = elementType != DartElement.DART_PROJECT // && movedFromType == DartElement.DART_PROJECT ? null : // outside // // classpath // createElement(movedFromRes, movedFromType, movedFromInfo); // if (movedFromElement == null) { // // moved from outside classpath // currentDelta().added(element); // } else { // currentDelta().movedTo(element, movedFromElement); // } } } } /** * Generic processing for a removed element: * <ul> * <li>Close the element, removing its structure from the cache * <li>Remove the element from its parent's cache of children * <li>Add a REMOVED entry in the delta * </ul> * Delta argument could be null if processing an external JAR change */ private void elementRemoved(OpenableElementImpl element, IResourceDelta delta) { int elementType = element.getElementType(); if (delta == null || (delta.getFlags() & IResourceDelta.MOVED_TO) == 0) { // regular element removal if (isPrimaryWorkingCopy(element, elementType)) { // filter out changes to primary compilation unit in working copy mode // just report a change to the resource (see // https://bugs.eclipse.org/bugs/show_bug.cgi?id=59500) currentDelta().changed(element, DartElementDelta.F_PRIMARY_RESOURCE); } else if (elementType == DartElement.COMPILATION_UNIT && ((CompilationUnit) element).definesLibrary()) { close(element); removeFromParentInfo(element); currentDelta().removed(element.getParent()); currentDelta().removed(element); } else { close(element); removeFromParentInfo(element); currentDelta().removed(element); } } else { // element is moved // TODO This case is not yet supported. // See the JDT code to get started on the various cases } if (elementType == DartElement.DART_PROJECT) { // remember that the project's cache must be reset resetThisProjectCache((DartProjectImpl) element); } } /** * Returns the type of the Dart element the given delta matches to. Returns NON_DART_RESOURCE if * unknown (e.g. a non-dart resource or excluded .dart file) */ private int elementType(IResource res, int kind, int parentType) { switch (parentType) { case DartElement.DART_MODEL: // case of a movedTo or movedFrom project (other cases are handled in processResourceDelta(...) return DartElement.DART_PROJECT; case NON_DART_RESOURCE: case DartElement.DART_PROJECT: default: if (res instanceof IFolder) { return NON_DART_RESOURCE; } else { if (DartCore.isDartLikeFileName(res.getName())) { return DartElement.COMPILATION_UNIT; } else if (DartCore.isHTMLLikeFileName(res.getName())) { return DartElement.HTML_FILE; } } return NON_DART_RESOURCE; } } private void firePostChangeDelta(DartElementDelta deltaToNotify, ElementChangedListener[] listeners, int[] listenerMask, int listenerCount) { // post change deltas if (VERBOSE) { System.out.println("FIRING POST_CHANGE Delta [" + Thread.currentThread() + "]:"); //$NON-NLS-1$//$NON-NLS-2$ System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$ } if (deltaToNotify != null) { // flush now so as to keep listener reactions to post their own deltas for // subsequent iteration flush(); // mark the operation stack has not modifying resources since resource // deltas are being fired // DartModelOperation.setAttribute( // DartModelOperation.HAS_MODIFIED_RESOURCE_ATTR, null); notifyListeners(deltaToNotify, ElementChangedEvent.POST_CHANGE, listeners, listenerMask, listenerCount); } } private void fireReconcileDelta(ElementChangedListener[] listeners, int[] listenerMask, int listenerCount) { DartElementDelta deltaToNotify = mergeDeltas(reconcileDeltas.values()); if (VERBOSE) { System.out.println("FIRING POST_RECONCILE Delta [" + Thread.currentThread() + "]:"); //$NON-NLS-1$//$NON-NLS-2$ System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$ } if (deltaToNotify != null) { // flush now so as to keep listener reactions to post their own deltas for // subsequent iteration reconcileDeltas = new HashMap<CompilationUnit, DartElementDelta>(); notifyListeners(deltaToNotify, ElementChangedEvent.POST_RECONCILE, listeners, listenerMask, listenerCount); } } /** * Using the passed {@link DartLibrary}, this method caches the directives into a * {@link CachedDirectives} object. * <p> * The {@link CachedDirectives} object is returned with the {@link String} directives in the form * <code>[file:/Users/user/dart/HelloWorld/HelloWorld.dart, file:/Users/user/dart/HelloWorld/A.dart]</code>. * * @param library the library to be used when generating the returned {@link CachedDirectives} */ private CachedDirectives getCachedDirectives(DartLibrary library) { try { DartLibrary[] libraries = library.getImportedLibraries(); CompilationUnit[] compilationUnits = library.getCompilationUnits(); DartResource[] dartResources = library.getResources(); if (libraries == null || compilationUnits == null || dartResources == null) { return new CachedDirectives(); } else if (libraries.length == 0 && compilationUnits.length == 0 && dartResources.length == 0) { return new CachedDirectives(); } String libraryName = library.getDisplayName(); Set<String> importsSet = new HashSet<String>(libraries.length); Set<String> sourcesSet = new HashSet<String>(compilationUnits.length + 1); Set<String> resourceSet = new HashSet<String>(dartResources.length); for (int i = 0; i < libraries.length; i++) { DartLibrary lib = libraries[i]; IResource libIResource = lib.getDefiningCompilationUnit().getResource(); if (libIResource != null) { importsSet.add(libIResource.getLocationURI().toString()); } else { // This covers the use case where the imported library is of the form "dart:dom". importsSet.add(lib.getDisplayName()); } } for (int i = 0; i < compilationUnits.length; i++) { CompilationUnit compilationUnit = compilationUnits[i]; if (compilationUnit != null && compilationUnit.getResource() != null) { sourcesSet.add(compilationUnit.getResource().getLocationURI().toString()); } } for (int i = 0; i < dartResources.length; i++) { DartResource dartResource = dartResources[i]; if (dartResource != null && dartResource.getResource() != null) { resourceSet.add(dartResource.getResource().getLocationURI().toString()); } } return new CachedDirectives(libraryName, importsSet, sourcesSet, resourceSet); } catch (DartModelException e) { DartCore.logError( "Exception while attempting to compute the CachedDiectives using some DartLibrary object.", e); } return new CachedDirectives(); } /** * Only called by {@link #contentChanged(DartElementImpl, IResourceDelta)}, this method takes some * {@link IResource} library and uses {@link #parseDirectives(DartSource)} to return the set of * paths (relative to the workspace) of the sources included in the library. * <p> * The {@link CachedDirectives} object is returned with the {@link String} directives in the form * <code>[file:/Users/user/dart/HelloWorld/HelloWorld.dart, file:/Users/user/dart/HelloWorld/A.dart]</code>. * <p> * <code>null</code> can be returned if the the set couldn't be computed. */ private CachedDirectives getCachedDirectives(DartSource dartSrc, DartLibraryImpl library) { String libraryName = null; Set<String> importsSet = new HashSet<String>(); Set<String> sourcesSet = new HashSet<String>(); Set<String> resourcesSet = new HashSet<String>(); try { // TODO(jwren) revisit this, much of the code in parseDirectives is already in DartLibraryImpl, // should we have one method instead of two? CachedDirectives literalCachedDirectives = parseDirectives(dartSrc); LibrarySource librarySrc = dartSrc.getLibrary(); // LIBRARY NAME libraryName = literalCachedDirectives.getLibraryName(); if (libraryName == null || libraryName.length() == 0) { // if there is no #library(..) directive, then use the implicit name, computed in the same // way from DartLibraryImpl#getDisplayName() libraryName = library.getImplicitLibraryName(); } // IMPORTS Set<String> importUriSpecs = literalCachedDirectives.getImports(); for (String importText : importUriSpecs) { if (importText.startsWith("dart:")) { importsSet.add(importText); } else { LibrarySource importedLibSrc = librarySrc.getImportFor(importText); importsSet.add(importedLibSrc.getUri().toString()); } } // SRC Set<String> sourceUriSpecs = literalCachedDirectives.getSources(); for (String sourceText : sourceUriSpecs) { DartSource importedSrcDirective = librarySrc.getSourceFor(sourceText); if (importedSrcDirective != null && importedSrcDirective.exists()) { sourcesSet.add(importedSrcDirective.getUri().toString()); } //else { // TODO(jwren) handle else case- user has referenced a file which isn't linked into the workspace // IPath path = cuIFile.getLocation().removeLastSegments(1).append(new Path(sourceText)); // File srcFile = path.toFile(); // CompilationUnit cu = library.linkSource(srcFile); // if (portableString != null) { // sourcesSet.add(portableString); // } //} } // RES Set<String> resUriSpecs = literalCachedDirectives.getResources(); for (String resourceText : resUriSpecs) { DartSource importedResDirective = librarySrc.getSourceFor(resourceText); if (importedResDirective != null && importedResDirective.exists()) { resourcesSet.add(importedResDirective.getUri().toString()); } //else { // TODO(jwren) handle else case- user has referenced a file which isn't linked into the workspace //} } } catch (Exception e) { DartCore.logError("Failed to process delta for " + dartSrc.getUri().toString(), e); } return new CachedDirectives(libraryName, importsSet, sourcesSet, resourcesSet); } /** * Returns whether the given element is a primary compilation unit in working copy mode. */ private boolean isPrimaryWorkingCopy(DartElement element, int elementType) { if (elementType == DartElement.COMPILATION_UNIT) { CompilationUnit cu = (CompilationUnit) element; return cu.isPrimary() && cu.isWorkingCopy(); } return false; } /** * Merges all awaiting deltas, and returns the merged {@link DartElementDelta}. */ private DartElementDelta mergeDeltas(Collection<DartElementDelta> deltas) { if (deltas.size() == 0) { return null; } if (deltas.size() == 1) { return deltas.iterator().next(); } if (VERBOSE) { System.out.println("MERGING " + deltas.size() + " DELTAS [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } Iterator<DartElementDelta> iterator = deltas.iterator(); DartElementDeltaImpl rootDelta = new DartElementDeltaImpl(manager.getDartModel()); boolean insertedTree = false; while (iterator.hasNext()) { DartElementDeltaImpl delta = (DartElementDeltaImpl) iterator.next(); if (VERBOSE) { System.out.println(delta.toString()); } DartElement element = delta.getElement(); if (manager.getDartModel().equals(element)) { DartElementDelta[] children = delta.getAffectedChildren(); for (int j = 0; j < children.length; j++) { DartElementDeltaImpl projectDelta = (DartElementDeltaImpl) children[j]; rootDelta.insertDeltaTree(projectDelta.getElement(), projectDelta); insertedTree = true; } IResourceDelta[] resourceDeltas = delta.getResourceDeltas(); if (resourceDeltas != null) { for (int i = 0, length = resourceDeltas.length; i < length; i++) { rootDelta.addResourceDelta(resourceDeltas[i]); insertedTree = true; } } } else { rootDelta.insertDeltaTree(element, delta); insertedTree = true; } } if (insertedTree) { return rootDelta; } return null; } /** * This method is used by the JDT, it is left here commented out, for possible future work in this * file regarding non-Dart resource change events. * <p> * Generic processing for elements with changed contents: * <ul> * <li>The element is closed such that any subsequent accesses will re-open the element reflecting * its new structure. * <li>An entry is made in the delta reporting a content change (K_CHANGE with F_CONTENT flag * set). * </ul> */ // private void nonDartResourcesChanged(DartElementImpl element, IResourceDelta delta) // throws DartModelException { // switch (element.getElementType()) { // case DartElement.DART_PROJECT: // currentDelta().addResourceDelta(delta); // return; // } // DartElementDeltaImpl current = currentDelta(); // DartElementDeltaImpl elementDelta = current.find(element); // if (elementDelta == null) { // // don't use find after creating the delta as it can be null (see // // https://bugs.eclipse.org/bugs/show_bug.cgi?id=63434) // elementDelta = current.changed(element, DartElementDelta.F_CONTENT); // } // } /** * Notifies the list of {@link ElementChangedListener}s. The list of listeners is passed from * {@link DeltaProcessingState}. * * @see DeltaProcessingState#elementChangedListeners * @see DeltaProcessingState#elementChangedListenerMasks * @see DeltaProcessingState#elementChangedListenerCount */ private void notifyListeners(DartElementDelta deltaToNotify, int eventType, ElementChangedListener[] listeners, int[] listenerMask, int listenerCount) { final ElementChangedEvent elementChangeEvent = new ElementChangedEvent(deltaToNotify, eventType); for (int i = 0; i < listenerCount; i++) { if ((listenerMask[i] & eventType) != 0) { final ElementChangedListener listener = listeners[i]; long start = -1; if (VERBOSE) { System.out.print("Listener #" + (i + 1) + "=" + listener.toString());//$NON-NLS-1$//$NON-NLS-2$ start = System.currentTimeMillis(); } // wrap callbacks with Safe runnable for subsequent listeners to be // called when some are causing grief SafeRunner.run(new ISafeRunnable() { @Override public void handleException(Throwable exception) { DartCore.logError("Exception occurred in listener of Dart element change notification", //$NON-NLS-1$ exception); } @Override public void run() throws Exception { listener.elementChanged(elementChangeEvent); } }); if (VERBOSE) { System.out.println(" -> " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ } } } } /** * Returns a {@link CachedDirectives} object containing the literal directive {@link String} text * from the passed {@link DartSource}. * <p> * For instance, the {@link CachedDirectives#getSources()} return the sources in the form of * <code>[HelloWorld.dart, B.dart, A.dart]</code>, this is different than the other methods in * this class such as {@link #getCachedDirectives(DartLibrary)} and * {@link #getCachedDirectives(IFile)}. */ private CachedDirectives parseDirectives(DartSource dartSrc) throws IOException, DartModelException { Collection<DartCompilationError> parseErrors = new ArrayList<DartCompilationError>(); Reader reader = dartSrc.getSourceReader(); String contents; boolean readFailed = true; try { contents = FileUtilities.getContents(reader); readFailed = false; } finally { Closeables.close(reader, readFailed); } DartUnit dartUnit = DartCompilerUtilities.parseSource(dartSrc, contents, parseErrors); List<DartDirective> directives = dartUnit.getDirectives(); String libraryName = ""; Set<String> importsSet; Set<String> sourcesSet; Set<String> resourcesSet; if (directives != null) { importsSet = new HashSet<String>(directives.size()); sourcesSet = new HashSet<String>(directives.size() + 1); resourcesSet = new HashSet<String>(directives.size()); for (DartDirective directive : directives) { if (directive instanceof DartSourceDirective) { DartSourceDirective srcDirective = (DartSourceDirective) directive; sourcesSet.add(srcDirective.getSourceUri().getValue()); } else if (directive instanceof DartResourceDirective) { DartResourceDirective resDirective = (DartResourceDirective) directive; resourcesSet.add(resDirective.getResourceUri().getValue()); } else if (directive instanceof DartImportDirective) { DartImportDirective importDirective = (DartImportDirective) directive; importsSet.add(importDirective.getLibraryUri().getValue()); } else if (directive instanceof DartLibraryDirective) { DartLibraryDirective libraryDirective = (DartLibraryDirective) directive; libraryName = libraryDirective.getName().getValue(); } } } else { importsSet = new HashSet<String>(0); sourcesSet = new HashSet<String>(1); resourcesSet = new HashSet<String>(0); } // To match result returned by DartCompiler.analyzeLibrary // include the library itself in the list of sources // See LibraryUnit#getSelfSourcePath() String self = dartSrc.getUri().getSchemeSpecificPart(); int lastSlash = self.lastIndexOf('/'); if (lastSlash > -1) { self = self.substring(lastSlash + 1); } // ensure that the sourcesList doesn't already have self, then add to the list if (!sourcesSet.contains(self)) { sourcesSet.add(self); } return new CachedDirectives(libraryName, importsSet, sourcesSet, resourcesSet); } /** * Converts a <code>IResourceDelta</code> rooted in a <code>Workspace</code> into the * corresponding set of <code>DartElementDelta</code>, rooted in the relevant * <code>DartModelImpl</code>s. */ private DartElementDelta processResourceDelta(IResourceDelta changes) { try { currentElement = null; // get the workspace delta, and start processing there. // TODO(jwren) Can we remove the INCLUDE_HIDDEN flag? it should be tested and then removed IResourceDelta[] deltas = changes.getAffectedChildren(IResourceDelta.ADDED | IResourceDelta.REMOVED | IResourceDelta.CHANGED, IContainer.INCLUDE_HIDDEN); // traverse each delta for (int i = 0; i < deltas.length; i++) { traverseDelta(deltas[i], DartElement.DART_PROJECT); } resetProjectCaches(); return currentDelta; } finally { currentDelta = null; } } private void recomputeLibrarySet(DartElement dartElement) { DartProjectImpl dartProject = (DartProjectImpl) dartElement.getDartProject(); if (!projectHasRecomputedLibrarySet.contains(dartProject.getElementName())) { dartProject.recomputeLibrarySet(); projectHasRecomputedLibrarySet.add(dartProject.getElementName()); } } /** * Removes the given element from its parents cache of children. If the element does not have a * parent, or the parent is not currently open, this has no effect. * * @see #addToParentInfo(OpenableElementImpl) */ private void removeFromParentInfo(OpenableElementImpl child) { OpenableElementImpl parent = (OpenableElementImpl) child.getParent(); if (parent != null && parent.isOpen()) { try { OpenableElementInfo info = (OpenableElementInfo) parent.getElementInfo(); info.removeChild(child); } catch (DartModelException e) { // do nothing - we already checked if open } } } /** * This is called by the {@link DeltaProcessor} when some Dart project has been changed. * <p> * Since the user cannot directly delete, open or close the dart projects, this is currently only * ever called when the user creates (or opens) a new dart library. * <p> * By enforcing all callers of <code>projectCachesToReset.add(..)</code> to use this method, this * method can be used easily for debugging of the project cache story. * * @see DeltaProcessor#resetProjectCaches() * @param dartProjectImpl some non-<code>null</code> dart project * @return <code>true</code> if this set did not already contain the specified element */ private boolean resetThisProjectCache(DartProjectImpl dartProjectImpl) { return projectCachesToReset.add(dartProjectImpl); } /** * Turns the firing mode to on. That is, deltas that are/have been registered will be fired. */ private void startDeltas() { isFiring = true; } /** * Turns the firing mode to off. That is, deltas that are/have been registered will not be fired * until deltas are started again. */ private void stopDeltas() { isFiring = false; } /** * Converts an <code>IResourceDelta</code> and its children into the corresponding * <code>DartElementDelta</code>s. */ private void traverseDelta(IResourceDelta delta, int elementType) { if (DEBUG) { System.out.println("DeltaProcessor.traverseDelta() type = " + delta.getResource().getClass() + ", delta.getResource().getName() = \"" + delta.getResource().getFullPath().toOSString() + "\""); } // process current delta boolean processChildren = updateCurrentDelta(delta, elementType); // process children if needed if (processChildren) { IResourceDelta[] children = delta.getAffectedChildren(); int length = children.length; // for each of the children, also update the current delta, by calling this method recursively for (int i = 0; i < length; i++) { IResourceDelta child = children[i]; IResource childRes = child.getResource(); //////// // Optimization: if a generated dart file, then don't process delta if (childRes instanceof IFile && DartCore.isDartGeneratedFile(childRes.getFileExtension())) { if (VERBOSE) { System.out.println("Not traversing over the following file since it is generated by Dart: " + childRes.getFullPath().toOSString()); } continue; } //////// int childKind = child.getKind(); int childType = elementType(childRes, childKind, elementType); traverseDelta(child, childType); // if (childType == NON_DART_RESOURCE) { // if (parent == null && elementType == DartElement.DART_PROJECT) { // parent = createElement(res, elementType); // } // if (parent == null) { // continue; // } // try { // nonDartResourcesChanged(parent, child); // } catch (DartModelException e) { // } // } } } // else resource delta will be added by parent } /** * Update the current delta (i.e. add/remove/change the given element) and update the * corresponding index. Returns whether the children of the given delta must be processed. * * @return <code>true</code> if the children of the given delta must be processed. * @throws a DartModelException if the delta doesn't correspond to a Dart element of the given * type. */ private boolean updateCurrentDelta(IResourceDelta delta, int elementType) { IResource deltaRes = delta.getResource(); if (DEBUG) { System.out.println("DeltaProcessor.updateCurrentDelta() called for this resource: \"" + deltaRes.getFullPath().toOSString() + "\""); } OpenableElementImpl element; switch (delta.getKind()) { case IResourceDelta.ADDED: element = createElement(deltaRes, elementType); if (element == null) { return true; } recomputeLibrarySet(element); -// elementAdded(element, delta); + elementAdded(element, delta); // // if this element is a CompilationUnit that defines a library, make sure that we specify that the // // DartLibrary is being added // if (elementType == DartElement.COMPILATION_UNIT) { // // if the element is a LibraryConfigurationFile, then we need to post an add of it's parent // if (((CompilationUnit) element).definesLibrary()) { // elementAdded((DartLibraryImpl) element.getParent(), delta); // } // } return false; case IResourceDelta.REMOVED: element = createElement(deltaRes, elementType); if (element == null) { return true; } // If the element being removed is a DartProject, do NOT have its' children visited // recursively, return false. if (element instanceof DartProject) { return false; } recomputeLibrarySet(element); -// elementRemoved(element, delta); + elementRemoved(element, delta); // // if this element is a CompilationUnit that defines a library, make sure that we specify that the // // DartLibrary is being removed // if (elementType == DartElement.COMPILATION_UNIT) { // if (((CompilationUnit) element).definesLibrary()) { // elementRemoved((DartLibraryImpl) element.getParent(), delta); // } // } // Note: the JDT has a special case for projects, we may need some special case as well // later on, the DartModelManager currently doesn't have the equivalent methods //if (deltaRes.getType() == IResource.PROJECT) { //// reset the corresponding project built state, since cannot reuse if added back //... //} return false; case IResourceDelta.CHANGED: int flags = delta.getFlags(); if ((flags & IResourceDelta.CONTENT) != 0 || (flags & IResourceDelta.ENCODING) != 0) { // content or encoding has changed element = createElement(delta.getResource(), elementType); if (element == null) { return true; } recomputeLibrarySet(element); // This has been replaced by the call to recomputeLibrarySet, more a *hammer* approach to // get the Libraries view working ASAP, this could be re-visited in the future to make the // delta processing a faster process. - //contentChanged(element, delta); + contentChanged(element, delta); } // The following has all been commented out as DartProjects cannot be opened or closed in // the current UX (adding and removing libraries is different than closing a project). // else if (elementType == DartElement.DART_PROJECT) { // if ((flags & IResourceDelta.OPEN) != 0) { // // project has been opened or closed // IProject res = (IProject) delta.getResource(); // element = createElement(res, elementType); // if (element == null) { // // resource might be containing shared roots (see bug 19058) // //state.updateRoots(res.getFullPath(), delta, this); // return false; // } // if (res.isOpen()) { // if (DartProjectNature.hasDartNature(res)) { // addToParentInfo(element); // currentDelta().opened(element); // // // remember that the project's cache must be reset // projectCachesToReset.add((DartProjectImpl) element); // } // } else { // boolean wasDartProject = state.findDartProject(res.getName()) != null; // if (wasDartProject) { // close(element); // removeFromParentInfo(element); // currentDelta().closed(element); // } // } // // when a project is opened/closed don't process children // return false; // } // if ((flags & IResourceDelta.DESCRIPTION) != 0) { // IProject res = (IProject) delta.getResource(); // boolean wasDartProject = state.findDartProject(res.getName()) != null; // boolean isDartProject = DartProjectNature.hasDartNature(res); // if (wasDartProject != isDartProject) { // // project's nature has been added or removed // element = createElement(res, elementType); // if (element == null) { // // note its resources are still visible as roots to other projects // return false; // } // if (isDartProject) { // elementAdded(element, delta); // } else { // elementRemoved(element, delta); // } // // when a project's nature is added/removed don't process children // return false; // } // } // } return true; } return true; } }
false
true
private boolean updateCurrentDelta(IResourceDelta delta, int elementType) { IResource deltaRes = delta.getResource(); if (DEBUG) { System.out.println("DeltaProcessor.updateCurrentDelta() called for this resource: \"" + deltaRes.getFullPath().toOSString() + "\""); } OpenableElementImpl element; switch (delta.getKind()) { case IResourceDelta.ADDED: element = createElement(deltaRes, elementType); if (element == null) { return true; } recomputeLibrarySet(element); // elementAdded(element, delta); // // if this element is a CompilationUnit that defines a library, make sure that we specify that the // // DartLibrary is being added // if (elementType == DartElement.COMPILATION_UNIT) { // // if the element is a LibraryConfigurationFile, then we need to post an add of it's parent // if (((CompilationUnit) element).definesLibrary()) { // elementAdded((DartLibraryImpl) element.getParent(), delta); // } // } return false; case IResourceDelta.REMOVED: element = createElement(deltaRes, elementType); if (element == null) { return true; } // If the element being removed is a DartProject, do NOT have its' children visited // recursively, return false. if (element instanceof DartProject) { return false; } recomputeLibrarySet(element); // elementRemoved(element, delta); // // if this element is a CompilationUnit that defines a library, make sure that we specify that the // // DartLibrary is being removed // if (elementType == DartElement.COMPILATION_UNIT) { // if (((CompilationUnit) element).definesLibrary()) { // elementRemoved((DartLibraryImpl) element.getParent(), delta); // } // } // Note: the JDT has a special case for projects, we may need some special case as well // later on, the DartModelManager currently doesn't have the equivalent methods //if (deltaRes.getType() == IResource.PROJECT) { //// reset the corresponding project built state, since cannot reuse if added back //... //} return false; case IResourceDelta.CHANGED: int flags = delta.getFlags(); if ((flags & IResourceDelta.CONTENT) != 0 || (flags & IResourceDelta.ENCODING) != 0) { // content or encoding has changed element = createElement(delta.getResource(), elementType); if (element == null) { return true; } recomputeLibrarySet(element); // This has been replaced by the call to recomputeLibrarySet, more a *hammer* approach to // get the Libraries view working ASAP, this could be re-visited in the future to make the // delta processing a faster process. //contentChanged(element, delta); } // The following has all been commented out as DartProjects cannot be opened or closed in // the current UX (adding and removing libraries is different than closing a project). // else if (elementType == DartElement.DART_PROJECT) { // if ((flags & IResourceDelta.OPEN) != 0) { // // project has been opened or closed // IProject res = (IProject) delta.getResource(); // element = createElement(res, elementType); // if (element == null) { // // resource might be containing shared roots (see bug 19058) // //state.updateRoots(res.getFullPath(), delta, this); // return false; // } // if (res.isOpen()) { // if (DartProjectNature.hasDartNature(res)) { // addToParentInfo(element); // currentDelta().opened(element); // // // remember that the project's cache must be reset // projectCachesToReset.add((DartProjectImpl) element); // } // } else { // boolean wasDartProject = state.findDartProject(res.getName()) != null; // if (wasDartProject) { // close(element); // removeFromParentInfo(element); // currentDelta().closed(element); // } // } // // when a project is opened/closed don't process children // return false; // } // if ((flags & IResourceDelta.DESCRIPTION) != 0) { // IProject res = (IProject) delta.getResource(); // boolean wasDartProject = state.findDartProject(res.getName()) != null; // boolean isDartProject = DartProjectNature.hasDartNature(res); // if (wasDartProject != isDartProject) { // // project's nature has been added or removed // element = createElement(res, elementType); // if (element == null) { // // note its resources are still visible as roots to other projects // return false; // } // if (isDartProject) { // elementAdded(element, delta); // } else { // elementRemoved(element, delta); // } // // when a project's nature is added/removed don't process children // return false; // } // } // } return true; } return true; }
private boolean updateCurrentDelta(IResourceDelta delta, int elementType) { IResource deltaRes = delta.getResource(); if (DEBUG) { System.out.println("DeltaProcessor.updateCurrentDelta() called for this resource: \"" + deltaRes.getFullPath().toOSString() + "\""); } OpenableElementImpl element; switch (delta.getKind()) { case IResourceDelta.ADDED: element = createElement(deltaRes, elementType); if (element == null) { return true; } recomputeLibrarySet(element); elementAdded(element, delta); // // if this element is a CompilationUnit that defines a library, make sure that we specify that the // // DartLibrary is being added // if (elementType == DartElement.COMPILATION_UNIT) { // // if the element is a LibraryConfigurationFile, then we need to post an add of it's parent // if (((CompilationUnit) element).definesLibrary()) { // elementAdded((DartLibraryImpl) element.getParent(), delta); // } // } return false; case IResourceDelta.REMOVED: element = createElement(deltaRes, elementType); if (element == null) { return true; } // If the element being removed is a DartProject, do NOT have its' children visited // recursively, return false. if (element instanceof DartProject) { return false; } recomputeLibrarySet(element); elementRemoved(element, delta); // // if this element is a CompilationUnit that defines a library, make sure that we specify that the // // DartLibrary is being removed // if (elementType == DartElement.COMPILATION_UNIT) { // if (((CompilationUnit) element).definesLibrary()) { // elementRemoved((DartLibraryImpl) element.getParent(), delta); // } // } // Note: the JDT has a special case for projects, we may need some special case as well // later on, the DartModelManager currently doesn't have the equivalent methods //if (deltaRes.getType() == IResource.PROJECT) { //// reset the corresponding project built state, since cannot reuse if added back //... //} return false; case IResourceDelta.CHANGED: int flags = delta.getFlags(); if ((flags & IResourceDelta.CONTENT) != 0 || (flags & IResourceDelta.ENCODING) != 0) { // content or encoding has changed element = createElement(delta.getResource(), elementType); if (element == null) { return true; } recomputeLibrarySet(element); // This has been replaced by the call to recomputeLibrarySet, more a *hammer* approach to // get the Libraries view working ASAP, this could be re-visited in the future to make the // delta processing a faster process. contentChanged(element, delta); } // The following has all been commented out as DartProjects cannot be opened or closed in // the current UX (adding and removing libraries is different than closing a project). // else if (elementType == DartElement.DART_PROJECT) { // if ((flags & IResourceDelta.OPEN) != 0) { // // project has been opened or closed // IProject res = (IProject) delta.getResource(); // element = createElement(res, elementType); // if (element == null) { // // resource might be containing shared roots (see bug 19058) // //state.updateRoots(res.getFullPath(), delta, this); // return false; // } // if (res.isOpen()) { // if (DartProjectNature.hasDartNature(res)) { // addToParentInfo(element); // currentDelta().opened(element); // // // remember that the project's cache must be reset // projectCachesToReset.add((DartProjectImpl) element); // } // } else { // boolean wasDartProject = state.findDartProject(res.getName()) != null; // if (wasDartProject) { // close(element); // removeFromParentInfo(element); // currentDelta().closed(element); // } // } // // when a project is opened/closed don't process children // return false; // } // if ((flags & IResourceDelta.DESCRIPTION) != 0) { // IProject res = (IProject) delta.getResource(); // boolean wasDartProject = state.findDartProject(res.getName()) != null; // boolean isDartProject = DartProjectNature.hasDartNature(res); // if (wasDartProject != isDartProject) { // // project's nature has been added or removed // element = createElement(res, elementType); // if (element == null) { // // note its resources are still visible as roots to other projects // return false; // } // if (isDartProject) { // elementAdded(element, delta); // } else { // elementRemoved(element, delta); // } // // when a project's nature is added/removed don't process children // return false; // } // } // } return true; } return true; }
diff --git a/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java b/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java index f2d2ebb..0f7adbf 100644 --- a/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java +++ b/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java @@ -1,21 +1,23 @@ package com.github.kpacha.jkata.tennis; public class Tennis { private int playerOneScored = 0; private int playerTwoScored = 0; public String getScore() { + if (playerOneScored == 3 && playerTwoScored == 3) + return "Deuce"; if (playerOneScored == 4) return "Player 1 wins"; return (15 * playerOneScored) + " - " + (15 * playerTwoScored); } public void playerOneScores() { playerOneScored++; } public void playerTwoScores() { playerTwoScored++; } }
true
true
public String getScore() { if (playerOneScored == 4) return "Player 1 wins"; return (15 * playerOneScored) + " - " + (15 * playerTwoScored); }
public String getScore() { if (playerOneScored == 3 && playerTwoScored == 3) return "Deuce"; if (playerOneScored == 4) return "Player 1 wins"; return (15 * playerOneScored) + " - " + (15 * playerTwoScored); }
diff --git a/src/main/java/org/spout/api/command/CommandContext.java b/src/main/java/org/spout/api/command/CommandContext.java index 9916b5152..cd2de31d4 100644 --- a/src/main/java/org/spout/api/command/CommandContext.java +++ b/src/main/java/org/spout/api/command/CommandContext.java @@ -1,385 +1,385 @@ /* * This file is part of SpoutAPI. * * Copyright (c) 2011-2012, Spout LLC <http://www.spout.org/> * SpoutAPI is licensed under the Spout License Version 1. * * SpoutAPI 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. * * In addition, 180 days after any changes are published, you can use the * software, incorporating those changes, under the terms of the MIT license, * as described in the Spout License Version 1. * * SpoutAPI 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, * the MIT license and the Spout License Version 1 along with this program. * If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public * License and see <http://spout.in/licensev1> for the full license, including * the MIT license. */ package org.spout.api.command; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.spout.api.Server; import org.spout.api.Spout; import org.spout.api.chat.ChatArguments; import org.spout.api.chat.ChatSection; import org.spout.api.exception.CommandException; import org.spout.api.geo.World; import org.spout.api.entity.Player; import org.spout.api.plugin.Platform; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TCharObjectMap; import gnu.trove.map.hash.TCharObjectHashMap; import gnu.trove.set.TCharSet; import gnu.trove.set.hash.TCharHashSet; /** * This class serves as a wrapper for command arguments. It also provides * boolean and value flag parsing and several command helper methods. */ public class CommandContext { protected final String command; protected final List<ChatSection> parsedArgs; protected final TIntList originalArgIndices; protected final List<ChatSection> originalArgs; protected final TCharSet booleanFlags = new TCharHashSet(); protected final TCharObjectMap<ChatSection> valueFlags = new TCharObjectHashMap<ChatSection>(); public CommandContext(String command, List<ChatSection> args) throws CommandException { this(command, args, null); } /** * @param command The command name used * @param args An array with arguments. Empty strings outside quotes will be * removed. * @param valueFlags A set containing all value flags. Pass null to disable * value flag parsing. * @throws CommandException This is thrown if flag fails for some reason. */ public CommandContext(String command, List<ChatSection> args, TCharSet valueFlags) throws CommandException { if (valueFlags == null) { valueFlags = new TCharHashSet(); } originalArgs = args; this.command = command; // Eliminate empty args and combine multiword args first TIntList argIndexList = new TIntArrayList(args.size()); List<ChatSection> argList = new ArrayList<ChatSection>(args.size()); for (int i = 0; i < args.size(); ++i) { ChatSection arg = args.get(i); if (arg.length() == 0) { continue; } argIndexList.add(i); switch (arg.getPlainString().charAt(0)) { case '\'': case '"': final ChatArguments build = new ChatArguments(); final char quotedChar = arg.getPlainString().charAt(0); int endIndex; for (endIndex = i; endIndex < args.size(); ++endIndex) { final ChatSection arg2 = args.get(endIndex); if (arg2.length() == 0) { continue; } if (arg2.getPlainString().charAt(arg2.length() - 1) == quotedChar) { if (endIndex != i) { build.append(' '); } if (endIndex == i && arg2.length() < 2) { continue; } - build.append(arg2.subSection(endIndex == i ? 1 : 0,arg2.length() - 2)); + build.append(arg2.subSection(endIndex == i ? 1 : 0, arg2.length() - 2)); break; } else if (endIndex == i) { build.append(arg2.subSection(1, arg2.length() - 1)); } else { build.append(' ').append(arg2); } } if (endIndex < args.size()) { arg = build.toSections(ChatSection.SplitType.ALL).get(0); i = endIndex; } // else raise exception about hanging quotes? } argList.add(arg); } // Then flags originalArgIndices = new TIntArrayList(argIndexList.size()); parsedArgs = new ArrayList<ChatSection>(argList.size()); for (int nextArg = 0; nextArg < argList.size();) { // Fetch argument ChatSection arg = argList.get(nextArg++); String plainArg = arg.getPlainString(); // Not a flag? if (plainArg.charAt(0) != '-' || plainArg.length() == 1 || !plainArg.matches("^-[a-zA-Z]+$")) { originalArgIndices.add(argIndexList.get(nextArg - 1)); parsedArgs.add(arg); continue; } // Handle flag parsing terminator -- if (arg.getPlainString().equals("--")) { while (nextArg < argList.size()) { originalArgIndices.add(argIndexList.get(nextArg)); parsedArgs.add(argList.get(nextArg++)); } break; } // Go through the flag characters for (int i = 1; i < arg.getPlainString().length(); ++i) { char flagName = arg.getPlainString().charAt(i); if (valueFlags.contains(flagName)) { if (this.valueFlags.containsKey(flagName)) { throw new CommandException("Value flag '" + flagName + "' already given"); } if (nextArg >= argList.size()) { throw new CommandException("No value specified for the '-" + flagName + "' flag."); } // If it is a value flag, read another argument and add it this.valueFlags.put(flagName, argList.get(nextArg++)); } else { booleanFlags.add(flagName); } } } } public int length() { return parsedArgs.size(); } public String getCommand() { return command; } public int getInteger(int index) throws NumberFormatException { return Integer.parseInt(getString(index)); } public int getInteger(int index, int def) throws NumberFormatException { return index < parsedArgs.size() ? Integer.parseInt(parsedArgs.get(index).getPlainString()) : def; } public boolean isInteger(int index) { if (index >= parsedArgs.size()) { return false; } try { Integer.parseInt(parsedArgs.get(index).getPlainString()); return true; } catch (NumberFormatException e) { return false; } } public World getWorld(int index) { return Spout.getEngine().getWorld(getString(index)); } public World getWorld(int index, boolean exact) { return Spout.getEngine().getWorld(getString(index), exact); } public Player getPlayer(int index, boolean exact) { Platform p = Spout.getPlatform(); if (p != Platform.SERVER && p != Platform.PROXY) { throw new IllegalStateException("You can only match players in server mode."); } return ((Server) Spout.getEngine()).getPlayer(getString(index), exact); } public Collection<World> matchWorld(int index) { return Spout.getEngine().matchWorld(getString(index)); } public Collection<Player> matchPlayer(int index) { Platform p = Spout.getPlatform(); if (p != Platform.SERVER && p != Platform.PROXY) { throw new IllegalStateException("You can only match players in server mode."); } return ((Server) Spout.getEngine()).matchPlayer(getString(index)); } public double getDouble(int index) throws NumberFormatException { return Double.parseDouble(getString(index)); } public double getDouble(int index, double def) throws NumberFormatException { return index < parsedArgs.size() ? Double.parseDouble(parsedArgs.get(index).getPlainString()) : def; } public boolean isDouble(int index) { if (index >= parsedArgs.size()) { return false; } try { Double.parseDouble(parsedArgs.get(index).getPlainString()); return true; } catch (NumberFormatException e) { return false; } } public float getFloat(int index) throws NumberFormatException { return Float.parseFloat(getString(index)); } public float getFloat(int index, float def) throws NumberFormatException { return index < parsedArgs.size() ? Float.parseFloat(parsedArgs.get(index).getPlainString()) : def; } public boolean isFloat(int index) { if (index >= parsedArgs.size()) { return false; } try { Float.parseFloat(parsedArgs.get(index).getPlainString()); return true; } catch (NumberFormatException e) { return false; } } public ChatSection get(int index) { return parsedArgs.get(index); } public ChatSection get(int index, ChatSection def) { return index < parsedArgs.size() ? parsedArgs.get(index) : def; } public String getString(int index) { return parsedArgs.get(index).getPlainString(); } public String getString(int index, String def) { return index < parsedArgs.size() ? parsedArgs.get(index).getPlainString() : def; } public boolean hasFlag(char ch) { return booleanFlags.contains(ch) || valueFlags.containsKey(ch); } public TCharSet getFlags() { return booleanFlags; } public TCharObjectMap<ChatSection> getValueFlags() { return valueFlags; } public ChatSection getFlag(char ch) { return valueFlags.get(ch); } public ChatSection getFlag(char ch, ChatSection def) { final ChatSection value = valueFlags.get(ch); if (value == null) { return def; } return value; } public String getFlagString(char ch) { ChatSection sect = valueFlags.get(ch); return sect == null ? null : sect.getPlainString(); } public String getFlagString(char ch, String def) { final ChatSection value = valueFlags.get(ch); if (value == null) { return def; } return value.getPlainString(); } public int getFlagInteger(char ch) throws NumberFormatException { return Integer.parseInt(getFlagString(ch)); } public int getFlagInteger(char ch, int def) throws NumberFormatException { final ChatSection value = valueFlags.get(ch); if (value == null) { return def; } return Integer.parseInt(value.getPlainString()); } public boolean isFlagInteger(char ch) { try { Integer.parseInt(getFlagString(ch)); return true; } catch (NumberFormatException e) { return false; } } public double getFlagDouble(char ch) throws NumberFormatException { return Double.parseDouble(getFlagString(ch)); } public double getFlagDouble(char ch, double def) throws NumberFormatException { final ChatSection value = valueFlags.get(ch); if (value == null) { return def; } return Double.parseDouble(value.getPlainString()); } public boolean isFlagDouble(char ch) { try { Double.parseDouble(getFlagString(ch)); return true; } catch (NumberFormatException e) { return false; } } public ChatArguments getJoinedString(int initialIndex) { initialIndex = originalArgIndices.get(initialIndex); ChatArguments args = new ChatArguments(originalArgs.get(initialIndex)); for (int i = initialIndex + 1; i < originalArgs.size(); ++i) { args.append(" ").append(originalArgs.get(i)); } return args; } public List<ChatSection> getRawArgs() { return Collections.unmodifiableList(originalArgs); } }
true
true
public CommandContext(String command, List<ChatSection> args, TCharSet valueFlags) throws CommandException { if (valueFlags == null) { valueFlags = new TCharHashSet(); } originalArgs = args; this.command = command; // Eliminate empty args and combine multiword args first TIntList argIndexList = new TIntArrayList(args.size()); List<ChatSection> argList = new ArrayList<ChatSection>(args.size()); for (int i = 0; i < args.size(); ++i) { ChatSection arg = args.get(i); if (arg.length() == 0) { continue; } argIndexList.add(i); switch (arg.getPlainString().charAt(0)) { case '\'': case '"': final ChatArguments build = new ChatArguments(); final char quotedChar = arg.getPlainString().charAt(0); int endIndex; for (endIndex = i; endIndex < args.size(); ++endIndex) { final ChatSection arg2 = args.get(endIndex); if (arg2.length() == 0) { continue; } if (arg2.getPlainString().charAt(arg2.length() - 1) == quotedChar) { if (endIndex != i) { build.append(' '); } if (endIndex == i && arg2.length() < 2) { continue; } build.append(arg2.subSection(endIndex == i ? 1 : 0,arg2.length() - 2)); break; } else if (endIndex == i) { build.append(arg2.subSection(1, arg2.length() - 1)); } else { build.append(' ').append(arg2); } } if (endIndex < args.size()) { arg = build.toSections(ChatSection.SplitType.ALL).get(0); i = endIndex; } // else raise exception about hanging quotes? } argList.add(arg); } // Then flags originalArgIndices = new TIntArrayList(argIndexList.size()); parsedArgs = new ArrayList<ChatSection>(argList.size()); for (int nextArg = 0; nextArg < argList.size();) { // Fetch argument ChatSection arg = argList.get(nextArg++); String plainArg = arg.getPlainString(); // Not a flag? if (plainArg.charAt(0) != '-' || plainArg.length() == 1 || !plainArg.matches("^-[a-zA-Z]+$")) { originalArgIndices.add(argIndexList.get(nextArg - 1)); parsedArgs.add(arg); continue; } // Handle flag parsing terminator -- if (arg.getPlainString().equals("--")) { while (nextArg < argList.size()) { originalArgIndices.add(argIndexList.get(nextArg)); parsedArgs.add(argList.get(nextArg++)); } break; } // Go through the flag characters for (int i = 1; i < arg.getPlainString().length(); ++i) { char flagName = arg.getPlainString().charAt(i); if (valueFlags.contains(flagName)) { if (this.valueFlags.containsKey(flagName)) { throw new CommandException("Value flag '" + flagName + "' already given"); } if (nextArg >= argList.size()) { throw new CommandException("No value specified for the '-" + flagName + "' flag."); } // If it is a value flag, read another argument and add it this.valueFlags.put(flagName, argList.get(nextArg++)); } else { booleanFlags.add(flagName); } } } }
public CommandContext(String command, List<ChatSection> args, TCharSet valueFlags) throws CommandException { if (valueFlags == null) { valueFlags = new TCharHashSet(); } originalArgs = args; this.command = command; // Eliminate empty args and combine multiword args first TIntList argIndexList = new TIntArrayList(args.size()); List<ChatSection> argList = new ArrayList<ChatSection>(args.size()); for (int i = 0; i < args.size(); ++i) { ChatSection arg = args.get(i); if (arg.length() == 0) { continue; } argIndexList.add(i); switch (arg.getPlainString().charAt(0)) { case '\'': case '"': final ChatArguments build = new ChatArguments(); final char quotedChar = arg.getPlainString().charAt(0); int endIndex; for (endIndex = i; endIndex < args.size(); ++endIndex) { final ChatSection arg2 = args.get(endIndex); if (arg2.length() == 0) { continue; } if (arg2.getPlainString().charAt(arg2.length() - 1) == quotedChar) { if (endIndex != i) { build.append(' '); } if (endIndex == i && arg2.length() < 2) { continue; } build.append(arg2.subSection(endIndex == i ? 1 : 0, arg2.length() - 2)); break; } else if (endIndex == i) { build.append(arg2.subSection(1, arg2.length() - 1)); } else { build.append(' ').append(arg2); } } if (endIndex < args.size()) { arg = build.toSections(ChatSection.SplitType.ALL).get(0); i = endIndex; } // else raise exception about hanging quotes? } argList.add(arg); } // Then flags originalArgIndices = new TIntArrayList(argIndexList.size()); parsedArgs = new ArrayList<ChatSection>(argList.size()); for (int nextArg = 0; nextArg < argList.size();) { // Fetch argument ChatSection arg = argList.get(nextArg++); String plainArg = arg.getPlainString(); // Not a flag? if (plainArg.charAt(0) != '-' || plainArg.length() == 1 || !plainArg.matches("^-[a-zA-Z]+$")) { originalArgIndices.add(argIndexList.get(nextArg - 1)); parsedArgs.add(arg); continue; } // Handle flag parsing terminator -- if (arg.getPlainString().equals("--")) { while (nextArg < argList.size()) { originalArgIndices.add(argIndexList.get(nextArg)); parsedArgs.add(argList.get(nextArg++)); } break; } // Go through the flag characters for (int i = 1; i < arg.getPlainString().length(); ++i) { char flagName = arg.getPlainString().charAt(i); if (valueFlags.contains(flagName)) { if (this.valueFlags.containsKey(flagName)) { throw new CommandException("Value flag '" + flagName + "' already given"); } if (nextArg >= argList.size()) { throw new CommandException("No value specified for the '-" + flagName + "' flag."); } // If it is a value flag, read another argument and add it this.valueFlags.put(flagName, argList.get(nextArg++)); } else { booleanFlags.add(flagName); } } } }
diff --git a/src/com/github/egonw/rednael/LeanderBot.java b/src/com/github/egonw/rednael/LeanderBot.java index 203bdf6..c853031 100644 --- a/src/com/github/egonw/rednael/LeanderBot.java +++ b/src/com/github/egonw/rednael/LeanderBot.java @@ -1,161 +1,162 @@ /* Copyright (C) 2009 Egon Willighagen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.github.egonw.rednael; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.jibble.pircbot.IrcException; import org.jibble.pircbot.NickAlreadyInUseException; import org.jibble.pircbot.PircBot; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.fetcher.FeedFetcher; import com.sun.syndication.fetcher.FetcherException; import com.sun.syndication.fetcher.impl.FeedFetcherCache; import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache; import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher; import com.sun.syndication.io.FeedException; public class LeanderBot extends PircBot { /** * Keeps track of the latest entries. */ private List<Channel> channels; private FeedFetcherCache feedInfoCache; private FeedFetcher fetcher; public LeanderBot() throws NickAlreadyInUseException, IOException, IrcException { - this.setName("hadhadhadhadhadhadhadhadhad"); +// this.setName("hadhadhadhadhadhadhadhadhad"); + this.setName("rednael"); this.setVerbose(true); this.connect("irc.freenode.net"); this.channels = new ArrayList<Channel>(); Channel cdk = new Channel("#cdk"); String branch = "cdk-1.2.x"; cdk.addFeed(branch, new URL( "http://cdk.git.sourceforge.net/git/gitweb.cgi?p=cdk;a=rss;h=refs/heads/" + branch )); branch = "master"; cdk.addFeed(branch, new URL( "http://cdk.git.sourceforge.net/git/gitweb.cgi?p=cdk;a=rss;h=refs/heads/" + branch )); cdk.addFeed("CDK Twitter", new URL( "http://search.twitter.com/search.atom?q=%23cdk" )); addChannel(cdk); Channel bioclipse = new Channel("#bioclipse"); bioclipse.addFeed("Leander Git", new URL( "http://github.com/feeds/egonw/commits/rednael/master" )); bioclipse.addFeed("Planet Bioclipse", new URL( "http://pele.farmbio.uu.se/planetbioclipse/atom.xml" )); bioclipse.addFeed("Bioclipse Twitter", new URL( "http://search.twitter.com/search.atom?q=%23bioclipse" )); addChannel(bioclipse); Channel metware = new Channel("#metware"); metware.addFeed("Metware Twitter", new URL( "http://search.twitter.com/search.atom?q=%23metware" )); addChannel(metware); feedInfoCache = HashMapFeedInfoCache.getInstance(); fetcher = new HttpURLFeedFetcher(feedInfoCache); } private void addChannel(Channel channel) { this.channels.add(channel); this.joinChannel(channel.getName()); } private void boot() throws IllegalArgumentException, IOException, FeedException, FetcherException { for (Channel channel : channels) { for (Feed chFeed : channel.getFeeds()) { SyndFeed feed = null; feed = fetcher.retrieveFeed(chFeed.getURL()); int itemCount = 0; List<SyndEntry> entries = feed.getEntries(); for (SyndEntry entry : entries) { itemCount++; String link = entry.getLink(); chFeed.addInitial(link); } } } } private void update() { for (Channel channel : channels) { for (Feed chFeed : channel.getFeeds()) { try { SyndFeed feed = null; System.out.println("Feed url: " + chFeed.getURL()); feed = fetcher.retrieveFeed(chFeed.getURL()); List<SyndEntry> entries = feed.getEntries(); for (SyndEntry entry : entries) { String title = entry.getTitle(); String link = entry.getLink(); if (!chFeed.contains(link)) { chFeed.add(link); StringBuffer message = new StringBuffer(); message.append('[').append(chFeed.getLabel()).append("] "); message.append(title); String author = entry.getAuthor(); if (author.indexOf('<') != -1) { author = author.substring(0, author.indexOf('<')); } message.append(" ").append(link); sendMessage(channel.getName(), message.toString()); Thread.sleep(2000); } } } catch (Exception exception) { exception.printStackTrace(); } } } } public void onMessage(String channel, String sender, String login, String hostname, String message) { } public static void main(String[] args) throws Exception { LeanderBot bot = new LeanderBot(); bot.boot(); Random random = new Random(); while (bot.isConnected()) { bot.update(); Thread.sleep(55000 + random.nextInt(10000)); } } }
true
true
public LeanderBot() throws NickAlreadyInUseException, IOException, IrcException { this.setName("hadhadhadhadhadhadhadhadhad"); this.setVerbose(true); this.connect("irc.freenode.net"); this.channels = new ArrayList<Channel>(); Channel cdk = new Channel("#cdk"); String branch = "cdk-1.2.x"; cdk.addFeed(branch, new URL( "http://cdk.git.sourceforge.net/git/gitweb.cgi?p=cdk;a=rss;h=refs/heads/" + branch )); branch = "master"; cdk.addFeed(branch, new URL( "http://cdk.git.sourceforge.net/git/gitweb.cgi?p=cdk;a=rss;h=refs/heads/" + branch )); cdk.addFeed("CDK Twitter", new URL( "http://search.twitter.com/search.atom?q=%23cdk" )); addChannel(cdk); Channel bioclipse = new Channel("#bioclipse"); bioclipse.addFeed("Leander Git", new URL( "http://github.com/feeds/egonw/commits/rednael/master" )); bioclipse.addFeed("Planet Bioclipse", new URL( "http://pele.farmbio.uu.se/planetbioclipse/atom.xml" )); bioclipse.addFeed("Bioclipse Twitter", new URL( "http://search.twitter.com/search.atom?q=%23bioclipse" )); addChannel(bioclipse); Channel metware = new Channel("#metware"); metware.addFeed("Metware Twitter", new URL( "http://search.twitter.com/search.atom?q=%23metware" )); addChannel(metware); feedInfoCache = HashMapFeedInfoCache.getInstance(); fetcher = new HttpURLFeedFetcher(feedInfoCache); }
public LeanderBot() throws NickAlreadyInUseException, IOException, IrcException { // this.setName("hadhadhadhadhadhadhadhadhad"); this.setName("rednael"); this.setVerbose(true); this.connect("irc.freenode.net"); this.channels = new ArrayList<Channel>(); Channel cdk = new Channel("#cdk"); String branch = "cdk-1.2.x"; cdk.addFeed(branch, new URL( "http://cdk.git.sourceforge.net/git/gitweb.cgi?p=cdk;a=rss;h=refs/heads/" + branch )); branch = "master"; cdk.addFeed(branch, new URL( "http://cdk.git.sourceforge.net/git/gitweb.cgi?p=cdk;a=rss;h=refs/heads/" + branch )); cdk.addFeed("CDK Twitter", new URL( "http://search.twitter.com/search.atom?q=%23cdk" )); addChannel(cdk); Channel bioclipse = new Channel("#bioclipse"); bioclipse.addFeed("Leander Git", new URL( "http://github.com/feeds/egonw/commits/rednael/master" )); bioclipse.addFeed("Planet Bioclipse", new URL( "http://pele.farmbio.uu.se/planetbioclipse/atom.xml" )); bioclipse.addFeed("Bioclipse Twitter", new URL( "http://search.twitter.com/search.atom?q=%23bioclipse" )); addChannel(bioclipse); Channel metware = new Channel("#metware"); metware.addFeed("Metware Twitter", new URL( "http://search.twitter.com/search.atom?q=%23metware" )); addChannel(metware); feedInfoCache = HashMapFeedInfoCache.getInstance(); fetcher = new HttpURLFeedFetcher(feedInfoCache); }
diff --git a/BasicCommands/src/info/tregmine/basiccommands/BasicCommands.java b/BasicCommands/src/info/tregmine/basiccommands/BasicCommands.java index 10429c2..2d96d6c 100644 --- a/BasicCommands/src/info/tregmine/basiccommands/BasicCommands.java +++ b/BasicCommands/src/info/tregmine/basiccommands/BasicCommands.java @@ -1,557 +1,557 @@ package info.tregmine.basiccommands; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.FireworkEffect; //import org.bukkit.FireworkEffect; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.World; //import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; //import org.bukkit.entity.CreatureType; //import org.bukkit.entity.Chicken; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; //import org.bukkit.entity.Firework; //import org.bukkit.entity.Firework; //import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Monster; //import org.bukkit.Color; import org.bukkit.entity.Player; import org.bukkit.entity.Slime; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.entity.EnderDragon; //import org.bukkit.inventory.ItemStack; //import org.bukkit.inventory.meta.FireworkMeta; import info.tregmine.Tregmine; import info.tregmine.api.TregminePlayer; //import info.tregmine.api.TregminePlayer; public class BasicCommands extends JavaPlugin { public final Logger log = Logger.getLogger("Minecraft"); public Tregmine tregmine = null; // public Map<String, FireworkEffect.Builder> fireWorkEffect = new HashMap<String, FireworkEffect.Builder>(); // public Map<String, FireworkMeta> fireWorkMeta = new HashMap<String, FireworkMeta>(); // public Map<String, ItemStack> fireWork = new HashMap<String, ItemStack>(); // public Map<String, Boolean> property = new HashMap<String, Boolean>(); public Map<String, info.tregmine.api.firework.createFirework> firework = new HashMap<String, info.tregmine.api.firework.createFirework>(); @Override public void onEnable(){ Plugin test = this.getServer().getPluginManager().getPlugin("Tregmine"); if(this.tregmine == null) { if(test != null) { this.tregmine = ((Tregmine)test); } else { log.info(this.getDescription().getName() + " " + this.getDescription().getVersion() + " - could not find Tregmine"); this.getServer().getPluginManager().disablePlugin(this); } } getServer().getPluginManager().registerEvents(new BasicCommandsBlock(this), this); } @Override public void onDisable(){ } @Override public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { String commandName = command.getName().toLowerCase(); if(!(sender instanceof Player)) { if (commandName.matches("kick")) { Player victim = this.getServer().matchPlayer(args[0]).get(0); if (victim != null) { info.tregmine.api.TregminePlayer victimPlayer = this.tregmine.tregminePlayer.get(victim.getName()); this.getServer().broadcastMessage("GOD kicked " + victimPlayer.getChatName() + ChatColor.AQUA + " for 1 min."); victim.kickPlayer("kicked by GOD."); } return true; } return false; } final Player player = (Player) sender; info.tregmine.api.TregminePlayer tregminePlayer = this.tregmine.tregminePlayer.get(player.getName()); boolean isAdmin = tregminePlayer.isAdmin(); boolean isDonator = tregminePlayer.isDonator(); boolean isMentor = tregminePlayer.getMetaBoolean("mentor"); if (commandName.matches("fw")) { } if (commandName.matches("keyword")) { if (args.length != 1) { return false; } if (args[0].length() < 1) { tregminePlayer.sendMessage(ChatColor.RED + "Your keyword must be at least " + "1 characters long."); return true; } tregminePlayer.setMetaString("keyword", args[0].toLowerCase()); tregminePlayer.sendMessage(ChatColor.YELLOW + "From now on you can only log in by using ip " + args[0].toLowerCase() + ".mc.tregmine.info"); return true; } if (commandName.matches("password")) { if (args.length != 1) { return false; } if (args[0].length() < 6) { tregminePlayer.sendMessage(ChatColor.RED + "Your password must be at least " + "6 characters long."); return true; } tregminePlayer.setPassword(args[0]); tregminePlayer.sendMessage(ChatColor.YELLOW + "Your password has been changed."); return true; } if (commandName.matches("creative") && (tregminePlayer.isAdmin() || tregminePlayer.getMetaBoolean("builder"))) { final TregminePlayer tregPlayer = tregmine.getPlayer(player); tregPlayer.setGameMode(GameMode.CREATIVE); tregPlayer.sendMessage(ChatColor.YELLOW + "You are now in creative mode."); } if (commandName.matches("survival") && (tregminePlayer.isAdmin() || tregminePlayer.getMetaBoolean("builder"))) { final TregminePlayer tregPlayer = tregmine.getPlayer(player); tregPlayer.setGameMode(GameMode.SURVIVAL); tregPlayer.sendMessage(ChatColor.YELLOW + "You are now in survival mode."); } if (commandName.matches("pos")) { Location loc = player.getLocation(); Location spawn = player.getWorld().getSpawnLocation(); double distance = info.tregmine.api.math.Distance.calc2d(spawn, loc); player.sendMessage(ChatColor.DARK_AQUA + "World: " + ChatColor.WHITE + player.getWorld().getName()); this.log.info("World: " + player.getWorld().getName()); player.sendMessage(ChatColor.DARK_AQUA + "X: " + ChatColor.WHITE + loc.getX() + ChatColor.RED + " (" + loc.getBlockX() + ")" ); this.log.info("X: " + loc.getX() + " (" + loc.getBlockX() + ")" ); player.sendMessage(ChatColor.DARK_AQUA + "Y: " + ChatColor.WHITE + loc.getY() + ChatColor.RED + " (" + loc.getBlockY() + ")" ); this.log.info("Y: " + loc.getY() + " (" + loc.getBlockY() + ")" ); player.sendMessage(ChatColor.DARK_AQUA + "Z: " + ChatColor.WHITE + loc.getZ() + ChatColor.RED + " (" + loc.getBlockZ() + ")" ); this.log.info("Z: " + loc.getZ() + " (" + loc.getBlockZ() + ")" ); player.sendMessage(ChatColor.DARK_AQUA + "Yaw: " + ChatColor.WHITE + loc.getYaw()); this.log.info("Yaw: " + loc.getYaw()); player.sendMessage(ChatColor.DARK_AQUA + "Pitch: " + ChatColor.WHITE + loc.getPitch()); this.log.info("Pitch: " + loc.getPitch() ); player.sendMessage(ChatColor.DARK_AQUA + "Blocks from spawn: " + ChatColor.WHITE + distance); return true; } if (commandName.matches("cname") && tregminePlayer.isAdmin()) { ChatColor color = ChatColor.getByChar(args[0]); tregminePlayer.setTemporaryChatName(color + args[1]); tregminePlayer.sendMessage("You are now: " + tregminePlayer.getChatName()); this.log.info(tregminePlayer.getName() + "changed name to" + tregminePlayer.getChatName()); } if (commandName.matches("t") && tregminePlayer.isAdmin()) { Player victim = this.getServer().matchPlayer(args[0]).get(0); victim.getWorld().strikeLightningEffect(victim.getLocation()); return true; } if (commandName.matches("td") && tregminePlayer.isOp()) { Player victim = this.getServer().matchPlayer(args[0]).get(0); victim.getWorld().strikeLightningEffect(victim.getLocation()); victim.setHealth(0); return true; } if (commandName.matches("time") && tregminePlayer.isDonator()) { if (args.length == 1) { if (args[0].matches("day")) { player.setPlayerTime(6000, false); } else if (args[0].matches("night")) { player.setPlayerTime(18000, false); } else if (args[0].matches("normal")) { player.resetPlayerTime(); } } else { player.sendMessage(ChatColor.YELLOW + "Say /time day|night|normal"); } log.info(player.getName() + "TIME"); return true; } if (commandName.matches("tpblock") && isDonator) { - if (args[0].matches("on")) { + if ("on".matches(args[0])) { tregminePlayer.setMetaString("tpblock", "true"); player.sendMessage("Teleportation is now blocked to you."); return true; } - if (args[0].matches("off")) { + if ("off".matches(args[0])) { tregminePlayer.setMetaString("tpblock", "false"); player.sendMessage("Teleportation is now allowed to you."); return true; } - if (args[0].matches("status")) { + if ("status".matches(args[0])) { player.sendMessage("Your tpblock is set to " + tregminePlayer.getMetaString("tpblock") + "."); return true; } player.sendMessage(ChatColor.RED + "The commands are /tpblock on, /tpblock off and /tpblock status."); return true; } if (commandName.matches("normal")) { info.tregmine.api.TregminePlayer tregPlayer = this.tregmine.tregminePlayer.get(player.getName()); if (isAdmin) { tregPlayer.setTempMetaString("admin", "false"); tregPlayer.setTemporaryChatName(ChatColor.GOLD + tregPlayer.getName()); player.sendMessage(ChatColor.YELLOW + "You are no longer admin, until you reconnect!"); } else if (tregPlayer.getMetaBoolean("builder")) { tregPlayer.setTempMetaString("builder", "false"); tregPlayer.setTemporaryChatName(ChatColor.GOLD + tregPlayer.getName()); player.sendMessage(ChatColor.YELLOW + "You are no longer builder, until you reconnect!"); } else if (tregPlayer.isGuardian()) { Player[] players = tregmine.getServer().getOnlinePlayers(); TregminePlayer maxRank = null; for (Player srvPlayer : players) { TregminePlayer guardian = tregmine.getPlayer(srvPlayer); if (!guardian.isGuardian()) { continue; } TregminePlayer.GuardianState state = guardian.getGuardianState(); if (state == TregminePlayer.GuardianState.QUEUED) { if (maxRank == null || guardian.getGuardianRank() > maxRank.getGuardianRank()) { maxRank = guardian; } } } if (maxRank != null) { tregPlayer.setGuardianState(TregminePlayer.GuardianState.INACTIVE); tregPlayer.sendMessage(ChatColor.BLUE + "You are now in normal mode, and no longer have to response to help requests."); maxRank.setGuardianState(TregminePlayer.GuardianState.ACTIVE); maxRank.sendMessage(ChatColor.BLUE + "You are now on active duty and should respond to help requests."); } else { tregPlayer.sendMessage(ChatColor.BLUE + "Not enough guardians are on to manage the server. We need you to keep working. Sorry. :/"); } } return true; } info.tregmine.api.TregminePlayer tP = this.tregmine.tregminePlayer.get(player.getName()); if (commandName.matches("nuke") && (tP.isGuardian() || tP.isAdmin())) { player.sendMessage("You nuked all mobs in this world!"); for (Entity ent : player.getWorld().getLivingEntities()) { if(ent instanceof Monster) { Monster mob = (Monster) ent; mob.setHealth(0); } // if(ent instanceof Chicken) { // Chicken chicken = (Chicken) ent; // chicken.setHealth(0); // } if(ent instanceof org.bukkit.entity.Animals) { org.bukkit.entity.Animals animal = (org.bukkit.entity.Animals) ent; animal.setHealth(0); } if(ent instanceof Slime) { Slime slime = (Slime) ent; slime.setHealth(0); } if (ent instanceof EnderDragon) { EnderDragon dragon = (EnderDragon)ent; dragon.setHealth(0); } } return true; } if (commandName.matches("user") && args.length > 0 && (isAdmin || isMentor)) { if (args[0].matches("reload")) { this.tregmine.tregminePlayer.get(this.getServer().matchPlayer(args[1]).get(0).getDisplayName()).load(); player.sendMessage("Player reloaded "+ this.getServer().matchPlayer(args[1]).get(0).getDisplayName()); return true; } if (args[0].matches("make")) { Player victim = this.getServer().matchPlayer(args[2]).get(0); info.tregmine.api.TregminePlayer victimPlayer = this.tregmine.tregminePlayer.get(victim.getName()); TregminePlayer vtregPlayer = this.tregmine.tregminePlayer.get(victim.getName()); if (args[1].matches("settler")) { vtregPlayer.setMetaString("color", "trial"); vtregPlayer.setMetaString("trusted", "true"); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); player.sendMessage(ChatColor.AQUA + "You made " + victimPlayer.getChatName() + ChatColor.AQUA + " settler of this server." ); victim.sendMessage("Welcome! You are now made settler."); this.log.info(victim.getName() + " was given settler rights by " + player.getName() + "."); return true; } if (args[1].matches("warn")) { vtregPlayer.setMetaString("color", "warned"); player.sendMessage(ChatColor.AQUA + "You warned " + victimPlayer.getChatName() + "."); victim.sendMessage("You are now warned"); this.log.info(victim.getName() + " was warned by " + player.getName() + "."); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("hardwarn")) { vtregPlayer.setMetaString("color", "warned"); vtregPlayer.setMetaString("trusted", "false"); player.sendMessage(ChatColor.AQUA + "You warned " + victimPlayer.getChatName() + " and removed his building rights." ); victim.sendMessage("You are now warned and bereft of your building rights."); this.log.info(victim.getName() + " was hardwarned by " + player.getName() + "."); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("trial")) { player.sendMessage(ChatColor.RED + "Please use /user make settler name"); } if (args[1].matches("resident") && player.isOp() ) { vtregPlayer.setMetaString("color", "trusted"); vtregPlayer.setMetaString("trusted", "true"); this.log.info(victim.getName() + " was given trusted rights by " + tregminePlayer.getChatName() + "."); player.sendMessage(ChatColor.AQUA + "You made " + victimPlayer.getChatName() + ChatColor.AQUA + " a resident." ); victim.sendMessage("Welcome! You are now a resident"); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("donator") && player.isOp() ) { vtregPlayer.setMetaString("donator", "true"); // vtregPlayer.setMetaString("compass", "true"); vtregPlayer.setFlying(true); vtregPlayer.setMetaString("color", "donator"); player.sendMessage(ChatColor.AQUA + "You made " + vtregPlayer.getChatName() + " a donator." ); this.log.info(victim.getName() + " was made donator by" + tregminePlayer.getChatName() + "."); victim.sendMessage("Congratulations, you are now a donator!"); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("child")) { vtregPlayer.setMetaString("color", "child"); player.sendMessage(ChatColor.AQUA + "You made " + vtregPlayer.getChatName() + " a child." ); this.log.info(victim.getName() + " was made child by" + tregminePlayer.getChatName() + "."); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("guardian") && player.isOp() ) { if(vtregPlayer.isDonator()) { vtregPlayer.setMetaString("police", "true"); vtregPlayer.setMetaString("color", "police"); player.sendMessage(ChatColor.AQUA + "You made " + vtregPlayer.getChatName() + " a police." ); this.log.info(victim.getName() + " was made police by" + tregminePlayer.getChatName() + "."); victim.sendMessage("Congratulations, you are now a police!"); } else { player.sendMessage(ChatColor.AQUA + "Sorry this person is not a " + ChatColor.GOLD + " donator." ); } vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } } } if (commandName.matches("kick") && (isAdmin || isMentor)) { Player victim = this.getServer().matchPlayer(args[0]).get(0); if (victim != null) { info.tregmine.api.TregminePlayer victimPlayer = this.tregmine.tregminePlayer.get(victim.getName()); if(victim.getName().matches("einand")) { this.getServer().broadcastMessage("Never try to kick a god!"); player.kickPlayer("Never kick a god!"); return true; } this.getServer().broadcastMessage(tregminePlayer.getChatName() + ChatColor.AQUA + " kicked " + victimPlayer.getChatName() + ChatColor.AQUA + " for 1 minute."); this.log.info(victim.getName() + " kicked by " + player.getName()); victim.kickPlayer("kicked by " + player.getName()); } return true; } if (commandName.matches("ride.") && tregminePlayer.isOp() ) { Player v = this.getServer().matchPlayer(args[0]).get(0); Player v2 = this.getServer().matchPlayer(args[1]).get(0); v2.setPassenger(v); return true; } if (commandName.matches("eject")) { Player v = this.getServer().matchPlayer(args[0]).get(0); v.eject(); } if (commandName.matches("newspawn") && isAdmin) { player.getWorld().setSpawnLocation(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()); return true; } if (commandName.matches("sendto") && isAdmin) { Player victim = this.getServer().matchPlayer(args[0]).get(0); if (victim != null){ Location cpspawn = this.getServer().getWorld(args[1]).getSpawnLocation(); player.teleport(cpspawn); } return true; } if (commandName.matches("test")) { player.sendMessage("Admin: " + tregminePlayer.isAdmin()); player.sendMessage("Donator: " +tregminePlayer.isDonator()); player.sendMessage("Trusted: " +tregminePlayer.isTrusted()); } if (commandName.matches("createmob") && isAdmin) { int amount = 1; EntityType mobtyp; try { amount = Integer.parseInt( args[1] ); } catch (Exception e) { amount = 1; } try { String mobname = args[0]; //args[0].substring(0,1).toUpperCase() + args[0].substring(1).toLowerCase(); mobtyp = EntityType.fromName(mobname); } catch (Exception e) { player.sendMessage(ChatColor.RED + "Sorry that mob doesn't exist."); return true; } if (mobtyp != null) { for (int i = 0; i<amount;i++) { if (mobtyp.isSpawnable() && mobtyp.isAlive()) { // player.getWorld().spawnCreature(player.getLocation(), mobtyp); player.getWorld().spawnEntity(player.getLocation(), mobtyp); } } player.sendMessage(ChatColor.YELLOW + "You created " + amount + " " + mobtyp.getName() + "."); this.log.info(player.getName() + " created " + amount + " " + mobtyp.getName()); } else { StringBuilder buf = new StringBuilder(); String delim = ""; for (EntityType mob : EntityType.values()) { if (mob.isSpawnable() && mob.isAlive()) { buf.append(delim); buf.append(mob.getName()); delim = ", "; } } player.sendMessage("Valid names are: "); player.sendMessage(buf.toString()); } return true; } if (commandName.matches("ban") && (isAdmin || isMentor)) { if (this.getServer().matchPlayer(args[0]).size() > 1) { player.sendMessage("Found more then one player that contain that letters"); } Player victim = this.getServer().matchPlayer(args[0]).get(0); if (victim != null) { info.tregmine.api.TregminePlayer victimPlayer = this.tregmine.tregminePlayer.get(victim.getName()); if(victim.getName().matches("einand")) { this.getServer().broadcastMessage("Never ban a god!"); player.kickPlayer("Never ban a god!"); return true; } victimPlayer.setMetaString("banned", "true"); this.getServer().broadcastMessage(victimPlayer.getChatName() + ChatColor.RED + " was banned by " + tregminePlayer.getChatName() + "."); this.log.info(victim.getName() + " Banned by " + player.getName()); victim.kickPlayer("banned by " + player.getName()); } return true; } if (commandName.matches("clean")) { player.getInventory().clear(); return true; } return false; } @Override public void onLoad() { final World world = this.getServer().getWorld("world"); this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { public void run() { Location loc = world.getSpawnLocation(); info.tregmine.api.firework.createFirework firework = new info.tregmine.api.firework.createFirework(); firework.addColor(Color.BLUE); firework.addColor(Color.YELLOW); firework.addType(FireworkEffect.Type.STAR); firework.shot(loc); } },100L,200L); } }
false
true
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { String commandName = command.getName().toLowerCase(); if(!(sender instanceof Player)) { if (commandName.matches("kick")) { Player victim = this.getServer().matchPlayer(args[0]).get(0); if (victim != null) { info.tregmine.api.TregminePlayer victimPlayer = this.tregmine.tregminePlayer.get(victim.getName()); this.getServer().broadcastMessage("GOD kicked " + victimPlayer.getChatName() + ChatColor.AQUA + " for 1 min."); victim.kickPlayer("kicked by GOD."); } return true; } return false; } final Player player = (Player) sender; info.tregmine.api.TregminePlayer tregminePlayer = this.tregmine.tregminePlayer.get(player.getName()); boolean isAdmin = tregminePlayer.isAdmin(); boolean isDonator = tregminePlayer.isDonator(); boolean isMentor = tregminePlayer.getMetaBoolean("mentor"); if (commandName.matches("fw")) { } if (commandName.matches("keyword")) { if (args.length != 1) { return false; } if (args[0].length() < 1) { tregminePlayer.sendMessage(ChatColor.RED + "Your keyword must be at least " + "1 characters long."); return true; } tregminePlayer.setMetaString("keyword", args[0].toLowerCase()); tregminePlayer.sendMessage(ChatColor.YELLOW + "From now on you can only log in by using ip " + args[0].toLowerCase() + ".mc.tregmine.info"); return true; } if (commandName.matches("password")) { if (args.length != 1) { return false; } if (args[0].length() < 6) { tregminePlayer.sendMessage(ChatColor.RED + "Your password must be at least " + "6 characters long."); return true; } tregminePlayer.setPassword(args[0]); tregminePlayer.sendMessage(ChatColor.YELLOW + "Your password has been changed."); return true; } if (commandName.matches("creative") && (tregminePlayer.isAdmin() || tregminePlayer.getMetaBoolean("builder"))) { final TregminePlayer tregPlayer = tregmine.getPlayer(player); tregPlayer.setGameMode(GameMode.CREATIVE); tregPlayer.sendMessage(ChatColor.YELLOW + "You are now in creative mode."); } if (commandName.matches("survival") && (tregminePlayer.isAdmin() || tregminePlayer.getMetaBoolean("builder"))) { final TregminePlayer tregPlayer = tregmine.getPlayer(player); tregPlayer.setGameMode(GameMode.SURVIVAL); tregPlayer.sendMessage(ChatColor.YELLOW + "You are now in survival mode."); } if (commandName.matches("pos")) { Location loc = player.getLocation(); Location spawn = player.getWorld().getSpawnLocation(); double distance = info.tregmine.api.math.Distance.calc2d(spawn, loc); player.sendMessage(ChatColor.DARK_AQUA + "World: " + ChatColor.WHITE + player.getWorld().getName()); this.log.info("World: " + player.getWorld().getName()); player.sendMessage(ChatColor.DARK_AQUA + "X: " + ChatColor.WHITE + loc.getX() + ChatColor.RED + " (" + loc.getBlockX() + ")" ); this.log.info("X: " + loc.getX() + " (" + loc.getBlockX() + ")" ); player.sendMessage(ChatColor.DARK_AQUA + "Y: " + ChatColor.WHITE + loc.getY() + ChatColor.RED + " (" + loc.getBlockY() + ")" ); this.log.info("Y: " + loc.getY() + " (" + loc.getBlockY() + ")" ); player.sendMessage(ChatColor.DARK_AQUA + "Z: " + ChatColor.WHITE + loc.getZ() + ChatColor.RED + " (" + loc.getBlockZ() + ")" ); this.log.info("Z: " + loc.getZ() + " (" + loc.getBlockZ() + ")" ); player.sendMessage(ChatColor.DARK_AQUA + "Yaw: " + ChatColor.WHITE + loc.getYaw()); this.log.info("Yaw: " + loc.getYaw()); player.sendMessage(ChatColor.DARK_AQUA + "Pitch: " + ChatColor.WHITE + loc.getPitch()); this.log.info("Pitch: " + loc.getPitch() ); player.sendMessage(ChatColor.DARK_AQUA + "Blocks from spawn: " + ChatColor.WHITE + distance); return true; } if (commandName.matches("cname") && tregminePlayer.isAdmin()) { ChatColor color = ChatColor.getByChar(args[0]); tregminePlayer.setTemporaryChatName(color + args[1]); tregminePlayer.sendMessage("You are now: " + tregminePlayer.getChatName()); this.log.info(tregminePlayer.getName() + "changed name to" + tregminePlayer.getChatName()); } if (commandName.matches("t") && tregminePlayer.isAdmin()) { Player victim = this.getServer().matchPlayer(args[0]).get(0); victim.getWorld().strikeLightningEffect(victim.getLocation()); return true; } if (commandName.matches("td") && tregminePlayer.isOp()) { Player victim = this.getServer().matchPlayer(args[0]).get(0); victim.getWorld().strikeLightningEffect(victim.getLocation()); victim.setHealth(0); return true; } if (commandName.matches("time") && tregminePlayer.isDonator()) { if (args.length == 1) { if (args[0].matches("day")) { player.setPlayerTime(6000, false); } else if (args[0].matches("night")) { player.setPlayerTime(18000, false); } else if (args[0].matches("normal")) { player.resetPlayerTime(); } } else { player.sendMessage(ChatColor.YELLOW + "Say /time day|night|normal"); } log.info(player.getName() + "TIME"); return true; } if (commandName.matches("tpblock") && isDonator) { if (args[0].matches("on")) { tregminePlayer.setMetaString("tpblock", "true"); player.sendMessage("Teleportation is now blocked to you."); return true; } if (args[0].matches("off")) { tregminePlayer.setMetaString("tpblock", "false"); player.sendMessage("Teleportation is now allowed to you."); return true; } if (args[0].matches("status")) { player.sendMessage("Your tpblock is set to " + tregminePlayer.getMetaString("tpblock") + "."); return true; } player.sendMessage(ChatColor.RED + "The commands are /tpblock on, /tpblock off and /tpblock status."); return true; } if (commandName.matches("normal")) { info.tregmine.api.TregminePlayer tregPlayer = this.tregmine.tregminePlayer.get(player.getName()); if (isAdmin) { tregPlayer.setTempMetaString("admin", "false"); tregPlayer.setTemporaryChatName(ChatColor.GOLD + tregPlayer.getName()); player.sendMessage(ChatColor.YELLOW + "You are no longer admin, until you reconnect!"); } else if (tregPlayer.getMetaBoolean("builder")) { tregPlayer.setTempMetaString("builder", "false"); tregPlayer.setTemporaryChatName(ChatColor.GOLD + tregPlayer.getName()); player.sendMessage(ChatColor.YELLOW + "You are no longer builder, until you reconnect!"); } else if (tregPlayer.isGuardian()) { Player[] players = tregmine.getServer().getOnlinePlayers(); TregminePlayer maxRank = null; for (Player srvPlayer : players) { TregminePlayer guardian = tregmine.getPlayer(srvPlayer); if (!guardian.isGuardian()) { continue; } TregminePlayer.GuardianState state = guardian.getGuardianState(); if (state == TregminePlayer.GuardianState.QUEUED) { if (maxRank == null || guardian.getGuardianRank() > maxRank.getGuardianRank()) { maxRank = guardian; } } } if (maxRank != null) { tregPlayer.setGuardianState(TregminePlayer.GuardianState.INACTIVE); tregPlayer.sendMessage(ChatColor.BLUE + "You are now in normal mode, and no longer have to response to help requests."); maxRank.setGuardianState(TregminePlayer.GuardianState.ACTIVE); maxRank.sendMessage(ChatColor.BLUE + "You are now on active duty and should respond to help requests."); } else { tregPlayer.sendMessage(ChatColor.BLUE + "Not enough guardians are on to manage the server. We need you to keep working. Sorry. :/"); } } return true; } info.tregmine.api.TregminePlayer tP = this.tregmine.tregminePlayer.get(player.getName()); if (commandName.matches("nuke") && (tP.isGuardian() || tP.isAdmin())) { player.sendMessage("You nuked all mobs in this world!"); for (Entity ent : player.getWorld().getLivingEntities()) { if(ent instanceof Monster) { Monster mob = (Monster) ent; mob.setHealth(0); } // if(ent instanceof Chicken) { // Chicken chicken = (Chicken) ent; // chicken.setHealth(0); // } if(ent instanceof org.bukkit.entity.Animals) { org.bukkit.entity.Animals animal = (org.bukkit.entity.Animals) ent; animal.setHealth(0); } if(ent instanceof Slime) { Slime slime = (Slime) ent; slime.setHealth(0); } if (ent instanceof EnderDragon) { EnderDragon dragon = (EnderDragon)ent; dragon.setHealth(0); } } return true; } if (commandName.matches("user") && args.length > 0 && (isAdmin || isMentor)) { if (args[0].matches("reload")) { this.tregmine.tregminePlayer.get(this.getServer().matchPlayer(args[1]).get(0).getDisplayName()).load(); player.sendMessage("Player reloaded "+ this.getServer().matchPlayer(args[1]).get(0).getDisplayName()); return true; } if (args[0].matches("make")) { Player victim = this.getServer().matchPlayer(args[2]).get(0); info.tregmine.api.TregminePlayer victimPlayer = this.tregmine.tregminePlayer.get(victim.getName()); TregminePlayer vtregPlayer = this.tregmine.tregminePlayer.get(victim.getName()); if (args[1].matches("settler")) { vtregPlayer.setMetaString("color", "trial"); vtregPlayer.setMetaString("trusted", "true"); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); player.sendMessage(ChatColor.AQUA + "You made " + victimPlayer.getChatName() + ChatColor.AQUA + " settler of this server." ); victim.sendMessage("Welcome! You are now made settler."); this.log.info(victim.getName() + " was given settler rights by " + player.getName() + "."); return true; } if (args[1].matches("warn")) { vtregPlayer.setMetaString("color", "warned"); player.sendMessage(ChatColor.AQUA + "You warned " + victimPlayer.getChatName() + "."); victim.sendMessage("You are now warned"); this.log.info(victim.getName() + " was warned by " + player.getName() + "."); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("hardwarn")) { vtregPlayer.setMetaString("color", "warned"); vtregPlayer.setMetaString("trusted", "false"); player.sendMessage(ChatColor.AQUA + "You warned " + victimPlayer.getChatName() + " and removed his building rights." ); victim.sendMessage("You are now warned and bereft of your building rights."); this.log.info(victim.getName() + " was hardwarned by " + player.getName() + "."); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("trial")) { player.sendMessage(ChatColor.RED + "Please use /user make settler name"); } if (args[1].matches("resident") && player.isOp() ) { vtregPlayer.setMetaString("color", "trusted"); vtregPlayer.setMetaString("trusted", "true"); this.log.info(victim.getName() + " was given trusted rights by " + tregminePlayer.getChatName() + "."); player.sendMessage(ChatColor.AQUA + "You made " + victimPlayer.getChatName() + ChatColor.AQUA + " a resident." ); victim.sendMessage("Welcome! You are now a resident"); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("donator") && player.isOp() ) { vtregPlayer.setMetaString("donator", "true"); // vtregPlayer.setMetaString("compass", "true"); vtregPlayer.setFlying(true); vtregPlayer.setMetaString("color", "donator"); player.sendMessage(ChatColor.AQUA + "You made " + vtregPlayer.getChatName() + " a donator." ); this.log.info(victim.getName() + " was made donator by" + tregminePlayer.getChatName() + "."); victim.sendMessage("Congratulations, you are now a donator!"); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("child")) { vtregPlayer.setMetaString("color", "child"); player.sendMessage(ChatColor.AQUA + "You made " + vtregPlayer.getChatName() + " a child." ); this.log.info(victim.getName() + " was made child by" + tregminePlayer.getChatName() + "."); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("guardian") && player.isOp() ) { if(vtregPlayer.isDonator()) { vtregPlayer.setMetaString("police", "true"); vtregPlayer.setMetaString("color", "police"); player.sendMessage(ChatColor.AQUA + "You made " + vtregPlayer.getChatName() + " a police." ); this.log.info(victim.getName() + " was made police by" + tregminePlayer.getChatName() + "."); victim.sendMessage("Congratulations, you are now a police!"); } else { player.sendMessage(ChatColor.AQUA + "Sorry this person is not a " + ChatColor.GOLD + " donator." ); } vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } } } if (commandName.matches("kick") && (isAdmin || isMentor)) { Player victim = this.getServer().matchPlayer(args[0]).get(0); if (victim != null) { info.tregmine.api.TregminePlayer victimPlayer = this.tregmine.tregminePlayer.get(victim.getName()); if(victim.getName().matches("einand")) { this.getServer().broadcastMessage("Never try to kick a god!"); player.kickPlayer("Never kick a god!"); return true; } this.getServer().broadcastMessage(tregminePlayer.getChatName() + ChatColor.AQUA + " kicked " + victimPlayer.getChatName() + ChatColor.AQUA + " for 1 minute."); this.log.info(victim.getName() + " kicked by " + player.getName()); victim.kickPlayer("kicked by " + player.getName()); } return true; } if (commandName.matches("ride.") && tregminePlayer.isOp() ) { Player v = this.getServer().matchPlayer(args[0]).get(0); Player v2 = this.getServer().matchPlayer(args[1]).get(0); v2.setPassenger(v); return true; } if (commandName.matches("eject")) { Player v = this.getServer().matchPlayer(args[0]).get(0); v.eject(); } if (commandName.matches("newspawn") && isAdmin) { player.getWorld().setSpawnLocation(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()); return true; } if (commandName.matches("sendto") && isAdmin) { Player victim = this.getServer().matchPlayer(args[0]).get(0); if (victim != null){ Location cpspawn = this.getServer().getWorld(args[1]).getSpawnLocation(); player.teleport(cpspawn); } return true; } if (commandName.matches("test")) { player.sendMessage("Admin: " + tregminePlayer.isAdmin()); player.sendMessage("Donator: " +tregminePlayer.isDonator()); player.sendMessage("Trusted: " +tregminePlayer.isTrusted()); } if (commandName.matches("createmob") && isAdmin) { int amount = 1; EntityType mobtyp; try { amount = Integer.parseInt( args[1] ); } catch (Exception e) { amount = 1; } try { String mobname = args[0]; //args[0].substring(0,1).toUpperCase() + args[0].substring(1).toLowerCase(); mobtyp = EntityType.fromName(mobname); } catch (Exception e) { player.sendMessage(ChatColor.RED + "Sorry that mob doesn't exist."); return true; } if (mobtyp != null) { for (int i = 0; i<amount;i++) { if (mobtyp.isSpawnable() && mobtyp.isAlive()) { // player.getWorld().spawnCreature(player.getLocation(), mobtyp); player.getWorld().spawnEntity(player.getLocation(), mobtyp); } } player.sendMessage(ChatColor.YELLOW + "You created " + amount + " " + mobtyp.getName() + "."); this.log.info(player.getName() + " created " + amount + " " + mobtyp.getName()); } else { StringBuilder buf = new StringBuilder(); String delim = ""; for (EntityType mob : EntityType.values()) { if (mob.isSpawnable() && mob.isAlive()) { buf.append(delim); buf.append(mob.getName()); delim = ", "; } } player.sendMessage("Valid names are: "); player.sendMessage(buf.toString()); } return true; } if (commandName.matches("ban") && (isAdmin || isMentor)) { if (this.getServer().matchPlayer(args[0]).size() > 1) { player.sendMessage("Found more then one player that contain that letters"); } Player victim = this.getServer().matchPlayer(args[0]).get(0); if (victim != null) { info.tregmine.api.TregminePlayer victimPlayer = this.tregmine.tregminePlayer.get(victim.getName()); if(victim.getName().matches("einand")) { this.getServer().broadcastMessage("Never ban a god!"); player.kickPlayer("Never ban a god!"); return true; } victimPlayer.setMetaString("banned", "true"); this.getServer().broadcastMessage(victimPlayer.getChatName() + ChatColor.RED + " was banned by " + tregminePlayer.getChatName() + "."); this.log.info(victim.getName() + " Banned by " + player.getName()); victim.kickPlayer("banned by " + player.getName()); } return true; } if (commandName.matches("clean")) { player.getInventory().clear(); return true; } return false; }
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { String commandName = command.getName().toLowerCase(); if(!(sender instanceof Player)) { if (commandName.matches("kick")) { Player victim = this.getServer().matchPlayer(args[0]).get(0); if (victim != null) { info.tregmine.api.TregminePlayer victimPlayer = this.tregmine.tregminePlayer.get(victim.getName()); this.getServer().broadcastMessage("GOD kicked " + victimPlayer.getChatName() + ChatColor.AQUA + " for 1 min."); victim.kickPlayer("kicked by GOD."); } return true; } return false; } final Player player = (Player) sender; info.tregmine.api.TregminePlayer tregminePlayer = this.tregmine.tregminePlayer.get(player.getName()); boolean isAdmin = tregminePlayer.isAdmin(); boolean isDonator = tregminePlayer.isDonator(); boolean isMentor = tregminePlayer.getMetaBoolean("mentor"); if (commandName.matches("fw")) { } if (commandName.matches("keyword")) { if (args.length != 1) { return false; } if (args[0].length() < 1) { tregminePlayer.sendMessage(ChatColor.RED + "Your keyword must be at least " + "1 characters long."); return true; } tregminePlayer.setMetaString("keyword", args[0].toLowerCase()); tregminePlayer.sendMessage(ChatColor.YELLOW + "From now on you can only log in by using ip " + args[0].toLowerCase() + ".mc.tregmine.info"); return true; } if (commandName.matches("password")) { if (args.length != 1) { return false; } if (args[0].length() < 6) { tregminePlayer.sendMessage(ChatColor.RED + "Your password must be at least " + "6 characters long."); return true; } tregminePlayer.setPassword(args[0]); tregminePlayer.sendMessage(ChatColor.YELLOW + "Your password has been changed."); return true; } if (commandName.matches("creative") && (tregminePlayer.isAdmin() || tregminePlayer.getMetaBoolean("builder"))) { final TregminePlayer tregPlayer = tregmine.getPlayer(player); tregPlayer.setGameMode(GameMode.CREATIVE); tregPlayer.sendMessage(ChatColor.YELLOW + "You are now in creative mode."); } if (commandName.matches("survival") && (tregminePlayer.isAdmin() || tregminePlayer.getMetaBoolean("builder"))) { final TregminePlayer tregPlayer = tregmine.getPlayer(player); tregPlayer.setGameMode(GameMode.SURVIVAL); tregPlayer.sendMessage(ChatColor.YELLOW + "You are now in survival mode."); } if (commandName.matches("pos")) { Location loc = player.getLocation(); Location spawn = player.getWorld().getSpawnLocation(); double distance = info.tregmine.api.math.Distance.calc2d(spawn, loc); player.sendMessage(ChatColor.DARK_AQUA + "World: " + ChatColor.WHITE + player.getWorld().getName()); this.log.info("World: " + player.getWorld().getName()); player.sendMessage(ChatColor.DARK_AQUA + "X: " + ChatColor.WHITE + loc.getX() + ChatColor.RED + " (" + loc.getBlockX() + ")" ); this.log.info("X: " + loc.getX() + " (" + loc.getBlockX() + ")" ); player.sendMessage(ChatColor.DARK_AQUA + "Y: " + ChatColor.WHITE + loc.getY() + ChatColor.RED + " (" + loc.getBlockY() + ")" ); this.log.info("Y: " + loc.getY() + " (" + loc.getBlockY() + ")" ); player.sendMessage(ChatColor.DARK_AQUA + "Z: " + ChatColor.WHITE + loc.getZ() + ChatColor.RED + " (" + loc.getBlockZ() + ")" ); this.log.info("Z: " + loc.getZ() + " (" + loc.getBlockZ() + ")" ); player.sendMessage(ChatColor.DARK_AQUA + "Yaw: " + ChatColor.WHITE + loc.getYaw()); this.log.info("Yaw: " + loc.getYaw()); player.sendMessage(ChatColor.DARK_AQUA + "Pitch: " + ChatColor.WHITE + loc.getPitch()); this.log.info("Pitch: " + loc.getPitch() ); player.sendMessage(ChatColor.DARK_AQUA + "Blocks from spawn: " + ChatColor.WHITE + distance); return true; } if (commandName.matches("cname") && tregminePlayer.isAdmin()) { ChatColor color = ChatColor.getByChar(args[0]); tregminePlayer.setTemporaryChatName(color + args[1]); tregminePlayer.sendMessage("You are now: " + tregminePlayer.getChatName()); this.log.info(tregminePlayer.getName() + "changed name to" + tregminePlayer.getChatName()); } if (commandName.matches("t") && tregminePlayer.isAdmin()) { Player victim = this.getServer().matchPlayer(args[0]).get(0); victim.getWorld().strikeLightningEffect(victim.getLocation()); return true; } if (commandName.matches("td") && tregminePlayer.isOp()) { Player victim = this.getServer().matchPlayer(args[0]).get(0); victim.getWorld().strikeLightningEffect(victim.getLocation()); victim.setHealth(0); return true; } if (commandName.matches("time") && tregminePlayer.isDonator()) { if (args.length == 1) { if (args[0].matches("day")) { player.setPlayerTime(6000, false); } else if (args[0].matches("night")) { player.setPlayerTime(18000, false); } else if (args[0].matches("normal")) { player.resetPlayerTime(); } } else { player.sendMessage(ChatColor.YELLOW + "Say /time day|night|normal"); } log.info(player.getName() + "TIME"); return true; } if (commandName.matches("tpblock") && isDonator) { if ("on".matches(args[0])) { tregminePlayer.setMetaString("tpblock", "true"); player.sendMessage("Teleportation is now blocked to you."); return true; } if ("off".matches(args[0])) { tregminePlayer.setMetaString("tpblock", "false"); player.sendMessage("Teleportation is now allowed to you."); return true; } if ("status".matches(args[0])) { player.sendMessage("Your tpblock is set to " + tregminePlayer.getMetaString("tpblock") + "."); return true; } player.sendMessage(ChatColor.RED + "The commands are /tpblock on, /tpblock off and /tpblock status."); return true; } if (commandName.matches("normal")) { info.tregmine.api.TregminePlayer tregPlayer = this.tregmine.tregminePlayer.get(player.getName()); if (isAdmin) { tregPlayer.setTempMetaString("admin", "false"); tregPlayer.setTemporaryChatName(ChatColor.GOLD + tregPlayer.getName()); player.sendMessage(ChatColor.YELLOW + "You are no longer admin, until you reconnect!"); } else if (tregPlayer.getMetaBoolean("builder")) { tregPlayer.setTempMetaString("builder", "false"); tregPlayer.setTemporaryChatName(ChatColor.GOLD + tregPlayer.getName()); player.sendMessage(ChatColor.YELLOW + "You are no longer builder, until you reconnect!"); } else if (tregPlayer.isGuardian()) { Player[] players = tregmine.getServer().getOnlinePlayers(); TregminePlayer maxRank = null; for (Player srvPlayer : players) { TregminePlayer guardian = tregmine.getPlayer(srvPlayer); if (!guardian.isGuardian()) { continue; } TregminePlayer.GuardianState state = guardian.getGuardianState(); if (state == TregminePlayer.GuardianState.QUEUED) { if (maxRank == null || guardian.getGuardianRank() > maxRank.getGuardianRank()) { maxRank = guardian; } } } if (maxRank != null) { tregPlayer.setGuardianState(TregminePlayer.GuardianState.INACTIVE); tregPlayer.sendMessage(ChatColor.BLUE + "You are now in normal mode, and no longer have to response to help requests."); maxRank.setGuardianState(TregminePlayer.GuardianState.ACTIVE); maxRank.sendMessage(ChatColor.BLUE + "You are now on active duty and should respond to help requests."); } else { tregPlayer.sendMessage(ChatColor.BLUE + "Not enough guardians are on to manage the server. We need you to keep working. Sorry. :/"); } } return true; } info.tregmine.api.TregminePlayer tP = this.tregmine.tregminePlayer.get(player.getName()); if (commandName.matches("nuke") && (tP.isGuardian() || tP.isAdmin())) { player.sendMessage("You nuked all mobs in this world!"); for (Entity ent : player.getWorld().getLivingEntities()) { if(ent instanceof Monster) { Monster mob = (Monster) ent; mob.setHealth(0); } // if(ent instanceof Chicken) { // Chicken chicken = (Chicken) ent; // chicken.setHealth(0); // } if(ent instanceof org.bukkit.entity.Animals) { org.bukkit.entity.Animals animal = (org.bukkit.entity.Animals) ent; animal.setHealth(0); } if(ent instanceof Slime) { Slime slime = (Slime) ent; slime.setHealth(0); } if (ent instanceof EnderDragon) { EnderDragon dragon = (EnderDragon)ent; dragon.setHealth(0); } } return true; } if (commandName.matches("user") && args.length > 0 && (isAdmin || isMentor)) { if (args[0].matches("reload")) { this.tregmine.tregminePlayer.get(this.getServer().matchPlayer(args[1]).get(0).getDisplayName()).load(); player.sendMessage("Player reloaded "+ this.getServer().matchPlayer(args[1]).get(0).getDisplayName()); return true; } if (args[0].matches("make")) { Player victim = this.getServer().matchPlayer(args[2]).get(0); info.tregmine.api.TregminePlayer victimPlayer = this.tregmine.tregminePlayer.get(victim.getName()); TregminePlayer vtregPlayer = this.tregmine.tregminePlayer.get(victim.getName()); if (args[1].matches("settler")) { vtregPlayer.setMetaString("color", "trial"); vtregPlayer.setMetaString("trusted", "true"); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); player.sendMessage(ChatColor.AQUA + "You made " + victimPlayer.getChatName() + ChatColor.AQUA + " settler of this server." ); victim.sendMessage("Welcome! You are now made settler."); this.log.info(victim.getName() + " was given settler rights by " + player.getName() + "."); return true; } if (args[1].matches("warn")) { vtregPlayer.setMetaString("color", "warned"); player.sendMessage(ChatColor.AQUA + "You warned " + victimPlayer.getChatName() + "."); victim.sendMessage("You are now warned"); this.log.info(victim.getName() + " was warned by " + player.getName() + "."); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("hardwarn")) { vtregPlayer.setMetaString("color", "warned"); vtregPlayer.setMetaString("trusted", "false"); player.sendMessage(ChatColor.AQUA + "You warned " + victimPlayer.getChatName() + " and removed his building rights." ); victim.sendMessage("You are now warned and bereft of your building rights."); this.log.info(victim.getName() + " was hardwarned by " + player.getName() + "."); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("trial")) { player.sendMessage(ChatColor.RED + "Please use /user make settler name"); } if (args[1].matches("resident") && player.isOp() ) { vtregPlayer.setMetaString("color", "trusted"); vtregPlayer.setMetaString("trusted", "true"); this.log.info(victim.getName() + " was given trusted rights by " + tregminePlayer.getChatName() + "."); player.sendMessage(ChatColor.AQUA + "You made " + victimPlayer.getChatName() + ChatColor.AQUA + " a resident." ); victim.sendMessage("Welcome! You are now a resident"); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("donator") && player.isOp() ) { vtregPlayer.setMetaString("donator", "true"); // vtregPlayer.setMetaString("compass", "true"); vtregPlayer.setFlying(true); vtregPlayer.setMetaString("color", "donator"); player.sendMessage(ChatColor.AQUA + "You made " + vtregPlayer.getChatName() + " a donator." ); this.log.info(victim.getName() + " was made donator by" + tregminePlayer.getChatName() + "."); victim.sendMessage("Congratulations, you are now a donator!"); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("child")) { vtregPlayer.setMetaString("color", "child"); player.sendMessage(ChatColor.AQUA + "You made " + vtregPlayer.getChatName() + " a child." ); this.log.info(victim.getName() + " was made child by" + tregminePlayer.getChatName() + "."); vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } if (args[1].matches("guardian") && player.isOp() ) { if(vtregPlayer.isDonator()) { vtregPlayer.setMetaString("police", "true"); vtregPlayer.setMetaString("color", "police"); player.sendMessage(ChatColor.AQUA + "You made " + vtregPlayer.getChatName() + " a police." ); this.log.info(victim.getName() + " was made police by" + tregminePlayer.getChatName() + "."); victim.sendMessage("Congratulations, you are now a police!"); } else { player.sendMessage(ChatColor.AQUA + "Sorry this person is not a " + ChatColor.GOLD + " donator." ); } vtregPlayer.setTemporaryChatName(vtregPlayer.getNameColor() + vtregPlayer.getName()); return true; } } } if (commandName.matches("kick") && (isAdmin || isMentor)) { Player victim = this.getServer().matchPlayer(args[0]).get(0); if (victim != null) { info.tregmine.api.TregminePlayer victimPlayer = this.tregmine.tregminePlayer.get(victim.getName()); if(victim.getName().matches("einand")) { this.getServer().broadcastMessage("Never try to kick a god!"); player.kickPlayer("Never kick a god!"); return true; } this.getServer().broadcastMessage(tregminePlayer.getChatName() + ChatColor.AQUA + " kicked " + victimPlayer.getChatName() + ChatColor.AQUA + " for 1 minute."); this.log.info(victim.getName() + " kicked by " + player.getName()); victim.kickPlayer("kicked by " + player.getName()); } return true; } if (commandName.matches("ride.") && tregminePlayer.isOp() ) { Player v = this.getServer().matchPlayer(args[0]).get(0); Player v2 = this.getServer().matchPlayer(args[1]).get(0); v2.setPassenger(v); return true; } if (commandName.matches("eject")) { Player v = this.getServer().matchPlayer(args[0]).get(0); v.eject(); } if (commandName.matches("newspawn") && isAdmin) { player.getWorld().setSpawnLocation(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()); return true; } if (commandName.matches("sendto") && isAdmin) { Player victim = this.getServer().matchPlayer(args[0]).get(0); if (victim != null){ Location cpspawn = this.getServer().getWorld(args[1]).getSpawnLocation(); player.teleport(cpspawn); } return true; } if (commandName.matches("test")) { player.sendMessage("Admin: " + tregminePlayer.isAdmin()); player.sendMessage("Donator: " +tregminePlayer.isDonator()); player.sendMessage("Trusted: " +tregminePlayer.isTrusted()); } if (commandName.matches("createmob") && isAdmin) { int amount = 1; EntityType mobtyp; try { amount = Integer.parseInt( args[1] ); } catch (Exception e) { amount = 1; } try { String mobname = args[0]; //args[0].substring(0,1).toUpperCase() + args[0].substring(1).toLowerCase(); mobtyp = EntityType.fromName(mobname); } catch (Exception e) { player.sendMessage(ChatColor.RED + "Sorry that mob doesn't exist."); return true; } if (mobtyp != null) { for (int i = 0; i<amount;i++) { if (mobtyp.isSpawnable() && mobtyp.isAlive()) { // player.getWorld().spawnCreature(player.getLocation(), mobtyp); player.getWorld().spawnEntity(player.getLocation(), mobtyp); } } player.sendMessage(ChatColor.YELLOW + "You created " + amount + " " + mobtyp.getName() + "."); this.log.info(player.getName() + " created " + amount + " " + mobtyp.getName()); } else { StringBuilder buf = new StringBuilder(); String delim = ""; for (EntityType mob : EntityType.values()) { if (mob.isSpawnable() && mob.isAlive()) { buf.append(delim); buf.append(mob.getName()); delim = ", "; } } player.sendMessage("Valid names are: "); player.sendMessage(buf.toString()); } return true; } if (commandName.matches("ban") && (isAdmin || isMentor)) { if (this.getServer().matchPlayer(args[0]).size() > 1) { player.sendMessage("Found more then one player that contain that letters"); } Player victim = this.getServer().matchPlayer(args[0]).get(0); if (victim != null) { info.tregmine.api.TregminePlayer victimPlayer = this.tregmine.tregminePlayer.get(victim.getName()); if(victim.getName().matches("einand")) { this.getServer().broadcastMessage("Never ban a god!"); player.kickPlayer("Never ban a god!"); return true; } victimPlayer.setMetaString("banned", "true"); this.getServer().broadcastMessage(victimPlayer.getChatName() + ChatColor.RED + " was banned by " + tregminePlayer.getChatName() + "."); this.log.info(victim.getName() + " Banned by " + player.getName()); victim.kickPlayer("banned by " + player.getName()); } return true; } if (commandName.matches("clean")) { player.getInventory().clear(); return true; } return false; }
diff --git a/poem/src/main/java/org/melati/poem/ValueInfo.java b/poem/src/main/java/org/melati/poem/ValueInfo.java index 3c6b9918c..ef57c1b0d 100644 --- a/poem/src/main/java/org/melati/poem/ValueInfo.java +++ b/poem/src/main/java/org/melati/poem/ValueInfo.java @@ -1,258 +1,257 @@ /* * $Source$ * $Revision$ * * Copyright (C) 2000 William Chesters * * Part of Melati (http://melati.org), a framework for the rapid * development of clean, maintainable web applications. * * Melati is free software; Permission is granted to copy, distribute * and/or modify this software under the terms either: * * a) 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, * * or * * b) any version of the Melati Software License, as published * at http://melati.org * * You should have received a copy of the GNU General Public License and * the Melati Software License along with this program; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA to obtain the * GNU General Public License and visit http://melati.org to obtain the * Melati Software License. * * Feel free to contact the Developers of Melati (http://melati.org), * if you would like to work out a different arrangement than the options * outlined here. It is our intention to allow Melati to be used by as * wide an audience as possible. * * 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. * * Contact details for copyright holder: * * William Chesters <williamc At paneris.org> * http://paneris.org/~williamc * Obrechtstraat 114, 2517VX Den Haag, The Netherlands */ package org.melati.poem; import org.melati.poem.generated.ValueInfoBase; /** * Abstract persistent generated from Poem.dsd * and extended to cover {@link Setting} and {@link ColumnInfo}. * * Melati POEM generated, programmer modifiable stub * for a <code>Persistent</code> <code>ValueInfo</code> object. * * * <table> * <tr><th colspan='3'> * Field summary for SQL table <code>ValueInfo</code> * </th></tr> * <tr><th>Name</th><th>Type</th><th>Description</th></tr> * <tr><td> displayname </td><td> String </td><td> A user-friendly name for * the field </td></tr> * <tr><td> description </td><td> String </td><td> A brief description of the * field's function </td></tr> * <tr><td> usereditable </td><td> Boolean </td><td> Whether it makes sense * for the user to update the field's value </td></tr> * <tr><td> typefactory </td><td> PoemTypeFactory </td><td> The field's * Melati type </td></tr> * <tr><td> nullable </td><td> Boolean </td><td> Whether the field can be * empty </td></tr> * <tr><td> size </td><td> Integer </td><td> For character fields, the * maximum number of characters that can be stored, (-1 for unlimited) * </td></tr> * <tr><td> width </td><td> Integer </td><td> A sensible width for text boxes * used for entering the field, where appropriate </td></tr> * <tr><td> height </td><td> Integer </td><td> A sensible height for text * boxes used for entering the field, where appropriate </td></tr> * <tr><td> precision </td><td> Integer </td><td> Precision (total number of * digits) for fixed-point numbers </td></tr> * <tr><td> scale </td><td> Integer </td><td> Scale (number of digits after * the decimal) for fixed-point numbers </td></tr> * <tr><td> renderinfo </td><td> String </td><td> The name of the Melati * templet (if not the default) to use for input controls for the field * </td></tr> * <tr><td> rangelow_string </td><td> String </td><td> The low end of the * range of permissible values for the field </td></tr> * <tr><td> rangelimit_string </td><td> String </td><td> The (exclusive) * limit of the range of permissible values for the field </td></tr> * </table> * * @generator org.melati.poem.prepro.TableDef#generateMainJava */ public class ValueInfo extends ValueInfoBase { /** * Constructor * for a <code>Persistent</code> <code>ValueInfo</code> object. * * @generator org.melati.poem.prepro.TableDef#generateMainJava */ public ValueInfo() { } // programmer's domain-specific code here /** * @return a Type Parameter based upon our size and nullability */ public PoemTypeFactory.Parameter toTypeParameter() { final Boolean nullableL = getNullable_unsafe(); final Integer sizeL = getSize_unsafe(); return new PoemTypeFactory.Parameter() { public boolean getNullable() { return nullableL == null || nullableL.booleanValue(); } public int getSize() { return sizeL == null ? -1 : sizeL.intValue(); } }; } private SQLPoemType poemType = null; /** * @return our SQLPoemType */ public SQLPoemType getType() { if (poemType == null) { PoemTypeFactory f = getTypefactory(); if (f == null) { // this can happen before we have been fully initialised // it's convenient to return the "most general" type available ... return StringPoemType.nullableInstance; } poemType = f.typeOf(getDatabase(), toTypeParameter()); } return poemType; } /** * @param nullableP * @return */ private SQLPoemType getRangeEndType(boolean nullableP) { // FIXME a little inefficient, but rarely used; also relies on BasePoemType // should have interface for ranged type ... SQLPoemType t = getType(); if (t instanceof BasePoemType) { BasePoemType unrangedType = (BasePoemType)((BasePoemType)t).clone(); unrangedType.setRawRange(null, null); return (SQLPoemType)unrangedType.withNullable(nullableP); } else return null; } private FieldAttributes fieldAttributesRenamedAs(FieldAttributes c, PoemType type) { return new BaseFieldAttributes( c.getName(), c.getDisplayName(), c.getDescription(), type, width == null ? 12 : width.intValue(), height == null ? 1 : height.intValue(), renderinfo, false, // indexed usereditable == null ? true : usereditable.booleanValue(), true // usercreateable ); } /** * @param c a FieldAttributes eg a Field * @return a new FieldAttributes */ public FieldAttributes fieldAttributesRenamedAs(FieldAttributes c) { return fieldAttributesRenamedAs(c, getType()); } /** * @param c a Column with a Range * @return a Field representing the end of the Range */ private Field rangeEndField(Column c) { SQLPoemType unrangedType = getRangeEndType(c.getType().getNullable()); if (unrangedType == null) return null; else { Object raw; try { raw = unrangedType.rawOfString((String)c.getRaw_unsafe(this)); } catch (Exception e) { - System.err.println("Found a bad entry for " + c + " in " + - getTable().getName() + "/" + troid() + ": " + - "solution is to null it out ..."); - e.printStackTrace(); c.setRaw_unsafe(this, null); raw = null; + throw new AppBugPoemException("Found a bad entry for " + c + " in " + + getTable().getName() + "/" + troid() + ": " + + "solution is to null it out ...", e); } return new Field( raw, fieldAttributesRenamedAs(c, unrangedType)); } } /** * {@inheritDoc} * @see org.melati.poem.generated.ValueInfoBase#getRangelow_stringField() */ public Field getRangelow_stringField() { Field it = rangeEndField(getValueInfoTable().getRangelow_stringColumn()); return it != null ? it : super.getRangelow_stringField(); } /** * {@inheritDoc} * @see org.melati.poem.generated.ValueInfoBase#getRangelimit_stringField() */ public Field getRangelimit_stringField() { Field it = rangeEndField(getValueInfoTable().getRangelimit_stringColumn()); return it != null ? it : super.getRangelimit_stringField(); } /** * {@inheritDoc} * @see org.melati.poem.generated.ValueInfoBase#setRangelow_string(java.lang.String) */ public void setRangelow_string(String value) { boolean nullableL = getValueInfoTable().getRangelow_stringColumn(). getType().getNullable(); PoemType unrangedType = getRangeEndType(nullableL); if (unrangedType != null) value = unrangedType.stringOfRaw(unrangedType.rawOfString(value)); super.setRangelow_string(value); } /** * {@inheritDoc} * @see org.melati.poem.generated.ValueInfoBase#setRangelimit_string(java.lang.String) */ public void setRangelimit_string(String value) { boolean nullableL = getValueInfoTable().getRangelimit_stringColumn(). getType().getNullable(); PoemType unrangedType = getRangeEndType(nullableL); if (unrangedType != null) value = unrangedType.stringOfRaw(unrangedType.rawOfString(value)); super.setRangelimit_string(value); } }
false
true
private Field rangeEndField(Column c) { SQLPoemType unrangedType = getRangeEndType(c.getType().getNullable()); if (unrangedType == null) return null; else { Object raw; try { raw = unrangedType.rawOfString((String)c.getRaw_unsafe(this)); } catch (Exception e) { System.err.println("Found a bad entry for " + c + " in " + getTable().getName() + "/" + troid() + ": " + "solution is to null it out ..."); e.printStackTrace(); c.setRaw_unsafe(this, null); raw = null; } return new Field( raw, fieldAttributesRenamedAs(c, unrangedType)); } }
private Field rangeEndField(Column c) { SQLPoemType unrangedType = getRangeEndType(c.getType().getNullable()); if (unrangedType == null) return null; else { Object raw; try { raw = unrangedType.rawOfString((String)c.getRaw_unsafe(this)); } catch (Exception e) { c.setRaw_unsafe(this, null); raw = null; throw new AppBugPoemException("Found a bad entry for " + c + " in " + getTable().getName() + "/" + troid() + ": " + "solution is to null it out ...", e); } return new Field( raw, fieldAttributesRenamedAs(c, unrangedType)); } }
diff --git a/ScalpelCarver/src/org/sleuthkit/autopsy/scalpel/jni/ScalpelCarver.java b/ScalpelCarver/src/org/sleuthkit/autopsy/scalpel/jni/ScalpelCarver.java index e8d91d057..266d989d2 100644 --- a/ScalpelCarver/src/org/sleuthkit/autopsy/scalpel/jni/ScalpelCarver.java +++ b/ScalpelCarver/src/org/sleuthkit/autopsy/scalpel/jni/ScalpelCarver.java @@ -1,170 +1,170 @@ /* * Autopsy Forensic Browser * * Copyright 2013 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.scalpel.jni; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.logging.Level; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.scalpel.jni.ScalpelOutputParser.CarvedFileMeta; import org.sleuthkit.datamodel.AbstractFile; import org.sleuthkit.datamodel.ReadContentInputStream; /** * JNI wrapper over libscalpel and library loader */ public class ScalpelCarver { private static final String SCALPEL_JNI_LIB = "libscalpel_jni"; private static final String SCALPEL_OUTPUT_FILE_NAME = "audit.txt"; private static boolean initialized = false; private static final Logger logger = Logger.getLogger(ScalpelCarver.class.getName()); private static native void carveNat(String carverInputId, ReadContentInputStream input, String configFilePath, String outputFolderPath) throws ScalpelException; public ScalpelCarver() { } public static boolean init() { if (initialized) { return true; } initialized = true; for (String library : Arrays.asList("libtre-4", "pthreadGC2", SCALPEL_JNI_LIB)) { if (!loadLib(library)) { initialized = false; logger.log(Level.SEVERE, "Failed initializing " + ScalpelCarver.class.getName() + " due to failure loading library: " + library); break; } } if (initialized) { logger.log(Level.INFO, ScalpelCarver.class.getName() + " JNI initialized successfully. "); } return initialized; } /** * initialize, load dynamic libraries */ private static boolean loadLib(String id) { boolean success = false; try { //rely on netbeans / jna to locate the lib variation for architecture/OS System.loadLibrary(id); success = true; } catch (UnsatisfiedLinkError ex) { String msg = "Could not load library " + id + " for your environment "; System.out.println(msg + ex.toString()); logger.log(Level.SEVERE, msg, ex); } catch (Exception ex) { String msg = "Could not load library " + id + " for your environment "; System.out.println(msg + ex.toString()); logger.log(Level.SEVERE, msg, ex); } return success; } /** * Check if initialized * * @return true if library has been initialized properly, false otherwise */ public boolean isInitialized() { return initialized; } /** * Carve the file passed in as an argument and save the results. * Requires prior call to ScalpelCarver.init() * * * @param file File to carve * @param configFilePath file path to scalpel * configuration file with signatures, such as scalpel.conf * @param outputFolder Location to save the reults to (should be in the case * folder) * @return list of carved files info * @throws ScalpelException on errors */ public List<CarvedFileMeta> carve(AbstractFile file, String configFilePath, String outputFolderPath) throws ScalpelException { if (!initialized) { throw new ScalpelException("Scalpel library is not fully initialized. "); } //basic check of arguments before going to jni land if (file == null || configFilePath == null || configFilePath.isEmpty() || outputFolderPath == null || outputFolderPath.isEmpty()) { throw new ScalpelException("Invalid arguments for scalpel carving. "); } //validate the paths passed in File config = new File(configFilePath); if (! config.exists() || ! config.canRead()) { throw new ScalpelException("Cannot read libscalpel config file: " + configFilePath); } File outDir = new File(outputFolderPath); if (! outDir.exists() || ! outDir.canWrite()) { throw new ScalpelException("Cannot write to libscalpel output dir: " + outputFolderPath); } final String carverInputId = file.getId() + ": " + file.getName(); final ReadContentInputStream carverInput = new ReadContentInputStream(file); try { carveNat(carverInputId, carverInput, configFilePath, outputFolderPath); } catch (Exception e) { logger.log(Level.SEVERE, "Error while caving file " + file, e); throw new ScalpelException(e); } finally { try { carverInput.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Error closing input stream after carving, file: " + file, ex); } } // create a file object for the output File outputFile = new File(outputFolderPath, SCALPEL_OUTPUT_FILE_NAME); // parse the output - List<CarvedFileMeta> output = Collections.EMPTY_LIST; + List<CarvedFileMeta> output = Collections.<CarvedFileMeta>emptyList(); try { output = ScalpelOutputParser.parse(outputFile); } catch (FileNotFoundException ex) { logger.log(Level.SEVERE, "Could not find scalpel output file.", ex); } catch (IOException ex) { logger.log(Level.SEVERE, "IOException while processing scalpel output file.", ex); } return output; } }
true
true
public List<CarvedFileMeta> carve(AbstractFile file, String configFilePath, String outputFolderPath) throws ScalpelException { if (!initialized) { throw new ScalpelException("Scalpel library is not fully initialized. "); } //basic check of arguments before going to jni land if (file == null || configFilePath == null || configFilePath.isEmpty() || outputFolderPath == null || outputFolderPath.isEmpty()) { throw new ScalpelException("Invalid arguments for scalpel carving. "); } //validate the paths passed in File config = new File(configFilePath); if (! config.exists() || ! config.canRead()) { throw new ScalpelException("Cannot read libscalpel config file: " + configFilePath); } File outDir = new File(outputFolderPath); if (! outDir.exists() || ! outDir.canWrite()) { throw new ScalpelException("Cannot write to libscalpel output dir: " + outputFolderPath); } final String carverInputId = file.getId() + ": " + file.getName(); final ReadContentInputStream carverInput = new ReadContentInputStream(file); try { carveNat(carverInputId, carverInput, configFilePath, outputFolderPath); } catch (Exception e) { logger.log(Level.SEVERE, "Error while caving file " + file, e); throw new ScalpelException(e); } finally { try { carverInput.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Error closing input stream after carving, file: " + file, ex); } } // create a file object for the output File outputFile = new File(outputFolderPath, SCALPEL_OUTPUT_FILE_NAME); // parse the output List<CarvedFileMeta> output = Collections.EMPTY_LIST; try { output = ScalpelOutputParser.parse(outputFile); } catch (FileNotFoundException ex) { logger.log(Level.SEVERE, "Could not find scalpel output file.", ex); } catch (IOException ex) { logger.log(Level.SEVERE, "IOException while processing scalpel output file.", ex); } return output; }
public List<CarvedFileMeta> carve(AbstractFile file, String configFilePath, String outputFolderPath) throws ScalpelException { if (!initialized) { throw new ScalpelException("Scalpel library is not fully initialized. "); } //basic check of arguments before going to jni land if (file == null || configFilePath == null || configFilePath.isEmpty() || outputFolderPath == null || outputFolderPath.isEmpty()) { throw new ScalpelException("Invalid arguments for scalpel carving. "); } //validate the paths passed in File config = new File(configFilePath); if (! config.exists() || ! config.canRead()) { throw new ScalpelException("Cannot read libscalpel config file: " + configFilePath); } File outDir = new File(outputFolderPath); if (! outDir.exists() || ! outDir.canWrite()) { throw new ScalpelException("Cannot write to libscalpel output dir: " + outputFolderPath); } final String carverInputId = file.getId() + ": " + file.getName(); final ReadContentInputStream carverInput = new ReadContentInputStream(file); try { carveNat(carverInputId, carverInput, configFilePath, outputFolderPath); } catch (Exception e) { logger.log(Level.SEVERE, "Error while caving file " + file, e); throw new ScalpelException(e); } finally { try { carverInput.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Error closing input stream after carving, file: " + file, ex); } } // create a file object for the output File outputFile = new File(outputFolderPath, SCALPEL_OUTPUT_FILE_NAME); // parse the output List<CarvedFileMeta> output = Collections.<CarvedFileMeta>emptyList(); try { output = ScalpelOutputParser.parse(outputFile); } catch (FileNotFoundException ex) { logger.log(Level.SEVERE, "Could not find scalpel output file.", ex); } catch (IOException ex) { logger.log(Level.SEVERE, "IOException while processing scalpel output file.", ex); } return output; }
diff --git a/src/main/java/org/dita/dost/module/DebugAndFilterModule.java b/src/main/java/org/dita/dost/module/DebugAndFilterModule.java index 6f15a3bb7..170c9284d 100644 --- a/src/main/java/org/dita/dost/module/DebugAndFilterModule.java +++ b/src/main/java/org/dita/dost/module/DebugAndFilterModule.java @@ -1,760 +1,760 @@ /* * This file is part of the DITA Open Toolkit project. * See the accompanying license.txt file for applicable licenses. */ /* * (c) Copyright IBM Corp. 2004, 2005 All Rights Reserved. */ package org.dita.dost.module; import static org.dita.dost.util.Constants.*; import static org.dita.dost.writer.DitaWriter.*; import static org.dita.dost.util.Job.*; import static org.dita.dost.util.Configuration.*; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Properties; import java.util.Queue; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; 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.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.dita.dost.exception.DITAOTException; import org.dita.dost.log.DITAOTLogger; import org.dita.dost.log.MessageUtils; import org.dita.dost.pipeline.AbstractPipelineInput; import org.dita.dost.pipeline.AbstractPipelineOutput; import org.dita.dost.reader.DitaValReader; import org.dita.dost.reader.SubjectSchemeReader; import org.dita.dost.util.DelayConrefUtils; import org.dita.dost.util.FilterUtils.Action; import org.dita.dost.util.FilterUtils.FilterKey; import org.dita.dost.util.CatalogUtils; import org.dita.dost.util.FileUtils; import org.dita.dost.util.FilterUtils; import org.dita.dost.util.Job; import org.dita.dost.util.KeyDef; import org.dita.dost.util.OutputUtils; import org.dita.dost.util.StringUtils; import org.dita.dost.util.TimingUtils; import org.dita.dost.util.URLUtils; import org.dita.dost.writer.DitaWriter; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; /** * DebugAndFilterModule implement the second step in preprocess. It will insert debug * information into every dita files and filter out the information that is not * necessary. * * @author Zhang, Yuan Peng */ final class DebugAndFilterModule implements AbstractPipelineModule { /** Subject scheme file extension */ private static final String SUBJECT_SCHEME_EXTENSION = ".subm"; /** * File extension of source file. */ private String extName = null; private File tempDir = null; private final OutputUtils outputUtils = new OutputUtils(); /** * Update property map. * * @param listName name of map to update * @param property property to update */ private void updatePropertyMap(final String listName, final Job property){ final Map<String, String> propValues = property.getMap(listName); if (propValues == null || propValues.isEmpty()){ return; } final Map<String, String> result = new HashMap<String, String>(); for (final Map.Entry<String, String> e: propValues.entrySet()) { String key = e.getKey(); String value = e.getValue(); if (!FILE_EXTENSION_DITAMAP.equals("." + FileUtils.getExtension(value))) { if (extName != null) { key = FileUtils.replaceExtension(key, extName); value = FileUtils.replaceExtension(value, extName); } } result.put(key, value); } property.setMap(listName, result); } /** * Update property set. * * @param listName name of set to update * @param property property to update */ private void updatePropertySet(final String listName, final Job property){ final Set<String> propValues = property.getSet(listName); if (propValues == null || propValues.isEmpty()){ return; } final Set<String> result = new HashSet<String>(propValues.size()); for (final String file: propValues) { String f = file; if (!FILE_EXTENSION_DITAMAP.equals("." + FileUtils.getExtension(file))) { if (extName != null) { f = FileUtils.replaceExtension(f, extName); } } result.add(f); } property.setSet(listName, result); } /** * Update property value. * * @param listName name of value to update * @param property property to update */ private void updatePropertyString(final String listName, final Job property){ String propValue = property.getProperty(listName); if (propValue == null || propValue.trim().length() == 0){ return; } if (!FILE_EXTENSION_DITAMAP.equals("." + FileUtils.getExtension(propValue))) { if (extName != null) { propValue = FileUtils.replaceExtension(propValue, extName); } } property.setProperty(listName, propValue); } private DITAOTLogger logger; /** Absolute input map path. */ private File inputMap = null; /** Absolute DITA-OT base path. */ private File ditaDir = null; /** Absolute input directory path. */ private File inputDir = null; private final boolean setSystemid = true; /** * Default Construtor. */ public DebugAndFilterModule(){ } @Override public void setLogger(final DITAOTLogger logger) { this.logger = logger; } @Override public AbstractPipelineOutput execute(final AbstractPipelineInput input) throws DITAOTException { if (logger == null) { throw new IllegalStateException("Logger not set"); } final Date executeStartTime = TimingUtils.getNowTime(); logger.logInfo("DebugAndFilterModule.execute(): Starting..."); try { final String baseDir = input.getAttribute(ANT_INVOKER_PARAM_BASEDIR); tempDir = new File(input.getAttribute(ANT_INVOKER_PARAM_TEMPDIR)); if (!tempDir.isAbsolute()) { throw new IllegalArgumentException("Temporary directory " + tempDir + " must be absolute"); } ditaDir=new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_DITADIR)); final String transtype = input.getAttribute(ANT_INVOKER_EXT_PARAM_TRANSTYPE); final String ext = input.getAttribute(ANT_INVOKER_PARAM_DITAEXT); if (ext != null) { extName = ext.startsWith(DOT) ? ext : (DOT + ext); } File ditavalFile = null; if (input.getAttribute(ANT_INVOKER_PARAM_DITAVAL) != null ) { ditavalFile = new File(input.getAttribute(ANT_INVOKER_PARAM_DITAVAL)); if (!ditavalFile.isAbsolute()) { ditavalFile = new File(baseDir, ditavalFile.getPath()).getAbsoluteFile(); } } final Job job = new Job(tempDir); final Set<String> parseList = new HashSet<String>(); parseList.addAll(job.getSet(FULL_DITAMAP_TOPIC_LIST)); parseList.addAll(job.getSet(CONREF_TARGET_LIST)); parseList.addAll(job.getSet(COPYTO_SOURCE_LIST)); inputDir = new File(job.getInputDir()); if (!inputDir.isAbsolute()) { inputDir = new File(baseDir, inputDir.getPath()).getAbsoluteFile(); } inputMap = new File(inputDir, job.getInputMap()).getAbsoluteFile(); // Output subject schemas outputSubjectScheme(); final DitaValReader filterReader = new DitaValReader(); filterReader.setLogger(logger); filterReader.initXMLReader("yes".equals(input.getAttribute(ANT_INVOKER_EXT_PARAN_SETSYSTEMID))); FilterUtils filterUtils = new FilterUtils(printTranstype.contains(transtype)); filterUtils.setLogger(logger); if (ditavalFile != null){ filterReader.read(ditavalFile.getAbsolutePath()); filterUtils.setFilterMap(filterReader.getFilterMap()); } final SubjectSchemeReader subjectSchemeReader = new SubjectSchemeReader(); subjectSchemeReader.setLogger(logger); final DitaWriter fileWriter = new DitaWriter(); fileWriter.setLogger(logger); try{ final boolean xmlValidate = Boolean.valueOf(input.getAttribute("validate")); fileWriter.initXMLReader(ditaDir.getAbsoluteFile(),xmlValidate, setSystemid); } catch (final SAXException e) { throw new DITAOTException(e.getMessage(), e); } fileWriter.setTempDir(tempDir); fileWriter.setExtName(extName); fileWriter.setTranstype(transtype); if (filterUtils != null) { fileWriter.setFilterUtils(filterUtils); } fileWriter.setDelayConrefUtils(new DelayConrefUtils()); fileWriter.setKeyDefinitions(KeyDef.readKeydef(new File(tempDir, KEYDEF_LIST_FILE))); outputUtils.setGeneratecopyouter(input.getAttribute(ANT_INVOKER_EXT_PARAM_GENERATECOPYOUTTER)); outputUtils.setOutterControl(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTTERCONTROL)); outputUtils.setOnlyTopicInMap(input.getAttribute(ANT_INVOKER_EXT_PARAM_ONLYTOPICINMAP)); outputUtils.setInputMapPathName(inputMap); outputUtils.setOutputDir(new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTPUTDIR))); fileWriter.setOutputUtils(outputUtils); final Map<String, Set<String>> dic = readMapFromXML(FILE_NAME_SUBJECT_DICTIONARY); for (final String filename: parseList) { final File currentFile = new File(inputDir, filename); logger.logInfo("Processing " + currentFile.getAbsolutePath()); final Set<String> schemaSet = dic.get(filename); filterReader.reset(); if (schemaSet != null) { subjectSchemeReader.reset(); final FilterUtils fu = new FilterUtils(printTranstype.contains(transtype)); fu.setLogger(logger); for (final String schema: schemaSet) { subjectSchemeReader.loadSubjectScheme(FileUtils.resolveFile(tempDir.getAbsolutePath(), schema) + SUBJECT_SCHEME_EXTENSION); } if (ditavalFile != null){ filterReader.filterReset(); filterReader.setSubjectScheme(subjectSchemeReader.getSubjectSchemeMap()); filterReader.read(ditavalFile.getAbsolutePath()); final Map<FilterKey, Action> fm = new HashMap<FilterKey, Action>(); fm.putAll(filterReader.getFilterMap()); fm.putAll(filterUtils.getFilterMap()); fu.setFilterMap(Collections.unmodifiableMap(fm)); } else { - fu.setFilterMap(null); + fu.setFilterMap(Collections.EMPTY_MAP); } fileWriter.setFilterUtils(fu); fileWriter.setValidateMap(subjectSchemeReader.getValidValuesMap()); fileWriter.setDefaultValueMap(subjectSchemeReader.getDefaultValueMap()); } else { fileWriter.setFilterUtils(filterUtils); } if (!new File(inputDir, filename).exists()) { // This is an copy-to target file, ignore it logger.logInfo("Ignoring a copy-to file " + filename); continue; } fileWriter.write(inputDir, filename); } if (extName != null) { updateList(tempDir); } //update dictionary. updateDictionary(tempDir); // reload the property for processing of copy-to performCopytoTask(tempDir, new Job(tempDir)); } catch (final Exception e) { e.printStackTrace(); throw new DITAOTException("Exception doing debug and filter module processing: " + e.getMessage(), e); } finally { logger.logInfo("Execution time: " + TimingUtils.reportElapsedTime(executeStartTime)); } return null; } /** * Read a map from XML properties file. Values are split by {@link org.dita.dost.util.Constants#COMMA COMMA} into a set. * * @param filename XML properties file path, relative to temporary directory */ private Map<String, Set<String>> readMapFromXML(final String filename) { final File inputFile = new File(tempDir, filename); final Map<String, Set<String>> graph = new HashMap<String, Set<String>>(); if (!inputFile.exists()) { return graph; } final Properties prop = new Properties(); FileInputStream in = null; try { in = new FileInputStream(inputFile); prop.loadFromXML(in); in.close(); } catch (final IOException e) { logger.logError(e.getMessage(), e) ; } finally { if (in != null) { try { in.close(); } catch (final IOException e) { logger.logError(e.getMessage(), e) ; } } } for (final Map.Entry<Object, Object> entry: prop.entrySet()) { final String key = (String) entry.getKey(); final String value = (String) entry.getValue(); graph.put(key, StringUtils.restoreSet(value, COMMA)); } return Collections.unmodifiableMap(graph); } /** * Output subject schema file. * * @throws DITAOTException if generation files */ private void outputSubjectScheme() throws DITAOTException { final Map<String, Set<String>> graph = readMapFromXML(FILE_NAME_SUBJECT_RELATION); final Queue<String> queue = new LinkedList<String>(); final Set<String> visitedSet = new HashSet<String>(); for (final Map.Entry<String, Set<String>> entry: graph.entrySet()) { queue.offer(entry.getKey()); } try { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(CatalogUtils.getCatalogResolver()); while (!queue.isEmpty()) { final String parent = queue.poll(); final Set<String> children = graph.get(parent); if (children != null) { queue.addAll(children); } if ("ROOT".equals(parent) || visitedSet.contains(parent)) { continue; } visitedSet.add(parent); String tmprel = FileUtils.getRelativePath(inputMap.getAbsolutePath(), parent); tmprel = FileUtils.resolveFile(tempDir.getAbsolutePath(), tmprel) + SUBJECT_SCHEME_EXTENSION; Document parentRoot = null; if (!FileUtils.fileExists(tmprel)) { parentRoot = builder.parse(new InputSource(new FileInputStream(parent))); } else { parentRoot = builder.parse(new InputSource(new FileInputStream(tmprel))); } if (children != null) { for (final String childpath: children) { final Document childRoot = builder.parse(new InputSource(new FileInputStream(childpath))); mergeScheme(parentRoot, childRoot); String rel = FileUtils.getRelativePath(inputMap.getAbsolutePath(), childpath); rel = FileUtils.resolveFile(tempDir.getAbsolutePath(), rel) + SUBJECT_SCHEME_EXTENSION; generateScheme(rel, childRoot); } } //Output parent scheme String rel = FileUtils.getRelativePath(inputMap.getAbsolutePath(), parent); rel = FileUtils.resolveFile(tempDir.getAbsolutePath(), rel) + SUBJECT_SCHEME_EXTENSION; generateScheme(rel, parentRoot); } } catch (final Exception e) { logger.logError(e.getMessage(), e) ; throw new DITAOTException(e); } } private void mergeScheme(final Document parentRoot, final Document childRoot) { final Queue<Element> pQueue = new LinkedList<Element>(); pQueue.offer(parentRoot.getDocumentElement()); while (!pQueue.isEmpty()) { final Element pe = pQueue.poll(); NodeList pList = pe.getChildNodes(); for (int i = 0; i < pList.getLength(); i++) { final Node node = pList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { pQueue.offer((Element)node); } } String value = pe.getAttribute(ATTRIBUTE_NAME_CLASS); if (StringUtils.isEmptyString(value) || !SUBJECTSCHEME_SUBJECTDEF.matches(value)) { continue; } if (!StringUtils.isEmptyString( value = pe.getAttribute(ATTRIBUTE_NAME_KEYREF))) { // extend child scheme final Element target = searchForKey(childRoot.getDocumentElement(), value); if (target == null) { /* * TODO: we have a keyref here to extend into child scheme, but can't * find any matching <subjectdef> in child scheme. Shall we throw out * a warning? * * Not for now, just bypass it. */ continue; } // target found pList = pe.getChildNodes(); for (int i = 0; i < pList.getLength(); i++) { final Node tmpnode = childRoot.importNode(pList.item(i), false); if (tmpnode.getNodeType() == Node.ELEMENT_NODE && searchForKey(target, ((Element)tmpnode).getAttribute(ATTRIBUTE_NAME_KEYS)) != null) { continue; } target.appendChild(tmpnode); } } else if (!StringUtils.isEmptyString( value = pe.getAttribute(ATTRIBUTE_NAME_KEYS))) { // merge into parent scheme final Element target = searchForKey(childRoot.getDocumentElement(), value); if (target != null) { pList = target.getChildNodes(); for (int i = 0; i < pList.getLength(); i++) { final Node tmpnode = parentRoot.importNode(pList.item(i), false); if (tmpnode.getNodeType() == Node.ELEMENT_NODE && searchForKey(pe, ((Element)tmpnode).getAttribute(ATTRIBUTE_NAME_KEYS)) != null) { continue; } pe.appendChild(tmpnode); } } } } } private Element searchForKey(final Element root, final String key) { if (root == null || StringUtils.isEmptyString(key)) { return null; } final Queue<Element> queue = new LinkedList<Element>(); queue.offer(root); while (!queue.isEmpty()) { final Element pe = queue.poll(); final NodeList pchildrenList = pe.getChildNodes(); for (int i = 0; i < pchildrenList.getLength(); i++) { final Node node = pchildrenList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { queue.offer((Element)node); } } String value = pe.getAttribute(ATTRIBUTE_NAME_CLASS); if (StringUtils.isEmptyString(value) || !SUBJECTSCHEME_SUBJECTDEF.matches(value)) { continue; } value = pe.getAttribute(ATTRIBUTE_NAME_KEYS); if (StringUtils.isEmptyString(value)) { continue; } if (value.equals(key)) { return pe; } } return null; } /** * Serialize subject scheme file. * * @param filename output filepath * @param root subject scheme document * * @throws DITAOTException if generation fails */ private void generateScheme(final String filename, final Document root) throws DITAOTException { try { final File f = new File(filename); final File p = f.getParentFile(); if (!p.exists() && !p.mkdirs()) { throw new IOException("Failed to make directory " + p.getAbsolutePath()); } final FileOutputStream file = new FileOutputStream(new File(filename)); final StreamResult res = new StreamResult(file); final DOMSource ds = new DOMSource(root); final TransformerFactory tff = TransformerFactory.newInstance(); final Transformer tf = tff.newTransformer(); tf.transform(ds, res); if (res.getOutputStream() != null) { res.getOutputStream().close(); } if (file != null) { file.close(); } } catch (final Exception e) { logger.logError(e.getMessage(), e) ; throw new DITAOTException(e); } } /** * Execute copy-to task, generate copy-to targets base on sources */ private void performCopytoTask(final File tempDir, final Job job) { final Map<String, String> copytoMap = job.getCopytoMap(); for (final Map.Entry<String, String> entry: copytoMap.entrySet()) { final String copytoTarget = entry.getKey(); final String copytoSource = entry.getValue(); final File srcFile = new File(tempDir, copytoSource); final File targetFile = new File(tempDir, copytoTarget); if (targetFile.exists()) { /*logger .logWarn(new StringBuffer("Copy-to task [copy-to=\"") .append(copytoTarget) .append("\"] which points to an existed file was ignored.").toString());*/ logger.logWarn(MessageUtils.getInstance().getMessage("DOTX064W", copytoTarget).toString()); }else{ final String inputMapInTemp = new File(tempDir + File.separator + job.getInputMap()).getAbsolutePath(); copyFileWithPIReplaced(srcFile, targetFile, copytoTarget, inputMapInTemp); } } } /** * Copy files and replace workdir PI contents. * * @param src * @param target * @param copytoTargetFilename * @param inputMapInTemp */ public void copyFileWithPIReplaced(final File src, final File target, final String copytoTargetFilename, final String inputMapInTemp ) { if (!target.getParentFile().exists() && !target.getParentFile().mkdirs()) { logger.logError("Failed to create copy-to target directory " + target.getParentFile().getAbsolutePath()); } final DitaWriter dw = new DitaWriter(); dw.setOutputUtils(outputUtils); final String path2project = dw.getPathtoProject(copytoTargetFilename, target, inputMapInTemp); final File workdir = target.getParentFile(); try { final Transformer serializer = TransformerFactory.newInstance().newTransformer(); final XMLFilter filter = new CopyToFilter(StringUtils.getXMLReader(), workdir, path2project); serializer.transform(new SAXSource(filter, new InputSource(src.toURI().toString())), new StreamResult(target)); } catch (final TransformerConfigurationException e) { logger.logError("Failed to configure serializer: " + e.getMessage(), e); } catch (final TransformerFactoryConfigurationError e) { logger.logError("Failed to configure serializer: " + e.getMessage(), e); } catch (final SAXException e) { logger.logError("Failed to create XML parser: " + e.getMessage(), e); } catch (final TransformerException e) { logger.logError("Failed to rewrite copy-to file: " + e.getMessage(), e); } } /** * XML filter to rewrite processing instructions to reflect copy-to location. The following processing-instructions are * * <ul> * <li>{@link DitaWriter#PI_WORKDIR_TARGET PI_WORKDIR_TARGET}</li> * <li>{@link DitaWriter#PI_WORKDIR_TARGET_URI PI_WORKDIR_TARGET_URI}</li> * <li>{@link DitaWriter#PI_PATH2PROJ_TARGET PI_PATH2PROJ_TARGET}</li> * <li>{@link DitaWriter#PI_PATH2PROJ_TARGET_URI PI_PATH2PROJ_TARGET_URI}</li> * </ul> */ private static final class CopyToFilter extends XMLFilterImpl { private final File workdir; private final String path2project; CopyToFilter(final XMLReader parent, final File workdir, final String path2project) { super(parent); this.workdir = workdir; this.path2project = path2project; } @Override public void processingInstruction(final String target, final String data) throws SAXException { String d = data; if(target.equals(PI_WORKDIR_TARGET)) { if (workdir != null) { try { if (OS_NAME.toLowerCase().indexOf(OS_NAME_WINDOWS) == -1) { d = workdir.getCanonicalPath(); } else { d = UNIX_SEPARATOR + workdir.getCanonicalPath(); } } catch (final IOException e) { throw new RuntimeException("Failed to get canonical path for working directory: " + e.getMessage(), e); } } } else if(target.equals(PI_WORKDIR_TARGET_URI)) { if (workdir != null) { d = workdir.toURI().toString(); } } else if (target.equals(PI_PATH2PROJ_TARGET)) { if (path2project != null) { d = path2project; } } else if (target.equals(PI_PATH2PROJ_TARGET_URI)) { if (path2project != null) { d = URLUtils.correct(path2project, true); } } getContentHandler().processingInstruction(target, d); } } /** * Read job configuration, update properties, and serialise. * * @param tempDir temporary directory path * @throws IOException */ private void updateList(final File tempDir) throws IOException{ final Job job = new Job(tempDir); updatePropertyString(INPUT_DITAMAP, job); updatePropertySet(HREF_TARGET_LIST, job); updatePropertySet(CONREF_LIST, job); updatePropertySet(HREF_DITA_TOPIC_LIST, job); updatePropertySet(FULL_DITA_TOPIC_LIST, job); updatePropertySet(FULL_DITAMAP_TOPIC_LIST, job); updatePropertySet(CONREF_TARGET_LIST, job); updatePropertySet(COPYTO_SOURCE_LIST, job); updatePropertyMap(COPYTO_TARGET_TO_SOURCE_MAP_LIST, job); updatePropertySet(OUT_DITA_FILES_LIST, job); updatePropertySet(CONREF_PUSH_LIST, job); updatePropertySet(KEYREF_LIST, job); updatePropertySet(CODEREF_LIST, job); updatePropertySet(CHUNK_TOPIC_LIST, job); updatePropertySet(HREF_TOPIC_LIST, job); updatePropertySet(RESOURCE_ONLY_LIST, job); job.write(); } /** * Update dictionary * * @param tempDir temporary directory */ private void updateDictionary(final File tempDir){ //orignal map final Map<String, Set<String>> dic = readMapFromXML(FILE_NAME_SUBJECT_DICTIONARY); //result map final Map<String, Set<String>> resultMap = new HashMap<String, Set<String>>(); //Iterate the orignal map for (final Map.Entry<String, java.util.Set<String>> entry: dic.entrySet()) { //filename will be checked. String filename = entry.getKey(); if (extName != null) { if(FileUtils.isDITATopicFile(filename)){ //Replace extension name. filename = FileUtils.replaceExtension(filename, extName); } } //put the updated value into the result map resultMap.put(filename, entry.getValue()); } //Write the updated map into the dictionary file this.writeMapToXML(resultMap, FILE_NAME_SUBJECT_DICTIONARY); //File inputFile = new File(tempDir, FILE_NAME_SUBJECT_DICTIONARY); } /** * Method for writing a map into xml file. */ private void writeMapToXML(final Map<String, Set<String>> m, final String filename) { if (m == null) { return; } final Properties prop = new Properties(); for (final Map.Entry<String, Set<String>> entry: m.entrySet()) { final String key = entry.getKey(); final String value = StringUtils.assembleString(entry.getValue(), COMMA); prop.setProperty(key, value); } final File outputFile = new File(tempDir, filename); FileOutputStream os = null; try { os = new FileOutputStream(outputFile, false); prop.storeToXML(os, null); os.close(); } catch (final IOException e) { logger.logError(e.getMessage(), e) ; } finally { if (os != null) { try { os.close(); } catch (final IOException e) { logger.logError(e.getMessage(), e) ; } } } } }
true
true
public AbstractPipelineOutput execute(final AbstractPipelineInput input) throws DITAOTException { if (logger == null) { throw new IllegalStateException("Logger not set"); } final Date executeStartTime = TimingUtils.getNowTime(); logger.logInfo("DebugAndFilterModule.execute(): Starting..."); try { final String baseDir = input.getAttribute(ANT_INVOKER_PARAM_BASEDIR); tempDir = new File(input.getAttribute(ANT_INVOKER_PARAM_TEMPDIR)); if (!tempDir.isAbsolute()) { throw new IllegalArgumentException("Temporary directory " + tempDir + " must be absolute"); } ditaDir=new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_DITADIR)); final String transtype = input.getAttribute(ANT_INVOKER_EXT_PARAM_TRANSTYPE); final String ext = input.getAttribute(ANT_INVOKER_PARAM_DITAEXT); if (ext != null) { extName = ext.startsWith(DOT) ? ext : (DOT + ext); } File ditavalFile = null; if (input.getAttribute(ANT_INVOKER_PARAM_DITAVAL) != null ) { ditavalFile = new File(input.getAttribute(ANT_INVOKER_PARAM_DITAVAL)); if (!ditavalFile.isAbsolute()) { ditavalFile = new File(baseDir, ditavalFile.getPath()).getAbsoluteFile(); } } final Job job = new Job(tempDir); final Set<String> parseList = new HashSet<String>(); parseList.addAll(job.getSet(FULL_DITAMAP_TOPIC_LIST)); parseList.addAll(job.getSet(CONREF_TARGET_LIST)); parseList.addAll(job.getSet(COPYTO_SOURCE_LIST)); inputDir = new File(job.getInputDir()); if (!inputDir.isAbsolute()) { inputDir = new File(baseDir, inputDir.getPath()).getAbsoluteFile(); } inputMap = new File(inputDir, job.getInputMap()).getAbsoluteFile(); // Output subject schemas outputSubjectScheme(); final DitaValReader filterReader = new DitaValReader(); filterReader.setLogger(logger); filterReader.initXMLReader("yes".equals(input.getAttribute(ANT_INVOKER_EXT_PARAN_SETSYSTEMID))); FilterUtils filterUtils = new FilterUtils(printTranstype.contains(transtype)); filterUtils.setLogger(logger); if (ditavalFile != null){ filterReader.read(ditavalFile.getAbsolutePath()); filterUtils.setFilterMap(filterReader.getFilterMap()); } final SubjectSchemeReader subjectSchemeReader = new SubjectSchemeReader(); subjectSchemeReader.setLogger(logger); final DitaWriter fileWriter = new DitaWriter(); fileWriter.setLogger(logger); try{ final boolean xmlValidate = Boolean.valueOf(input.getAttribute("validate")); fileWriter.initXMLReader(ditaDir.getAbsoluteFile(),xmlValidate, setSystemid); } catch (final SAXException e) { throw new DITAOTException(e.getMessage(), e); } fileWriter.setTempDir(tempDir); fileWriter.setExtName(extName); fileWriter.setTranstype(transtype); if (filterUtils != null) { fileWriter.setFilterUtils(filterUtils); } fileWriter.setDelayConrefUtils(new DelayConrefUtils()); fileWriter.setKeyDefinitions(KeyDef.readKeydef(new File(tempDir, KEYDEF_LIST_FILE))); outputUtils.setGeneratecopyouter(input.getAttribute(ANT_INVOKER_EXT_PARAM_GENERATECOPYOUTTER)); outputUtils.setOutterControl(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTTERCONTROL)); outputUtils.setOnlyTopicInMap(input.getAttribute(ANT_INVOKER_EXT_PARAM_ONLYTOPICINMAP)); outputUtils.setInputMapPathName(inputMap); outputUtils.setOutputDir(new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTPUTDIR))); fileWriter.setOutputUtils(outputUtils); final Map<String, Set<String>> dic = readMapFromXML(FILE_NAME_SUBJECT_DICTIONARY); for (final String filename: parseList) { final File currentFile = new File(inputDir, filename); logger.logInfo("Processing " + currentFile.getAbsolutePath()); final Set<String> schemaSet = dic.get(filename); filterReader.reset(); if (schemaSet != null) { subjectSchemeReader.reset(); final FilterUtils fu = new FilterUtils(printTranstype.contains(transtype)); fu.setLogger(logger); for (final String schema: schemaSet) { subjectSchemeReader.loadSubjectScheme(FileUtils.resolveFile(tempDir.getAbsolutePath(), schema) + SUBJECT_SCHEME_EXTENSION); } if (ditavalFile != null){ filterReader.filterReset(); filterReader.setSubjectScheme(subjectSchemeReader.getSubjectSchemeMap()); filterReader.read(ditavalFile.getAbsolutePath()); final Map<FilterKey, Action> fm = new HashMap<FilterKey, Action>(); fm.putAll(filterReader.getFilterMap()); fm.putAll(filterUtils.getFilterMap()); fu.setFilterMap(Collections.unmodifiableMap(fm)); } else { fu.setFilterMap(null); } fileWriter.setFilterUtils(fu); fileWriter.setValidateMap(subjectSchemeReader.getValidValuesMap()); fileWriter.setDefaultValueMap(subjectSchemeReader.getDefaultValueMap()); } else { fileWriter.setFilterUtils(filterUtils); } if (!new File(inputDir, filename).exists()) { // This is an copy-to target file, ignore it logger.logInfo("Ignoring a copy-to file " + filename); continue; } fileWriter.write(inputDir, filename); } if (extName != null) { updateList(tempDir); } //update dictionary. updateDictionary(tempDir); // reload the property for processing of copy-to performCopytoTask(tempDir, new Job(tempDir)); } catch (final Exception e) { e.printStackTrace(); throw new DITAOTException("Exception doing debug and filter module processing: " + e.getMessage(), e); } finally { logger.logInfo("Execution time: " + TimingUtils.reportElapsedTime(executeStartTime)); } return null; }
public AbstractPipelineOutput execute(final AbstractPipelineInput input) throws DITAOTException { if (logger == null) { throw new IllegalStateException("Logger not set"); } final Date executeStartTime = TimingUtils.getNowTime(); logger.logInfo("DebugAndFilterModule.execute(): Starting..."); try { final String baseDir = input.getAttribute(ANT_INVOKER_PARAM_BASEDIR); tempDir = new File(input.getAttribute(ANT_INVOKER_PARAM_TEMPDIR)); if (!tempDir.isAbsolute()) { throw new IllegalArgumentException("Temporary directory " + tempDir + " must be absolute"); } ditaDir=new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_DITADIR)); final String transtype = input.getAttribute(ANT_INVOKER_EXT_PARAM_TRANSTYPE); final String ext = input.getAttribute(ANT_INVOKER_PARAM_DITAEXT); if (ext != null) { extName = ext.startsWith(DOT) ? ext : (DOT + ext); } File ditavalFile = null; if (input.getAttribute(ANT_INVOKER_PARAM_DITAVAL) != null ) { ditavalFile = new File(input.getAttribute(ANT_INVOKER_PARAM_DITAVAL)); if (!ditavalFile.isAbsolute()) { ditavalFile = new File(baseDir, ditavalFile.getPath()).getAbsoluteFile(); } } final Job job = new Job(tempDir); final Set<String> parseList = new HashSet<String>(); parseList.addAll(job.getSet(FULL_DITAMAP_TOPIC_LIST)); parseList.addAll(job.getSet(CONREF_TARGET_LIST)); parseList.addAll(job.getSet(COPYTO_SOURCE_LIST)); inputDir = new File(job.getInputDir()); if (!inputDir.isAbsolute()) { inputDir = new File(baseDir, inputDir.getPath()).getAbsoluteFile(); } inputMap = new File(inputDir, job.getInputMap()).getAbsoluteFile(); // Output subject schemas outputSubjectScheme(); final DitaValReader filterReader = new DitaValReader(); filterReader.setLogger(logger); filterReader.initXMLReader("yes".equals(input.getAttribute(ANT_INVOKER_EXT_PARAN_SETSYSTEMID))); FilterUtils filterUtils = new FilterUtils(printTranstype.contains(transtype)); filterUtils.setLogger(logger); if (ditavalFile != null){ filterReader.read(ditavalFile.getAbsolutePath()); filterUtils.setFilterMap(filterReader.getFilterMap()); } final SubjectSchemeReader subjectSchemeReader = new SubjectSchemeReader(); subjectSchemeReader.setLogger(logger); final DitaWriter fileWriter = new DitaWriter(); fileWriter.setLogger(logger); try{ final boolean xmlValidate = Boolean.valueOf(input.getAttribute("validate")); fileWriter.initXMLReader(ditaDir.getAbsoluteFile(),xmlValidate, setSystemid); } catch (final SAXException e) { throw new DITAOTException(e.getMessage(), e); } fileWriter.setTempDir(tempDir); fileWriter.setExtName(extName); fileWriter.setTranstype(transtype); if (filterUtils != null) { fileWriter.setFilterUtils(filterUtils); } fileWriter.setDelayConrefUtils(new DelayConrefUtils()); fileWriter.setKeyDefinitions(KeyDef.readKeydef(new File(tempDir, KEYDEF_LIST_FILE))); outputUtils.setGeneratecopyouter(input.getAttribute(ANT_INVOKER_EXT_PARAM_GENERATECOPYOUTTER)); outputUtils.setOutterControl(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTTERCONTROL)); outputUtils.setOnlyTopicInMap(input.getAttribute(ANT_INVOKER_EXT_PARAM_ONLYTOPICINMAP)); outputUtils.setInputMapPathName(inputMap); outputUtils.setOutputDir(new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTPUTDIR))); fileWriter.setOutputUtils(outputUtils); final Map<String, Set<String>> dic = readMapFromXML(FILE_NAME_SUBJECT_DICTIONARY); for (final String filename: parseList) { final File currentFile = new File(inputDir, filename); logger.logInfo("Processing " + currentFile.getAbsolutePath()); final Set<String> schemaSet = dic.get(filename); filterReader.reset(); if (schemaSet != null) { subjectSchemeReader.reset(); final FilterUtils fu = new FilterUtils(printTranstype.contains(transtype)); fu.setLogger(logger); for (final String schema: schemaSet) { subjectSchemeReader.loadSubjectScheme(FileUtils.resolveFile(tempDir.getAbsolutePath(), schema) + SUBJECT_SCHEME_EXTENSION); } if (ditavalFile != null){ filterReader.filterReset(); filterReader.setSubjectScheme(subjectSchemeReader.getSubjectSchemeMap()); filterReader.read(ditavalFile.getAbsolutePath()); final Map<FilterKey, Action> fm = new HashMap<FilterKey, Action>(); fm.putAll(filterReader.getFilterMap()); fm.putAll(filterUtils.getFilterMap()); fu.setFilterMap(Collections.unmodifiableMap(fm)); } else { fu.setFilterMap(Collections.EMPTY_MAP); } fileWriter.setFilterUtils(fu); fileWriter.setValidateMap(subjectSchemeReader.getValidValuesMap()); fileWriter.setDefaultValueMap(subjectSchemeReader.getDefaultValueMap()); } else { fileWriter.setFilterUtils(filterUtils); } if (!new File(inputDir, filename).exists()) { // This is an copy-to target file, ignore it logger.logInfo("Ignoring a copy-to file " + filename); continue; } fileWriter.write(inputDir, filename); } if (extName != null) { updateList(tempDir); } //update dictionary. updateDictionary(tempDir); // reload the property for processing of copy-to performCopytoTask(tempDir, new Job(tempDir)); } catch (final Exception e) { e.printStackTrace(); throw new DITAOTException("Exception doing debug and filter module processing: " + e.getMessage(), e); } finally { logger.logInfo("Execution time: " + TimingUtils.reportElapsedTime(executeStartTime)); } return null; }
diff --git a/src/org/meta_environment/rascal/interpreter/errors/SyntaxError.java b/src/org/meta_environment/rascal/interpreter/errors/SyntaxError.java index 3c32c15932..fdb60752d4 100644 --- a/src/org/meta_environment/rascal/interpreter/errors/SyntaxError.java +++ b/src/org/meta_environment/rascal/interpreter/errors/SyntaxError.java @@ -1,16 +1,16 @@ package org.meta_environment.rascal.interpreter.errors; import org.meta_environment.rascal.ast.AbstractAST; public class SyntaxError extends Error { private static final long serialVersionUID = 333331541118811177L; //TODO: remove public SyntaxError(String message) { - super(null, message); + super("SyntaxError", message); } public SyntaxError(String message, AbstractAST node) { super("SyntaxError", message, node); } }
true
true
public SyntaxError(String message) { super(null, message); }
public SyntaxError(String message) { super("SyntaxError", message); }
diff --git a/src/test/java/pt/go2/keystore/HashKeyTest.java b/src/test/java/pt/go2/keystore/HashKeyTest.java index 788c858..37fc76d 100644 --- a/src/test/java/pt/go2/keystore/HashKeyTest.java +++ b/src/test/java/pt/go2/keystore/HashKeyTest.java @@ -1,51 +1,51 @@ /** * */ package pt.go2.keystore; import org.junit.Assert; import org.junit.Test; /** * * @author vilaca * */ public class HashKeyTest { @Test public void testCloning() { HashKey hk5 = new HashKey(); - HashKey hk6 = new HashKey(hk5.getBytes()); + HashKey hk6 = new HashKey(hk5.toString()); Assert.assertTrue(hk5.equals(hk6)); HashKey hk9 = new HashKey(); - HashKey hk10 = new HashKey(hk9.getBytes()); + HashKey hk10 = new HashKey(hk9.toString()); Assert.assertTrue(hk9.equals(hk10)); HashKey hk11 = new HashKey(); - HashKey hk12 = new HashKey(hk11.getBytes()); + HashKey hk12 = new HashKey(hk11.toString()); Assert.assertTrue(hk11.equals(hk12)); - HashKey hk1 = new HashKey("aaaaa0".getBytes()); - HashKey hk2 = new HashKey(hk1.getBytes()); + HashKey hk1 = new HashKey("aaaaa0"); + HashKey hk2 = new HashKey(hk1.toString()); Assert.assertTrue(hk1.equals(hk2)); - HashKey hk3 = new HashKey("aAbCeF".getBytes()); - HashKey hk4 = new HashKey(hk3.getBytes()); + HashKey hk3 = new HashKey("aAbCeF"); + HashKey hk4 = new HashKey(hk3.toString()); Assert.assertTrue(hk3.equals(hk4)); - HashKey hk7 = new HashKey("------".getBytes()); - HashKey hk8 = new HashKey(hk7.getBytes()); + HashKey hk7 = new HashKey("------"); + HashKey hk8 = new HashKey(hk7.toString()); Assert.assertTrue(hk7.equals(hk8)); } }
false
true
public void testCloning() { HashKey hk5 = new HashKey(); HashKey hk6 = new HashKey(hk5.getBytes()); Assert.assertTrue(hk5.equals(hk6)); HashKey hk9 = new HashKey(); HashKey hk10 = new HashKey(hk9.getBytes()); Assert.assertTrue(hk9.equals(hk10)); HashKey hk11 = new HashKey(); HashKey hk12 = new HashKey(hk11.getBytes()); Assert.assertTrue(hk11.equals(hk12)); HashKey hk1 = new HashKey("aaaaa0".getBytes()); HashKey hk2 = new HashKey(hk1.getBytes()); Assert.assertTrue(hk1.equals(hk2)); HashKey hk3 = new HashKey("aAbCeF".getBytes()); HashKey hk4 = new HashKey(hk3.getBytes()); Assert.assertTrue(hk3.equals(hk4)); HashKey hk7 = new HashKey("------".getBytes()); HashKey hk8 = new HashKey(hk7.getBytes()); Assert.assertTrue(hk7.equals(hk8)); }
public void testCloning() { HashKey hk5 = new HashKey(); HashKey hk6 = new HashKey(hk5.toString()); Assert.assertTrue(hk5.equals(hk6)); HashKey hk9 = new HashKey(); HashKey hk10 = new HashKey(hk9.toString()); Assert.assertTrue(hk9.equals(hk10)); HashKey hk11 = new HashKey(); HashKey hk12 = new HashKey(hk11.toString()); Assert.assertTrue(hk11.equals(hk12)); HashKey hk1 = new HashKey("aaaaa0"); HashKey hk2 = new HashKey(hk1.toString()); Assert.assertTrue(hk1.equals(hk2)); HashKey hk3 = new HashKey("aAbCeF"); HashKey hk4 = new HashKey(hk3.toString()); Assert.assertTrue(hk3.equals(hk4)); HashKey hk7 = new HashKey("------"); HashKey hk8 = new HashKey(hk7.toString()); Assert.assertTrue(hk7.equals(hk8)); }
diff --git a/src/org/jacorb/ir/Container.java b/src/org/jacorb/ir/Container.java index 6e5e68561..f5bf9851f 100644 --- a/src/org/jacorb/ir/Container.java +++ b/src/org/jacorb/ir/Container.java @@ -1,546 +1,546 @@ package org.jacorb.ir; /* * JacORB - a free Java ORB * * Copyright (C) 1997-2011 Gerald Brose / The JacORB Team. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ import java.io.File; import java.util.Enumeration; import java.util.Hashtable; import org.omg.CORBA.AbstractInterfaceDef; import org.omg.CORBA.ExtInitializer; import org.omg.CORBA.ExtValueDef; import org.omg.CORBA.INTF_REPOS; import org.omg.CORBA.InterfaceDef; import org.omg.CORBA.LocalInterfaceDef; import org.omg.CORBA.NO_IMPLEMENT; import org.omg.CORBA.ValueDef; import org.omg.PortableServer.POA; import org.slf4j.Logger; public class Container extends IRObject implements org.omg.CORBA.ContainerOperations { protected IRObject delegator; /** CORBA references to contained objects */ protected Hashtable contained = new Hashtable(); /** local references to contained objects */ protected Hashtable containedLocals = new Hashtable(); protected File my_dir = null; protected String path = null; protected String full_name = null; /** CORBA reference to this container */ protected org.omg.CORBA.Container this_container; /** outer container */ protected org.omg.CORBA.Container defined_in; protected org.omg.CORBA.Repository containing_repository; protected boolean defined = false; private ClassLoader loader; private POA poa; private Logger logger; /** */ public Container( IRObject delegator, String path, String full_name, ClassLoader loader, POA poa, Logger logger ) { this.loader = loader; this.poa = poa; this.logger = logger; this.delegator = delegator; this.path = path; this.full_name = full_name; my_dir = new File( path + fileSeparator + ( full_name != null ? full_name : "" ).replace('.', fileSeparator) ); if ( ! my_dir.isDirectory()) { throw new INTF_REPOS ("no directory : " + path + fileSeparator + full_name); } this.name = delegator.getName(); if (this.logger.isDebugEnabled()) { this.logger.debug("New Container full_name " + full_name + " name : " + name + " path: " + path); } // else: get reference from delegator, but must be postponed until later } /** */ void loadContents() { this_container = org.omg.CORBA.ContainerHelper.narrow( delegator.getReference()); if (this_container == null) { throw new INTF_REPOS ("no container !"); } if( delegator instanceof Contained ) { containing_repository = ((Contained)delegator).containing_repository(); defined_in = ((Contained)delegator).defined_in(); } else { containing_repository = org.omg.CORBA. RepositoryHelper.narrow( delegator.getReference()); defined_in = containing_repository; } if (containing_repository == null) { throw new INTF_REPOS ("no containing repository"); } String[] classes; String[] dirs; // get all files in this directory which either end in ".class" or // do not contain a "." at all classes = my_dir.list( new IRFilenameFilter(".class") ); dirs = my_dir.list( new IRFilenameFilter( null ) ); // load class files in this module/package if( classes != null) { String prefix = ( full_name != null ? full_name + '.' : ""); for( int j = 0; j< classes.length; j++ ) { try { if (this.logger.isDebugEnabled()) { this.logger.debug("Container " +name+ " tries " + prefix + classes[j].substring( 0, classes[j].indexOf(".class"))); } Class cl = this.loader.loadClass( ( prefix + classes[j].substring( 0, classes[j].indexOf(".class")) )); Contained containedObject = Contained.createContained( cl, path, this_container, containing_repository, this.logger, this.loader, this.poa ); if( containedObject == null ) { if (this.logger.isDebugEnabled()) { this.logger.debug("Container: nothing created for " + cl.getClass().getName()); } continue; } org.omg.CORBA.Contained containedRef = Contained.createContainedReference(containedObject, this.logger, this.poa); containedRef.move( this_container, containedRef.name(), containedRef.version() ); if (this.logger.isDebugEnabled()) { this.logger.debug("Container " + prefix + " loads "+ containedRef.name()); } contained.put( containedRef.name() , containedRef ); containedLocals.put( containedRef.name(), containedObject ); if( containedObject instanceof ContainerType ) ((ContainerType)containedObject).loadContents(); } catch ( java.lang.Throwable e ) { this.logger.error("Caught exception", e); } } } if( dirs != null) { for( int k = 0; k < dirs.length; k++ ) { if( !dirs[k].endsWith("Package")) { File f = new File( my_dir.getAbsolutePath() + fileSeparator + dirs[k] ); try { String [] classList = f.list(); if( classList != null && classList.length > 0) { ModuleDef m = new ModuleDef( path, (( full_name != null ? full_name + fileSeparator : "" - ) + dirs[k]).replace('/', '.'), + ) + dirs[k]).replace(fileSeparator, '.'), this_container, containing_repository, this.loader, this.poa, this.logger); org.omg.CORBA.ModuleDef moduleRef = org.omg.CORBA.ModuleDefHelper.narrow( this.poa.servant_to_reference( new org.omg.CORBA.ModuleDefPOATie( m ) )); m.setReference( moduleRef ); m.loadContents(); if (this.logger.isDebugEnabled()) { this.logger.debug("Container " + full_name + " puts module " + dirs[k]); } m.move( this_container, m.name(), m.version() ); contained.put( m.name() , moduleRef ); containedLocals.put( m.name(), m ); } } catch ( Exception e ) { this.logger.error("Caught Exception", e); } } } } } void define() { if (this.logger.isDebugEnabled()) { this.logger.debug("Container " + full_name + " defining..."); } for( Enumeration e = containedLocals.elements(); e.hasMoreElements(); ((IRObject)e.nextElement()).define()) ; defined = true; if (this.logger.isDebugEnabled()) { this.logger.debug("Container " + full_name + " defined"); } } public org.omg.CORBA.Contained[] contents(org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) { if ( ! defined) { throw new INTF_REPOS ("contents undefined"); } Hashtable filtered = new Hashtable(); if( limit_type.value() == org.omg.CORBA.DefinitionKind._dk_all ) { filtered = contained; } else { Enumeration f = contained.keys(); while( f.hasMoreElements() ) { Object k = f.nextElement(); org.omg.CORBA.Contained c = (org.omg.CORBA.Contained)contained.get( k ); if( c.def_kind().value() == limit_type.value() ) filtered.put( k, c ); } } Enumeration e = filtered.elements(); org.omg.CORBA.Contained[] result = new org.omg.CORBA.Contained[ filtered.size() ]; for( int i = 0; i < filtered.size(); i++ ) result[i] = (org.omg.CORBA.Contained)e.nextElement(); return result; } /** * retrieves a contained object given a scoped name */ public org.omg.CORBA.Contained lookup( String scopedname ) { String top_level_name; String rest_of_name; String name; if( scopedname.startsWith("::") ) { name = scopedname.substring(2); } else name = scopedname; if( name.indexOf("::") > 0 ) { top_level_name = name.substring( 0, name.indexOf("::") ); rest_of_name = name.substring( name.indexOf("::") + 2); } else { top_level_name = name; rest_of_name = null; } org.omg.CORBA.Contained top = (org.omg.CORBA.Contained)contained.get( top_level_name ); if( top == null ) { if (this.logger.isDebugEnabled()) { this.logger.debug("Container " + this.name + " top " + top_level_name + " not found "); } return null; } if( rest_of_name == null ) { return top; } org.omg.CORBA.Container topContainer = org.omg.CORBA.ContainerHelper.narrow( top ); if( topContainer != null ) { return topContainer.lookup( rest_of_name ); } if (this.logger.isDebugEnabled()) { this.logger.debug("Container " + this.name +" " + scopedname + " not found, top " + top.getClass().getName()); } return null; } public org.omg.CORBA.Contained[] lookup_name( String search_name, int levels_to_search, org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) { if( levels_to_search == 0 ) return null; org.omg.CORBA.Contained[] c = contents( limit_type, exclude_inherited ); Hashtable found = new Hashtable(); for( int i = 0; i < c.length; i++) if( c[i].name().equals( search_name ) ) found.put( c[i], "" ); if( levels_to_search > 1 || levels_to_search == -1 ) { // search up to a specific depth or undefinitely for( int i = 0; i < c.length; i++) { if( c[i] instanceof org.omg.CORBA.Container ) { org.omg.CORBA.Contained[] tmp_seq = ((org.omg.CORBA.Container)c[i]).lookup_name( search_name, levels_to_search-1, limit_type, exclude_inherited); if( tmp_seq != null ) for( int j = 0; j < tmp_seq.length; j++) found.put( tmp_seq[j], "" ); } } } org.omg.CORBA.Contained[] result = new org.omg.CORBA.Contained[ found.size() ]; int idx = 0; for( Enumeration e = found.keys(); e.hasMoreElements(); ) result[ idx++] = (org.omg.CORBA.Contained)e.nextElement(); return result; } public org.omg.CORBA.ContainerPackage.Description[] describe_contents(org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) { return null; } public org.omg.CORBA.ModuleDef create_module(/*RepositoryId*/ String id, /*Identifier*/ String name, /*VersionSpec*/ String version){ return null; } public org.omg.CORBA.ConstantDef create_constant(/*RepositoryId*/ String id, /*Identifier*/ String name, /*VersionSpec*/ String version, org.omg.CORBA.IDLType type, org.omg.CORBA.Any value){ return null; } public org.omg.CORBA.StructDef create_struct(/*RepositoryId*/ String id, /*Identifier*/ String name, /*VersionSpec*/ String version, /*StructMemberSeq*/ org.omg.CORBA.StructMember[] members){ return null; } public org.omg.CORBA.UnionDef create_union(/*RepositoryId*/ String id, /*Identifier*/ String name, /*VersionSpec*/ String version, org.omg.CORBA.IDLType discriminator_type, /*UnionMemberSeq*/ org.omg.CORBA.UnionMember[] members){ return null; } public org.omg.CORBA.EnumDef create_enum(/*RepositoryId*/ String id, /*Identifier*/ String name, /*VersionSpec*/ String version, /*EnumMemberSeq*/ /*Identifier*/ String[] members){ return null; } public org.omg.CORBA.AliasDef create_alias(/*RepositoryId*/ String id, /*Identifier*/ String name, /*VersionSpec*/ String version, org.omg.CORBA.IDLType original_type){ return null; } /** * not supported */ public org.omg.CORBA.ExceptionDef create_exception(java.lang.String id, java.lang.String name , java.lang.String version, org.omg.CORBA.StructMember[] member ) { return null; } /** * not supported */ public org.omg.CORBA.InterfaceDef create_interface( /*RepositoryId*/ String id, /*Identifier*/ String name, /*VersionSpec*/ String version, /*InterfaceDefSeq*/ org.omg.CORBA.InterfaceDef[] base_interfaces) { return null; } /** * not supported */ public org.omg.CORBA.ValueBoxDef create_value_box(java.lang.String id, java.lang.String name, java.lang.String version, org.omg.CORBA.IDLType type) { return null; } /** * not supported */ public org.omg.CORBA.ValueDef create_value( java.lang.String id, java.lang.String name, java.lang.String version, boolean is_custom, boolean is_abstract, org.omg.CORBA.ValueDef base_value, boolean is_truncatable, org.omg.CORBA.ValueDef[] abstract_base_values, org.omg.CORBA.InterfaceDef[] supported_interfaces, org.omg.CORBA.Initializer[] initializers) { return null; } /** * not supported */ public org.omg.CORBA.NativeDef create_native(java.lang.String id, java.lang.String name, java.lang.String version) { return null; } public void destroy(){} public AbstractInterfaceDef create_abstract_interface (String id, String name, String version, AbstractInterfaceDef[] baseInterfaces) { throw new NO_IMPLEMENT ("NYI"); } public ExtValueDef create_ext_value (String id, String name, String version, boolean isCustom, boolean isAbstract, ValueDef baseValue, boolean isTruncatable, ValueDef[] abstractBaseValues, InterfaceDef[] supportedInterfaces, ExtInitializer[] initializers) { throw new NO_IMPLEMENT ("NYI"); } public LocalInterfaceDef create_local_interface (String id, String name, String version, InterfaceDef[] baseInterfaces) { throw new NO_IMPLEMENT ("NYI"); } }
true
true
void loadContents() { this_container = org.omg.CORBA.ContainerHelper.narrow( delegator.getReference()); if (this_container == null) { throw new INTF_REPOS ("no container !"); } if( delegator instanceof Contained ) { containing_repository = ((Contained)delegator).containing_repository(); defined_in = ((Contained)delegator).defined_in(); } else { containing_repository = org.omg.CORBA. RepositoryHelper.narrow( delegator.getReference()); defined_in = containing_repository; } if (containing_repository == null) { throw new INTF_REPOS ("no containing repository"); } String[] classes; String[] dirs; // get all files in this directory which either end in ".class" or // do not contain a "." at all classes = my_dir.list( new IRFilenameFilter(".class") ); dirs = my_dir.list( new IRFilenameFilter( null ) ); // load class files in this module/package if( classes != null) { String prefix = ( full_name != null ? full_name + '.' : ""); for( int j = 0; j< classes.length; j++ ) { try { if (this.logger.isDebugEnabled()) { this.logger.debug("Container " +name+ " tries " + prefix + classes[j].substring( 0, classes[j].indexOf(".class"))); } Class cl = this.loader.loadClass( ( prefix + classes[j].substring( 0, classes[j].indexOf(".class")) )); Contained containedObject = Contained.createContained( cl, path, this_container, containing_repository, this.logger, this.loader, this.poa ); if( containedObject == null ) { if (this.logger.isDebugEnabled()) { this.logger.debug("Container: nothing created for " + cl.getClass().getName()); } continue; } org.omg.CORBA.Contained containedRef = Contained.createContainedReference(containedObject, this.logger, this.poa); containedRef.move( this_container, containedRef.name(), containedRef.version() ); if (this.logger.isDebugEnabled()) { this.logger.debug("Container " + prefix + " loads "+ containedRef.name()); } contained.put( containedRef.name() , containedRef ); containedLocals.put( containedRef.name(), containedObject ); if( containedObject instanceof ContainerType ) ((ContainerType)containedObject).loadContents(); } catch ( java.lang.Throwable e ) { this.logger.error("Caught exception", e); } } } if( dirs != null) { for( int k = 0; k < dirs.length; k++ ) { if( !dirs[k].endsWith("Package")) { File f = new File( my_dir.getAbsolutePath() + fileSeparator + dirs[k] ); try { String [] classList = f.list(); if( classList != null && classList.length > 0) { ModuleDef m = new ModuleDef( path, (( full_name != null ? full_name + fileSeparator : "" ) + dirs[k]).replace('/', '.'), this_container, containing_repository, this.loader, this.poa, this.logger); org.omg.CORBA.ModuleDef moduleRef = org.omg.CORBA.ModuleDefHelper.narrow( this.poa.servant_to_reference( new org.omg.CORBA.ModuleDefPOATie( m ) )); m.setReference( moduleRef ); m.loadContents(); if (this.logger.isDebugEnabled()) { this.logger.debug("Container " + full_name + " puts module " + dirs[k]); } m.move( this_container, m.name(), m.version() ); contained.put( m.name() , moduleRef ); containedLocals.put( m.name(), m ); } } catch ( Exception e ) { this.logger.error("Caught Exception", e); } } } } }
void loadContents() { this_container = org.omg.CORBA.ContainerHelper.narrow( delegator.getReference()); if (this_container == null) { throw new INTF_REPOS ("no container !"); } if( delegator instanceof Contained ) { containing_repository = ((Contained)delegator).containing_repository(); defined_in = ((Contained)delegator).defined_in(); } else { containing_repository = org.omg.CORBA. RepositoryHelper.narrow( delegator.getReference()); defined_in = containing_repository; } if (containing_repository == null) { throw new INTF_REPOS ("no containing repository"); } String[] classes; String[] dirs; // get all files in this directory which either end in ".class" or // do not contain a "." at all classes = my_dir.list( new IRFilenameFilter(".class") ); dirs = my_dir.list( new IRFilenameFilter( null ) ); // load class files in this module/package if( classes != null) { String prefix = ( full_name != null ? full_name + '.' : ""); for( int j = 0; j< classes.length; j++ ) { try { if (this.logger.isDebugEnabled()) { this.logger.debug("Container " +name+ " tries " + prefix + classes[j].substring( 0, classes[j].indexOf(".class"))); } Class cl = this.loader.loadClass( ( prefix + classes[j].substring( 0, classes[j].indexOf(".class")) )); Contained containedObject = Contained.createContained( cl, path, this_container, containing_repository, this.logger, this.loader, this.poa ); if( containedObject == null ) { if (this.logger.isDebugEnabled()) { this.logger.debug("Container: nothing created for " + cl.getClass().getName()); } continue; } org.omg.CORBA.Contained containedRef = Contained.createContainedReference(containedObject, this.logger, this.poa); containedRef.move( this_container, containedRef.name(), containedRef.version() ); if (this.logger.isDebugEnabled()) { this.logger.debug("Container " + prefix + " loads "+ containedRef.name()); } contained.put( containedRef.name() , containedRef ); containedLocals.put( containedRef.name(), containedObject ); if( containedObject instanceof ContainerType ) ((ContainerType)containedObject).loadContents(); } catch ( java.lang.Throwable e ) { this.logger.error("Caught exception", e); } } } if( dirs != null) { for( int k = 0; k < dirs.length; k++ ) { if( !dirs[k].endsWith("Package")) { File f = new File( my_dir.getAbsolutePath() + fileSeparator + dirs[k] ); try { String [] classList = f.list(); if( classList != null && classList.length > 0) { ModuleDef m = new ModuleDef( path, (( full_name != null ? full_name + fileSeparator : "" ) + dirs[k]).replace(fileSeparator, '.'), this_container, containing_repository, this.loader, this.poa, this.logger); org.omg.CORBA.ModuleDef moduleRef = org.omg.CORBA.ModuleDefHelper.narrow( this.poa.servant_to_reference( new org.omg.CORBA.ModuleDefPOATie( m ) )); m.setReference( moduleRef ); m.loadContents(); if (this.logger.isDebugEnabled()) { this.logger.debug("Container " + full_name + " puts module " + dirs[k]); } m.move( this_container, m.name(), m.version() ); contained.put( m.name() , moduleRef ); containedLocals.put( m.name(), m ); } } catch ( Exception e ) { this.logger.error("Caught Exception", e); } } } } }
diff --git a/src/main/com/xuechong/utils/exl/process/builder/ExlBuilderUtil.java b/src/main/com/xuechong/utils/exl/process/builder/ExlBuilderUtil.java index 2674164..da5a993 100644 --- a/src/main/com/xuechong/utils/exl/process/builder/ExlBuilderUtil.java +++ b/src/main/com/xuechong/utils/exl/process/builder/ExlBuilderUtil.java @@ -1,35 +1,35 @@ package com.xuechong.utils.exl.process.builder; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellRangeAddress; public class ExlBuilderUtil { /** * merg cal<br> * cal the num of merg cloumns * * @param contentStr * @param row * @return * @author xuechong */ static CellRangeAddress createMergRegion(String contentStr, Integer row) { int width = contentStr.length() / 2 + 1; return new CellRangeAddress(row, row, 0, width > 6 ? width : 6); } /** * expend the column width * @param dataLength * @param columnIndex * @param sheet * @author xuechong */ static void expendColumnWidth(int dataLength,int columnIndex,Sheet sheet){ int expectLength = (dataLength<<9); if( dataLength > 4 &&sheet.getColumnWidth(columnIndex) < expectLength){ - sheet.setColumnWidth(columnIndex,expectLength); + sheet.setColumnWidth(columnIndex,expectLength>255*256?255*256:expectLength); } } }
true
true
static void expendColumnWidth(int dataLength,int columnIndex,Sheet sheet){ int expectLength = (dataLength<<9); if( dataLength > 4 &&sheet.getColumnWidth(columnIndex) < expectLength){ sheet.setColumnWidth(columnIndex,expectLength); } }
static void expendColumnWidth(int dataLength,int columnIndex,Sheet sheet){ int expectLength = (dataLength<<9); if( dataLength > 4 &&sheet.getColumnWidth(columnIndex) < expectLength){ sheet.setColumnWidth(columnIndex,expectLength>255*256?255*256:expectLength); } }
diff --git a/java/src/com/yuktix/rest/exception/ThrowableMapper.java b/java/src/com/yuktix/rest/exception/ThrowableMapper.java index b72d48d..72ad473 100644 --- a/java/src/com/yuktix/rest/exception/ThrowableMapper.java +++ b/java/src/com/yuktix/rest/exception/ThrowableMapper.java @@ -1,46 +1,46 @@ package com.yuktix.rest.exception; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import com.yuktix.dto.response.ErrorBean; import com.yuktix.util.Log; /* mapper class to catch jersey runtime errors */ @Provider public class ThrowableMapper implements ExceptionMapper<Throwable> { @Override public Response toResponse(Throwable ex) { Log.error(ex.getMessage(), ex); String message = "Internal service error" ; Status status = Status.INTERNAL_SERVER_ERROR ; // jackson json parsing exception // @todo - jersey exception contains stack trace if(ex instanceof org.codehaus.jackson.JsonProcessingException) { - message = String.format("Json parsing error : %s ", ex.getMessage()); + message = String.format("malformed json; json processing error"); } if(ex instanceof org.glassfish.jersey.server.ParamException) { message = String.format("Bad request parameter : %s ", ((org.glassfish.jersey.server.ParamException) ex).getParameterName()); } if(ex instanceof com.yuktix.exception.ServiceIOException) { message = ex.getMessage(); status = Status.SERVICE_UNAVAILABLE ; } return Response.status(status) .entity(new ErrorBean(status.getStatusCode(),message)) .type(MediaType.APPLICATION_JSON) .build(); } }
true
true
public Response toResponse(Throwable ex) { Log.error(ex.getMessage(), ex); String message = "Internal service error" ; Status status = Status.INTERNAL_SERVER_ERROR ; // jackson json parsing exception // @todo - jersey exception contains stack trace if(ex instanceof org.codehaus.jackson.JsonProcessingException) { message = String.format("Json parsing error : %s ", ex.getMessage()); } if(ex instanceof org.glassfish.jersey.server.ParamException) { message = String.format("Bad request parameter : %s ", ((org.glassfish.jersey.server.ParamException) ex).getParameterName()); } if(ex instanceof com.yuktix.exception.ServiceIOException) { message = ex.getMessage(); status = Status.SERVICE_UNAVAILABLE ; } return Response.status(status) .entity(new ErrorBean(status.getStatusCode(),message)) .type(MediaType.APPLICATION_JSON) .build(); }
public Response toResponse(Throwable ex) { Log.error(ex.getMessage(), ex); String message = "Internal service error" ; Status status = Status.INTERNAL_SERVER_ERROR ; // jackson json parsing exception // @todo - jersey exception contains stack trace if(ex instanceof org.codehaus.jackson.JsonProcessingException) { message = String.format("malformed json; json processing error"); } if(ex instanceof org.glassfish.jersey.server.ParamException) { message = String.format("Bad request parameter : %s ", ((org.glassfish.jersey.server.ParamException) ex).getParameterName()); } if(ex instanceof com.yuktix.exception.ServiceIOException) { message = ex.getMessage(); status = Status.SERVICE_UNAVAILABLE ; } return Response.status(status) .entity(new ErrorBean(status.getStatusCode(),message)) .type(MediaType.APPLICATION_JSON) .build(); }
diff --git a/src/org/hive13/jircbot/commands/jIBCHelp.java b/src/org/hive13/jircbot/commands/jIBCHelp.java index e638578..3bd9816 100644 --- a/src/org/hive13/jircbot/commands/jIBCHelp.java +++ b/src/org/hive13/jircbot/commands/jIBCHelp.java @@ -1,24 +1,24 @@ package org.hive13.jircbot.commands; import org.hive13.jircbot.jIRCBot; public class jIBCHelp extends jIBCommand { @Override public String getCommandName() { return "help"; } @Override public String getHelp() { return "No."; } @Override protected void handleMessage(jIRCBot bot, String channel, String sender, String message) { bot.sendMessage(sender, "To get a list of available commands use '!plugins'. " + - "To learn more about a command type '!plugins help'."); + "To learn more about a command type '!<Command Name> help'."); } }
true
true
protected void handleMessage(jIRCBot bot, String channel, String sender, String message) { bot.sendMessage(sender, "To get a list of available commands use '!plugins'. " + "To learn more about a command type '!plugins help'."); }
protected void handleMessage(jIRCBot bot, String channel, String sender, String message) { bot.sendMessage(sender, "To get a list of available commands use '!plugins'. " + "To learn more about a command type '!<Command Name> help'."); }
diff --git a/KalenderProsjekt/src/data/CalendarModel.java b/KalenderProsjekt/src/data/CalendarModel.java index b9f2dd7..2a5e28a 100644 --- a/KalenderProsjekt/src/data/CalendarModel.java +++ b/KalenderProsjekt/src/data/CalendarModel.java @@ -1,381 +1,381 @@ package data; import java.awt.Color; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import client.Program; public class CalendarModel implements Serializable { private static final long serialVersionUID = -1762790448612918057L; private List<Person> persons; private ArrayList<Meeting> meetings; private ArrayList<Boolean> selected; private PropertyChangeSupport pcs; private ArrayList<Notification> notifications; private ArrayList<Alarm> alarms; private String username; private Person user; private ArrayList<MeetingRoom> meetingRooms; private GregorianCalendar calendar; private static final Color[] colors = { Color.red, Color.blue, Color.yellow, Color.orange, Color.magenta, Color.gray, Color.pink }; public static final String SELECTED_Property = "SELECTED", MEETINGS_CHANGED_Property = "MEETINGS", NOTIFICATIONS_CHANGED_Property = "NNOTI", CALENDAR_LOADED_Property = "LOADED", PERSONS_ADDED_Property = "PERSONS", ALARMS_CHANGED_Property = "ALARMA!", DATE_CHANGED_Property = "DATE", ROOMS_CHANGED_Property = "ROOMS"; /** * Constructs the calendar model. */ public CalendarModel() { pcs = new PropertyChangeSupport(this); calendar = new GregorianCalendar(); } /** * Initiate CalendarModel * @param username */ public void init(String username) { this.username = username; persons = new ArrayList<Person>(); meetings = new ArrayList<Meeting>(); selected = new ArrayList<Boolean>(); notifications = new ArrayList<Notification>(); alarms = new ArrayList<Alarm>(); meetingRooms = new ArrayList<MeetingRoom>(); requestAllPersons(); } /** * Returns all meetings of the person. * @param person * @param attending * @return allMeetings */ public ArrayList<Meeting> getAllMeetingsOfPerson(Person person, boolean attending) { ArrayList<Meeting> allMeetings = new ArrayList<Meeting>(); allMeetings.addAll(getAppointments(false)); allMeetings.addAll(getMeetings(person, attending)); return allMeetings; } /** * Returns something... DAVID!?? * @param person * @param attending * @return */ public ArrayList<Meeting> getMeetings(Person person, boolean attending) { ArrayList<Meeting> allMeetings = new ArrayList<Meeting>(); for (Notification n : notifications) { if (n.getPerson().getUsername().equals(person.getUsername()) && (n.getApproved() == 'y' || !attending)) { allMeetings.add(n.getMeeting()); } } return allMeetings; } /** * Returns a list of meetings. * @return appointments */ public ArrayList<Meeting> getAppointments(boolean allCreated) { ArrayList<Meeting> appointments = new ArrayList<Meeting>(); for (Meeting meeting : meetings) { if ((meeting.getTeam() == null || allCreated) && meeting.getCreator().getUsername() .equals(user.getUsername())) { appointments.add(meeting); } } return appointments; } /** * Returns all notifications of a person. * @param person * @return notifications */ public ArrayList<Notification> getAllNotificationsOfPerson(Person person) { ArrayList<Notification> notis = new ArrayList<Notification>(); for (Notification n : notifications) { if (n.getPerson().getUsername().equals(person.getUsername())) { notis.add(n); } } return notis; } /** * Returns unanswered notifications of user. * @return unanswered */ public ArrayList<Notification> getUnansweredNotificationsOfUser() { ArrayList<Notification> unanswered = new ArrayList<Notification>(); ArrayList<Notification> notis = getAllNotificationsOfPerson(user); for (Notification n : notis) { if (n.getApproved() == 'w') { unanswered.add(n); } } return unanswered; } /** * Returns all notifications of a meeting * @param meeting * @return notifications */ public ArrayList<Notification> getAllNotificationsOfMeeting(Meeting meeting) { ArrayList<Notification> notis = new ArrayList<Notification>(); for (Notification n : notifications) { if (n.getMeeting().getMeetingID() == meeting.getMeetingID()) { notis.add(n); } } return notis; } /** * Returns alarma by a meeting. * @param meeting * @return alarm */ public Alarm getAlarmByMeeting(Meeting meeting) { for (Alarm alarm : alarms) { if (alarm.getMeeting().getMeetingID() == meeting.getMeetingID()) { return alarm; } } return null; } /** * Gets ALL of the meetings of a person in the given time interval * * @param person * the person whose meetings to get * @param start * the minimum start time of the meeting * @param end * the maximum end time of the meeting * @return all the meetings of the given person within the given time * interval. */ // TODO // public ArrayList<Meeting> getMeetings(Person person, long start, long // end) { // ArrayList<Meeting> meetings = meetings.get(person); // ArrayList<Meeting> newMeetings = new ArrayList<Meeting>(); // for (Meeting meeting : meetings) { // if (meeting.getStartTime() >= start && meeting.getEndTime() < end) { // newMeetings.add(meeting); // } // } // return newMeetings; // } public List<Person> getPersons() { return persons; } // TODO // public HashMap<Person, ArrayList<Meeting>> getHasjmap() { // return meetings; // } public ArrayList<Boolean> getSelected() { return selected; } public void setAllSelected(ArrayList<Boolean> selected) { this.selected = selected; } public void setSelected(Person person, boolean sel) { selected.set(persons.indexOf(person), sel); pcs.firePropertyChange(SELECTED_Property, null, null); } private void requestEverything() { try { requestAllMeetings(); requestAllNotifications(); requestAlarmsOfUser(); requestAllRooms(); } catch (IOException e) { System.out.println("Requests failed"); e.printStackTrace(); } } private void requestAllMeetings() throws IOException { Program.reqHandler.sendGetEvryMeetingRequest(); } private void requestAllNotifications() throws IOException { Program.reqHandler.sendGetAllNotificationsRequest(); } private void requestAlarmsOfUser() throws IOException { Program.reqHandler.sendGetAlarmsByPersonRequest(user); } private void requestAllRooms() throws IOException { Program.reqHandler.sendGetAllMeetingroomsRequest(); } private void requestAllPersons() { try { if (Program.reqHandler != null) { Program.reqHandler.sendGetAllPersonsRequest(); } } catch (IOException e) { e.printStackTrace(); } } /** * Sets all the persons of the model. This method will only be called once * by the server at startup * * @param persons */ public void setAllPersons(List<Person> persons) { this.persons = persons; for (Person person : persons) { if (person.getUsername().equals(username)) { user = person; - selected.add(false); } + selected.add(false); } persons.remove(user); persons.add(user); selected.set(selected.size()-1, true); pcs.firePropertyChange(PERSONS_ADDED_Property, null, persons); requestEverything(); } public void setAllMeetings(List<Meeting> meetings) { this.meetings = (ArrayList<Meeting>) meetings; pcs.firePropertyChange(CALENDAR_LOADED_Property, null, meetings); } public void setAllRooms(List<MeetingRoom> rooms) { meetingRooms = (ArrayList<MeetingRoom>) rooms; pcs.firePropertyChange(ROOMS_CHANGED_Property, null, null); } public void setAlarmsOfUser(List<Alarm> alarms) { this.alarms = (ArrayList<Alarm>) alarms; pcs.firePropertyChange(ALARMS_CHANGED_Property, null, null); } public void setAllNotifications(List<Notification> notifications) { this.notifications = (ArrayList<Notification>) notifications; pcs.firePropertyChange(NOTIFICATIONS_CHANGED_Property, null, null); } public List<Person> getSelectedPersons() { List<Person> selectedPersons = new ArrayList<Person>(); for (int i = 0; i < selected.size(); i++) { if (selected.get(i)) { selectedPersons.add(persons.get(i)); } } return selectedPersons; } public Color getColorOfPerson(Person person) { int index = -2; for (int i = 0; i < persons.size(); i++) { if (person.getUsername().equals(persons.get(i).getUsername())) { index = i; } } return colors[index]; } public void setStatus(char c, Notification notification) { try { Program.reqHandler.sendUpdateNotificationRequest( new Notification(Calendar.getInstance().getTimeInMillis(), c, notification .getKind(), notification.getMeeting(), notification.getPerson())); } catch (IOException e) { e.printStackTrace(); } } public void pushMeeting(Meeting meeting) { try { Program.reqHandler.sendCreateMeetingRequest(meeting); } catch (IOException e) { e.printStackTrace(); } } public void changeMeeting(Meeting meeting) { try { Program.reqHandler.sendUpdateMeetingRequest(meeting); } catch (IOException e) { e.printStackTrace(); } } public void removeMeeting(Meeting meeting) { try { Program.reqHandler.sendDeleteMeetingRequest(meeting); } catch (IOException e) { e.printStackTrace(); } } public ArrayList<MeetingRoom> getRooms() { return meetingRooms; } public ArrayList<MeetingRoom> getAvailableRooms(long startTime, long endTime) { ArrayList<MeetingRoom> rooms = new ArrayList<MeetingRoom>(); rooms.addAll(meetingRooms); for (Meeting meeting : meetings) { long meetStart = meeting.getStartTime(); long meetEnd = meeting.getEndTime(); if (meeting.getRoom() != null && (meetStart >= startTime && meetStart < endTime) || (meetEnd > startTime && meetEnd < endTime)) { rooms.remove(meeting.getRoom()); } } return rooms; } public Person getUser() { return user; } public GregorianCalendar getCalendar() { return calendar; } public void changeDate() { pcs.firePropertyChange(DATE_CHANGED_Property, null, null); } public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } }
false
true
public void setAllPersons(List<Person> persons) { this.persons = persons; for (Person person : persons) { if (person.getUsername().equals(username)) { user = person; selected.add(false); } } persons.remove(user); persons.add(user); selected.set(selected.size()-1, true); pcs.firePropertyChange(PERSONS_ADDED_Property, null, persons); requestEverything(); }
public void setAllPersons(List<Person> persons) { this.persons = persons; for (Person person : persons) { if (person.getUsername().equals(username)) { user = person; } selected.add(false); } persons.remove(user); persons.add(user); selected.set(selected.size()-1, true); pcs.firePropertyChange(PERSONS_ADDED_Property, null, persons); requestEverything(); }
diff --git a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddPersonToRoleTwoStageGenerator.java b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddPersonToRoleTwoStageGenerator.java index ff7b631..2be020b 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddPersonToRoleTwoStageGenerator.java +++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddPersonToRoleTwoStageGenerator.java @@ -1,921 +1,921 @@ /* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.vivoweb.webapp.util.ModelUtils; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.XSD; import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.RoleToActivityPredicatePreprocessor; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation; import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode; import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils; /** * Generates the edit configuration for adding a Role to a Person. Stage one is selecting the type of the non-person thing associated with the Role with the intention of reducing the number of Individuals that the user has to select from. Stage two is selecting the non-person Individual to associate with the Role. This is intended to create a set of statements like: ?person core:hasResearchActivityRole ?newRole. ?newRole rdf:type core:ResearchActivityRole ; roleToActivityPredicate ?someActivity . ?someActivity rdf:type core:ResearchActivity . ?someActivity rdfs:label "activity title" . Important: This form cannot be directly used as a custom form. It has parameters that must be set. See addClinicalRoleToPerson.jsp for an example. roleToActivityPredicate and activityToRolePredicate are both dependent on the type of the activity itself. For a new statement, the predicate type is not known. For an existing statement, the predicate is known but may change based on the type of the activity newly selected. bdc34: TODO: figure out what needs to be customized per role form, document it here in comments TODO: rewrite class as an abstract class with simple, documented, required methods to override AddRoleToPersonTwoStageGenerator is abstract, each subclass will need to configure: From the old JSP version: showRoleLabelField boolean roleType URI roleToActivityPredicate URI activityToRolePredicate URI roleActivityType_optionsType roleActivityType_objectClassURI roleActivityType_literalOptions For the new generator version: template * */ public abstract class AddPersonToRoleTwoStageGenerator extends BaseEditConfigurationGenerator implements EditConfigurationGenerator { private Log log = LogFactory.getLog(AddPersonToRoleTwoStageGenerator.class); /* ***** Methods that are REQUIRED to be implemented in subclasses ***** */ /** Freemarker template to use */ abstract String getTemplate(); /** URI of type for the role context node */ abstract String getRoleType(); /** In the case of literal options, subclass generator will set the options to be returned */ abstract HashMap<String, String> getRoleActivityTypeLiteralOptions(); /** * Each subclass generator will return its own type of option here: * whether literal hardcoded, based on class group, or subclasses of a specific class * The latter two will apparently lend some kind of uri to objectClassUri ? */ abstract RoleActivityOptionTypes getRoleActivityTypeOptionsType(); /** The URI of a Class to use with options if required. An option type like * CHILD_VCLASSES would reqire a role activity object class URI. */ abstract String getRoleActivityTypeObjectClassUri(VitroRequest vreq); /** If true an input should be shown on the form for a * label for the role context node * TODO: move this to the FTL and have label optional. */ abstract boolean isShowRoleLabelField(); /** URI of predicate between role context node and activity */ //Bdc34: not used anywhere? that's odd // abstract String getActivityToRolePredicate(); @Override public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) { EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo(); initProcessParameters(vreq, session, editConfiguration); - editConfiguration.setVarNameForSubject("role"); + editConfiguration.setVarNameForSubject("grant"); editConfiguration.setVarNameForPredicate("rolePredicate"); - editConfiguration.setVarNameForObject("person"); + editConfiguration.setVarNameForObject("role"); // Required N3 editConfiguration.setN3Required(list( N3_PREFIX + "\n" + - "?role ?rolePredicate ?person .\n" + + "?grant ?rolePredicate ?role .\n" + "?role a ?roleType .\n" )); // Optional N3 //Note here we are placing the role to activity relationships as optional, since //it's possible to delete this relationship from the activity //On submission, if we kept these statements in n3required, the retractions would //not have all variables substituted, leading to an error //Note also we are including the relationship as a separate string in the array, to allow it to be //independently evaluated and passed back with substitutions even if the other strings are not //substituted correctly. editConfiguration.setN3Optional( list( "?role " + getRoleToActivityPlaceholder() + " ?roleActivity .\n"+ "?roleActivity " + getActivityToRolePlaceholder() + " ?role .", "?person ?inverseRolePredicate ?role .", getN3ForActivityLabel(), getN3ForActivityType(), getN3RoleLabelAssertion(), getN3ForStart(), getN3ForEnd() )); editConfiguration.setNewResources( newResources(vreq) ); //In scope setUrisAndLiteralsInScope(editConfiguration, vreq); //on Form setUrisAndLiteralsOnForm(editConfiguration, vreq); //Sparql queries setSparqlQueries(editConfiguration, vreq); //set fields setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq)); //Form title and submit label now moved to edit configuration template //TODO: check if edit configuration template correct place to set those or whether //additional methods here should be used and reference instead, e.g. edit configuration template could call //default obj property form.populateTemplate or some such method //Select from existing also set within template itself editConfiguration.setTemplate(getTemplate()); //Add validator //editConfiguration.addValidator(new DateTimeIntervalValidationVTwo("startField","endField") ); //editConfiguration.addValidator(new AntiXssValidation()); //Add preprocessors addPreprocessors(editConfiguration, vreq.getWebappDaoFactory()); //Adding additional data, specifically edit mode addFormSpecificData(editConfiguration, vreq); //prepare prepare(vreq, editConfiguration); return editConfiguration; } private void initProcessParameters(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) { editConfiguration.setFormUrl(EditConfigurationUtils.getFormUrlWithoutContext(vreq)); editConfiguration.setEntityToReturnTo(EditConfigurationUtils.getSubjectUri(vreq)); } /* N3 Required and Optional Generators as well as supporting methods */ private String getN3ForActivityLabel() { return "?roleActivity <" + RDFS.label.getURI() + "> ?activityLabel ."; } private String getN3ForActivityType() { return "?roleActivity a ?roleActivityType ."; } private String getN3RoleLabelAssertion() { return "?role <" + RDFS.label.getURI() + "> ?roleLabel ."; } //Method b/c used in two locations, n3 optional and n3 assertions private List<String> getN3ForStart() { List<String> n3ForStart = new ArrayList<String>(); n3ForStart.add("?role <" + RoleToIntervalURI + "> ?intervalNode ." + "?intervalNode <" + RDF.type.getURI() + "> <" + IntervalTypeURI + "> ." + "?intervalNode <" + IntervalToStartURI + "> ?startNode ." + "?startNode <" + RDF.type.getURI() + "> <" + DateTimeValueTypeURI + "> ." + "?startNode <" + DateTimeValueURI + "> ?startField-value ." + "?startNode <" + DateTimePrecisionURI + "> ?startField-precision ."); return n3ForStart; } private List<String> getN3ForEnd() { List<String> n3ForEnd = new ArrayList<String>(); n3ForEnd.add("?role <" + RoleToIntervalURI + "> ?intervalNode . " + "?intervalNode <" + RDF.type.getURI() + "> <" + IntervalTypeURI + "> ." + "?intervalNode <" + IntervalToEndURI + "> ?endNode ." + "?endNode <" + RDF.type.getURI() + "> <" + DateTimeValueTypeURI + "> ." + "?endNode <" + DateTimeValueURI + "> ?endField-value ." + "?endNode <" + DateTimePrecisionURI+ "> ?endField-precision ."); return n3ForEnd; } /** Get new resources */ private Map<String, String> newResources(VitroRequest vreq) { String DEFAULT_NS_TOKEN=null; //null forces the default NS HashMap<String, String> newResources = new HashMap<String, String>(); newResources.put("role", DEFAULT_NS_TOKEN); newResources.put("roleActivity", DEFAULT_NS_TOKEN); newResources.put("intervalNode", DEFAULT_NS_TOKEN); newResources.put("startNode", DEFAULT_NS_TOKEN); newResources.put("endNode", DEFAULT_NS_TOKEN); return newResources; } /** Set URIS and Literals In Scope and on form and supporting methods */ private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>(); //Setting inverse role predicate urisInScope.put("inverseRolePredicate", getInversePredicate(vreq)); urisInScope.put("roleType", list( getRoleType() ) ); //Uris in scope include subject, predicate, and object var editConfiguration.setUrisInScope(urisInScope); //literals in scope empty initially, usually populated by code in prepare for update //with existing values for variables } private List<String> getInversePredicate(VitroRequest vreq) { List<String> inversePredicateArray = new ArrayList<String>(); ObjectProperty op = EditConfigurationUtils.getObjectProperty(vreq); if(op != null && op.getURIInverse() != null) { inversePredicateArray.add(op.getURIInverse()); } return inversePredicateArray; } private void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { List<String> urisOnForm = new ArrayList<String>(); //add role activity and roleActivityType to uris on form urisOnForm.add("roleActivity"); urisOnForm.add("roleActivityType"); //Also adding the predicates //TODO: Check how to override this in case of default parameter? Just write hidden input to form? urisOnForm.add("roleToActivityPredicate"); urisOnForm.add("activityToRolePredicate"); editConfiguration.setUrisOnform(urisOnForm); //activity label and role label are literals on form List<String> literalsOnForm = new ArrayList<String>(); literalsOnForm.add("activityLabel"); literalsOnForm.add("roleLabel"); editConfiguration.setLiteralsOnForm(literalsOnForm); } /** Set SPARQL Queries and supporting methods. */ private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { //Queries for activity label, role label, start Field value, end Field value HashMap<String, String> map = new HashMap<String, String>(); map.put("activityLabel", getActivityLabelQuery(vreq)); map.put("roleLabel", getRoleLabelQuery(vreq)); map.put("startField-value", getExistingStartDateQuery(vreq)); map.put("endField-value", getExistingEndDateQuery(vreq)); editConfiguration.setSparqlForExistingLiterals(map); //Queries for role activity, activity type query, interval node, // start node, end node, start field precision, endfield precision map = new HashMap<String, String>(); map.put("roleActivity", getRoleActivityQuery(vreq)); map.put("roleActivityType", getActivityTypeQuery(vreq)); map.put("intervalNode", getIntervalNodeQuery(vreq)); map.put("startNode", getStartNodeQuery(vreq)); map.put("endNode", getEndNodeQuery(vreq)); map.put("startField-precision", getStartPrecisionQuery(vreq)); map.put("endField-precision", getEndPrecisionQuery(vreq)); //Also need sparql queries for roleToActivityPredicate and activityToRolePredicate map.put("roleToActivityPredicate", getRoleToActivityPredicateQuery(vreq)); map.put("activityToRolePredicate", getActivityToRolePredicateQuery(vreq)); editConfiguration.setSparqlForExistingUris(map); } private String getActivityToRolePredicateQuery(VitroRequest vreq) { String query = "SELECT ?existingActivityToRolePredicate \n " + "WHERE { \n" + "?roleActivity ?existingActivityToRolePredicate ?role .\n"; //Get possible predicates List<String> addToQuery = new ArrayList<String>(); List<String> predicates = getPossibleActivityToRolePredicates(); for(String p:predicates) { addToQuery.add("(?existingActivityToRolePredicate=<" + p + ">)"); } query += "FILTER (" + StringUtils.join(addToQuery, " || ") + ")\n"; query += "}"; return query; } private String getRoleToActivityPredicateQuery(VitroRequest vreq) { String query = "SELECT ?existingRoleToActivityPredicate \n " + "WHERE { \n" + "?role ?existingRoleToActivityPredicate ?roleActivity .\n"; //Get possible predicates query += getFilterRoleToActivityPredicate("existingRoleToActivityPredicate"); query += "\n}"; return query; } private String getEndPrecisionQuery(VitroRequest vreq) { String query = "SELECT ?existingEndPrecision WHERE {\n" + "?role <" + RoleToIntervalURI + "> ?intervalNode .\n" + "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" + "?intervalNode <" + IntervalToEndURI + "> ?endNode .\n" + "?endNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> . \n" + "?endNode <" + DateTimePrecisionURI + "> ?existingEndPrecision . }"; return query; } private String getStartPrecisionQuery(VitroRequest vreq) { String query = "SELECT ?existingStartPrecision WHERE {\n" + "?role <" + RoleToIntervalURI + "> ?intervalNode .\n" + "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" + "?intervalNode <" + IntervalToStartURI + "> ?startNode .\n" + "?startNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> . \n" + "?startNode <" + DateTimePrecisionURI + "> ?existingStartPrecision . }"; return query; } private String getEndNodeQuery(VitroRequest vreq) { String query = "SELECT ?existingEndNode WHERE {\n"+ "?role <" + RoleToIntervalURI + "> ?intervalNode .\n"+ "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n"+ "?intervalNode <" + IntervalToEndURI + "> ?existingEndNode . \n"+ "?existingEndNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .}\n"; return query; } private String getStartNodeQuery(VitroRequest vreq) { String query = "SELECT ?existingStartNode WHERE {\n"+ "?role <" + RoleToIntervalURI + "> ?intervalNode .\n"+ "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n"+ "?intervalNode <" + IntervalToStartURI + "> ?existingStartNode . \n"+ "?existingStartNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .}"; return query; } private String getIntervalNodeQuery(VitroRequest vreq) { String query = "SELECT ?existingIntervalNode WHERE { \n" + "?role <" + RoleToIntervalURI + "> ?existingIntervalNode . \n" + " ?existingIntervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> . }\n"; return query; } /* * The activity type query results must be limited to the values in the activity type select element. * Sometimes the query returns a superclass such as owl:Thing instead. * Make use of vitro:mostSpecificType so that, for example, an individual is both a * core:InvitedTalk and a core:Presentation, core:InvitedTalk is selected. * vitro:mostSpecificType alone may not suffice, since it does not guarantee that the value returned * is in the select list. * We could still have problems if the value from the select list is not a vitro:mostSpecificType, * but that is unlikely. */ //This method had some code already setup in the jsp file private String getActivityTypeQuery(VitroRequest vreq) { String activityTypeQuery = null; //roleActivityType_optionsType: This gets you whether this is a literal // RoleActivityOptionTypes optionsType = getRoleActivityTypeOptionsType(); // Note that this value is overloaded to specify either object class uri or classgroup uri String objectClassUri = getRoleActivityTypeObjectClassUri(vreq); if (StringUtils.isNotBlank(objectClassUri)) { log.debug("objectClassUri = " + objectClassUri); if (RoleActivityOptionTypes.VCLASSGROUP.equals(optionsType)) { activityTypeQuery = getClassgroupActivityTypeQuery(vreq); activityTypeQuery = QueryUtils.subUriForQueryVar(activityTypeQuery, "classgroup", objectClassUri); } else if (RoleActivityOptionTypes.CHILD_VCLASSES.equals(optionsType)) { activityTypeQuery = getSubclassActivityTypeQuery(vreq); activityTypeQuery = QueryUtils.subUriForQueryVar(activityTypeQuery, "objectClassUri", objectClassUri); } else { activityTypeQuery = getDefaultActivityTypeQuery(vreq); } // Select options are hardcoded } else if (RoleActivityOptionTypes.HARDCODED_LITERALS.equals(optionsType)) { //literal options HashMap<String, String> typeLiteralOptions = getRoleActivityTypeLiteralOptions(); if (typeLiteralOptions.size() > 0) { try { List<String> typeUris = new ArrayList<String>(); Set<String> optionUris = typeLiteralOptions.keySet(); for(String uri: optionUris) { if(!uri.isEmpty()) { typeUris.add("(?existingActivityType = <" + uri + ">)"); } } String typeFilters = "FILTER (" + StringUtils.join(typeUris, "||") + ")"; String defaultActivityTypeQuery = getDefaultActivityTypeQuery(vreq); activityTypeQuery = defaultActivityTypeQuery.replaceAll("}$", "") + typeFilters + "}"; } catch (Exception e) { activityTypeQuery = getDefaultActivityTypeQuery(vreq); } } else { activityTypeQuery = getDefaultActivityTypeQuery(vreq); } } else { activityTypeQuery = getDefaultActivityTypeQuery(vreq); } //The replacement of activity type query's predicate was only relevant when we actually //know which predicate is definitely being used here //Here we have multiple values possible for predicate so the original //Replacement should only happen when we have an actual predicate String replaceRoleToActivityPredicate = getRoleToActivityPredicate(vreq); activityTypeQuery = QueryUtils.replaceQueryVar(activityTypeQuery, "predicate", getRoleToActivityPlaceholderName()); log.debug("Activity type query: " + activityTypeQuery); return activityTypeQuery; } private String getDefaultActivityTypeQuery(VitroRequest vreq) { String query = "PREFIX core: <" + VIVO_NS + ">\n" + "PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" + "SELECT ?existingActivityType WHERE { \n" + " ?role ?predicate ?existingActivity . \n" + " ?existingActivity vitro:mostSpecificType ?existingActivityType . \n"; query += getFilterRoleToActivityPredicate("predicate"); query+= "}"; return query; } private String getSubclassActivityTypeQuery(VitroRequest vreq) { String query = "PREFIX core: <" + VIVO_NS + ">\n" + "PREFIX rdfs: <" + VitroVocabulary.RDFS + ">\n" + "PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" + "SELECT ?existingActivityType WHERE {\n" + " ?role ?predicate ?existingActivity . \n" + " ?existingActivity vitro:mostSpecificType ?existingActivityType . \n" + " ?existingActivityType rdfs:subClassOf ?objectClassUri . \n"; query += getFilterRoleToActivityPredicate("predicate"); query+= "}"; return query; } private String getClassgroupActivityTypeQuery(VitroRequest vreq) { String query = "PREFIX core: <" + VIVO_NS + ">\n" + "PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" + "SELECT ?existingActivityType WHERE { \n" + " ?role ?predicate ?existingActivity . \n" + " ?existingActivity vitro:mostSpecificType ?existingActivityType . \n" + " ?existingActivityType vitro:inClassGroup ?classgroup . \n"; query += getFilterRoleToActivityPredicate("predicate"); query+= "}"; return query; } private String getRoleActivityQuery(VitroRequest vreq) { //If role to activity predicate is the default query, then we need to replace with a union //of both realizedIn and the other String query = "PREFIX core: <" + VIVO_NS + ">"; //Portion below for multiple possible predicates List<String> predicates = getPossibleRoleToActivityPredicates(); List<String> addToQuery = new ArrayList<String>(); query += "SELECT ?existingActivity WHERE { \n" + " ?role ?predicate ?existingActivity . \n "; query += getFilterRoleToActivityPredicate("predicate"); query += "}"; return query; } private String getExistingEndDateQuery(VitroRequest vreq) { String query = " SELECT ?existingEndDate WHERE {\n" + "?role <" + RoleToIntervalURI + "> ?intervalNode .\n" + "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" + "?intervalNode <" + IntervalToEndURI + "> ?endNode .\n" + "?endNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .\n" + "?endNode <" + DateTimeValueURI + "> ?existingEndDate . }"; return query; } private String getExistingStartDateQuery(VitroRequest vreq) { String query = "SELECT ?existingDateStart WHERE {\n" + "?role <" + RoleToIntervalURI + "> ?intervalNode .\n" + "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" + "?intervalNode <" + IntervalToStartURI+ "> ?startNode .\n" + "?startNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .\n" + "?startNode <" + DateTimeValueURI + "> ?existingDateStart . }"; return query; } private String getRoleLabelQuery(VitroRequest vreq) { String query = "SELECT ?existingRoleLabel WHERE { \n" + "?role <" + VitroVocabulary.LABEL + "> ?existingRoleLabel . }"; return query; } private String getActivityLabelQuery(VitroRequest vreq) { String query = "PREFIX core: <" + VIVO_NS + ">" + "PREFIX rdfs: <" + RDFS.getURI() + "> \n"; query += "SELECT ?existingTitle WHERE { \n" + "?role ?predicate ?existingActivity . \n" + "?existingActivity rdfs:label ?existingTitle . \n"; query += getFilterRoleToActivityPredicate("predicate"); query += "}"; return query; } /** * * Set Fields and supporting methods */ private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) { Map<String, FieldVTwo> fields = new HashMap<String, FieldVTwo>(); //Multiple fields getActivityLabelField(editConfiguration, vreq, fields); getRoleActivityTypeField(editConfiguration, vreq, fields); getRoleActivityField(editConfiguration, vreq, fields); getRoleLabelField(editConfiguration, vreq, fields); getStartField(editConfiguration, vreq, fields); getEndField(editConfiguration, vreq, fields); //These fields are for the predicates that will be set later //TODO: Do these only if not using a parameter for the predicate? getRoleToActivityPredicateField(editConfiguration, vreq, fields); getActivityToRolePredicateField(editConfiguration, vreq, fields); editConfiguration.setFields(fields); } //This is a literal technically? private void getActivityToRolePredicateField( EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "activityToRolePredicate"; //get range data type uri and range language String stringDatatypeUri = XSD.xstring.toString(); FieldVTwo field = new FieldVTwo(); field.setName(fieldName); //queryForExisting is not being used anywhere in Field //Not really interested in validators here List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } private void getRoleToActivityPredicateField( EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "roleToActivityPredicate"; //get range data type uri and range language String stringDatatypeUri = XSD.xstring.toString(); FieldVTwo field = new FieldVTwo(); field.setName(fieldName); //queryForExisting is not being used anywhere in Field //Not really interested in validators here List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } //Label of "right side" of role, i.e. label for role roleIn Activity private void getActivityLabelField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "activityLabel"; //get range data type uri and range language String stringDatatypeUri = XSD.xstring.toString(); FieldVTwo field = new FieldVTwo(); field.setName(fieldName); //queryForExisting is not being used anywhere in Field List<String> validators = new ArrayList<String>(); //If add mode or repair, etc. need to add label required validator if(isAddMode(vreq) || isRepairMode(vreq)) { validators.add("nonempty"); } validators.add("datatype:" + stringDatatypeUri); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(stringDatatypeUri); field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } //type of "right side" of role, i.e. type of activity from role roleIn activity private void getRoleActivityTypeField( EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "roleActivityType"; //get range data type uri and range language FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); if(isAddMode(vreq) || isRepairMode(vreq)) { validators.add("nonempty"); } field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field //TODO: Check if this is correct field.setOptionsType(getRoleActivityTypeOptionsType().toString()); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(getRoleActivityTypeObjectClassUri(vreq)); field.setRangeDatatypeUri(null); HashMap<String, String> literalOptionsMap = getRoleActivityTypeLiteralOptions(); List<List<String>> fieldLiteralOptions = new ArrayList<List<String>>(); Set<String> optionUris = literalOptionsMap.keySet(); for(String optionUri: optionUris) { List<String> uriLabelArray = new ArrayList<String>(); uriLabelArray.add(optionUri); uriLabelArray.add(literalOptionsMap.get(optionUri)); fieldLiteralOptions.add(uriLabelArray); } field.setLiteralOptions(fieldLiteralOptions); fields.put(field.getName(), field); } //Assuming URI for activity for role? private void getRoleActivityField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "roleActivity"; //get range data type uri and range language FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); //empty field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } private void getRoleLabelField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "roleLabel"; String stringDatatypeUri = XSD.xstring.toString(); FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); validators.add("datatype:" + stringDatatypeUri); if(isShowRoleLabelField()) { validators.add("nonempty"); } field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(stringDatatypeUri); //empty field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } private void getStartField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "startField"; FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); //empty field.setLiteralOptions(new ArrayList<List<String>>()); //This logic was originally after edit configuration object created from json in original jsp field.setEditElement( new DateTimeWithPrecisionVTwo(field, VitroVocabulary.Precision.YEAR.uri(), VitroVocabulary.Precision.NONE.uri())); fields.put(field.getName(), field); } private void getEndField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "endField"; FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); //empty field.setLiteralOptions(new ArrayList<List<String>>()); //Set edit element field.setEditElement( new DateTimeWithPrecisionVTwo(field, VitroVocabulary.Precision.YEAR.uri(), VitroVocabulary.Precision.NONE.uri())); fields.put(field.getName(), field); } private void addPreprocessors(EditConfigurationVTwo editConfiguration, WebappDaoFactory wadf) { //Add preprocessor that will replace the role to activity predicate and inverse //with correct properties based on the activity type editConfiguration.addEditSubmissionPreprocessor( new RoleToActivityPredicatePreprocessor(editConfiguration, wadf)); } //This has a default value, but note that even that will not be used //in the update with realized in or contributes to //Overridden when need be in subclassed generator //Also note that for now we're going to actually going to return a //placeholder value by default public String getRoleToActivityPredicate(VitroRequest vreq) { //TODO: <uri> and ?placeholder are incompatible return getRoleToActivityPlaceholder(); } //Ensure when overwritten that this includes the <> b/c otherwise the query won't work //Some values will have a default value public List<String> getPossibleRoleToActivityPredicates() { return ModelUtils.getPossiblePropertiesForRole(); } public List<String> getPossibleActivityToRolePredicates() { return ModelUtils.getPossibleInversePropertiesForRole(); } /* Methods that check edit mode */ public EditMode getEditMode(VitroRequest vreq) { List<String> roleToGrantPredicates = getPossibleRoleToActivityPredicates(); return EditModeUtils.getEditMode(vreq, roleToGrantPredicates); } private boolean isAddMode(VitroRequest vreq) { return EditModeUtils.isAddMode(getEditMode(vreq)); } private boolean isEditMode(VitroRequest vreq) { return EditModeUtils.isEditMode(getEditMode(vreq)); } private boolean isRepairMode(VitroRequest vreq) { return EditModeUtils.isRepairMode(getEditMode(vreq)); } /* URIS for various predicates */ private final String VIVO_NS="http://vivoweb.org/ontology/core#"; private final String RoleToIntervalURI = VIVO_NS + "dateTimeInterval"; private final String IntervalTypeURI = VIVO_NS + "DateTimeInterval"; private final String IntervalToStartURI = VIVO_NS + "start"; private final String IntervalToEndURI = VIVO_NS + "end"; private final String StartYearPredURI = VIVO_NS + "startYear"; private final String EndYearPredURI = VIVO_NS + "endYear"; private final String DateTimeValueTypeURI=VIVO_NS + "DateTimeValue"; private final String DateTimePrecisionURI=VIVO_NS + "dateTimePrecision"; private final String DateTimeValueURI = VIVO_NS + "dateTime"; //Form specific data public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { HashMap<String, Object> formSpecificData = new HashMap<String, Object>(); formSpecificData.put("editMode", getEditMode(vreq).name().toLowerCase()); //Fields that will need select lists generated //Store field names List<String> objectSelect = new ArrayList<String>(); objectSelect.add("roleActivityType"); //TODO: Check if this is the proper way to do this? formSpecificData.put("objectSelect", objectSelect); //Also put in show role label field formSpecificData.put("showRoleLabelField", isShowRoleLabelField()); //Put in the fact that we require field editConfiguration.setFormSpecificData(formSpecificData); } public String getFilterRoleToActivityPredicate(String predicateVar) { String addFilter = "FILTER ("; List<String> predicates = getPossibleRoleToActivityPredicates(); List<String> filterPortions = new ArrayList<String>(); for(String p: predicates) { filterPortions.add("(?" + predicateVar + "=<" + p + ">)"); } addFilter += StringUtils.join(filterPortions, " || "); addFilter += ")"; return addFilter; } private String getRoleToActivityPlaceholder() { return "?" + getRoleToActivityPlaceholderName(); } private String getRoleToActivityPlaceholderName() { return "roleToActivityPredicate"; } private String getActivityToRolePlaceholder() { return "?activityToRolePredicate"; } //Types of options to populate drop-down for types for the "right side" of the role public static enum RoleActivityOptionTypes { VCLASSGROUP, CHILD_VCLASSES, HARDCODED_LITERALS }; private final String N3_PREFIX = "@prefix core: <http://vivoweb.org/ontology/core#> ."; }
false
true
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) { EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo(); initProcessParameters(vreq, session, editConfiguration); editConfiguration.setVarNameForSubject("role"); editConfiguration.setVarNameForPredicate("rolePredicate"); editConfiguration.setVarNameForObject("person"); // Required N3 editConfiguration.setN3Required(list( N3_PREFIX + "\n" + "?role ?rolePredicate ?person .\n" + "?role a ?roleType .\n" )); // Optional N3 //Note here we are placing the role to activity relationships as optional, since //it's possible to delete this relationship from the activity //On submission, if we kept these statements in n3required, the retractions would //not have all variables substituted, leading to an error //Note also we are including the relationship as a separate string in the array, to allow it to be //independently evaluated and passed back with substitutions even if the other strings are not //substituted correctly. editConfiguration.setN3Optional( list( "?role " + getRoleToActivityPlaceholder() + " ?roleActivity .\n"+ "?roleActivity " + getActivityToRolePlaceholder() + " ?role .", "?person ?inverseRolePredicate ?role .", getN3ForActivityLabel(), getN3ForActivityType(), getN3RoleLabelAssertion(), getN3ForStart(), getN3ForEnd() )); editConfiguration.setNewResources( newResources(vreq) ); //In scope setUrisAndLiteralsInScope(editConfiguration, vreq); //on Form setUrisAndLiteralsOnForm(editConfiguration, vreq); //Sparql queries setSparqlQueries(editConfiguration, vreq); //set fields setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq)); //Form title and submit label now moved to edit configuration template //TODO: check if edit configuration template correct place to set those or whether //additional methods here should be used and reference instead, e.g. edit configuration template could call //default obj property form.populateTemplate or some such method //Select from existing also set within template itself editConfiguration.setTemplate(getTemplate()); //Add validator //editConfiguration.addValidator(new DateTimeIntervalValidationVTwo("startField","endField") ); //editConfiguration.addValidator(new AntiXssValidation()); //Add preprocessors addPreprocessors(editConfiguration, vreq.getWebappDaoFactory()); //Adding additional data, specifically edit mode addFormSpecificData(editConfiguration, vreq); //prepare prepare(vreq, editConfiguration); return editConfiguration; }
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) { EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo(); initProcessParameters(vreq, session, editConfiguration); editConfiguration.setVarNameForSubject("grant"); editConfiguration.setVarNameForPredicate("rolePredicate"); editConfiguration.setVarNameForObject("role"); // Required N3 editConfiguration.setN3Required(list( N3_PREFIX + "\n" + "?grant ?rolePredicate ?role .\n" + "?role a ?roleType .\n" )); // Optional N3 //Note here we are placing the role to activity relationships as optional, since //it's possible to delete this relationship from the activity //On submission, if we kept these statements in n3required, the retractions would //not have all variables substituted, leading to an error //Note also we are including the relationship as a separate string in the array, to allow it to be //independently evaluated and passed back with substitutions even if the other strings are not //substituted correctly. editConfiguration.setN3Optional( list( "?role " + getRoleToActivityPlaceholder() + " ?roleActivity .\n"+ "?roleActivity " + getActivityToRolePlaceholder() + " ?role .", "?person ?inverseRolePredicate ?role .", getN3ForActivityLabel(), getN3ForActivityType(), getN3RoleLabelAssertion(), getN3ForStart(), getN3ForEnd() )); editConfiguration.setNewResources( newResources(vreq) ); //In scope setUrisAndLiteralsInScope(editConfiguration, vreq); //on Form setUrisAndLiteralsOnForm(editConfiguration, vreq); //Sparql queries setSparqlQueries(editConfiguration, vreq); //set fields setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq)); //Form title and submit label now moved to edit configuration template //TODO: check if edit configuration template correct place to set those or whether //additional methods here should be used and reference instead, e.g. edit configuration template could call //default obj property form.populateTemplate or some such method //Select from existing also set within template itself editConfiguration.setTemplate(getTemplate()); //Add validator //editConfiguration.addValidator(new DateTimeIntervalValidationVTwo("startField","endField") ); //editConfiguration.addValidator(new AntiXssValidation()); //Add preprocessors addPreprocessors(editConfiguration, vreq.getWebappDaoFactory()); //Adding additional data, specifically edit mode addFormSpecificData(editConfiguration, vreq); //prepare prepare(vreq, editConfiguration); return editConfiguration; }
diff --git a/src/com/bretth/osmosis/core/report/v0_5/IntegrityReporterFactory.java b/src/com/bretth/osmosis/core/report/v0_5/IntegrityReporterFactory.java index 433d5655..52b8859a 100644 --- a/src/com/bretth/osmosis/core/report/v0_5/IntegrityReporterFactory.java +++ b/src/com/bretth/osmosis/core/report/v0_5/IntegrityReporterFactory.java @@ -1,41 +1,41 @@ package com.bretth.osmosis.core.report.v0_5; import java.io.File; import java.util.Map; import com.bretth.osmosis.core.pipeline.common.TaskManager; import com.bretth.osmosis.core.pipeline.common.TaskManagerFactory; import com.bretth.osmosis.core.pipeline.v0_5.SinkManager; /** * The task manager factory for an integrity reporter. * * @author Brett Henderson */ public class IntegrityReporterFactory extends TaskManagerFactory { private static final String ARG_FILE_NAME = "file"; private static final String DEFAULT_FILE_NAME = "integrity-report.txt"; /** * {@inheritDoc} */ @Override protected TaskManager createTaskManagerImpl(String taskId, Map<String, String> taskArgs, Map<String, String> pipeArgs) { String fileName; File file; - EntityReporter task; + IntegrityReporter task; // Get the task arguments. fileName = getStringArgument(taskId, taskArgs, ARG_FILE_NAME, DEFAULT_FILE_NAME); // Create a file object from the file name provided. file = new File(fileName); // Build the task object. - task = new EntityReporter(file); + task = new IntegrityReporter(file); return new SinkManager(taskId, task, pipeArgs); } }
false
true
protected TaskManager createTaskManagerImpl(String taskId, Map<String, String> taskArgs, Map<String, String> pipeArgs) { String fileName; File file; EntityReporter task; // Get the task arguments. fileName = getStringArgument(taskId, taskArgs, ARG_FILE_NAME, DEFAULT_FILE_NAME); // Create a file object from the file name provided. file = new File(fileName); // Build the task object. task = new EntityReporter(file); return new SinkManager(taskId, task, pipeArgs); }
protected TaskManager createTaskManagerImpl(String taskId, Map<String, String> taskArgs, Map<String, String> pipeArgs) { String fileName; File file; IntegrityReporter task; // Get the task arguments. fileName = getStringArgument(taskId, taskArgs, ARG_FILE_NAME, DEFAULT_FILE_NAME); // Create a file object from the file name provided. file = new File(fileName); // Build the task object. task = new IntegrityReporter(file); return new SinkManager(taskId, task, pipeArgs); }
diff --git a/src/org/gavrog/apps/_3dt/Document.java b/src/org/gavrog/apps/_3dt/Document.java index c5800c0..b37e8e8 100644 --- a/src/org/gavrog/apps/_3dt/Document.java +++ b/src/org/gavrog/apps/_3dt/Document.java @@ -1,1197 +1,1197 @@ /** Copyright 2013 Olaf Delgado-Friedrichs 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.gavrog.apps._3dt; import java.awt.Color; import java.io.BufferedReader; import java.io.EOFException; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Reader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.Set; import org.gavrog.box.collections.Cache; import org.gavrog.box.collections.CacheMissException; import org.gavrog.box.collections.Iterators; import org.gavrog.box.simple.NamedConstant; import org.gavrog.box.simple.Tag; import org.gavrog.jane.compounds.LinearAlgebra; import org.gavrog.jane.compounds.Matrix; import org.gavrog.jane.numbers.Real; import org.gavrog.jane.numbers.Whole; import org.gavrog.joss.dsyms.basic.DSPair; import org.gavrog.joss.dsyms.basic.DSymbol; import org.gavrog.joss.dsyms.basic.DelaneySymbol; import org.gavrog.joss.dsyms.basic.DynamicDSymbol; import org.gavrog.joss.dsyms.basic.IndexList; import org.gavrog.joss.dsyms.derived.Covers; import org.gavrog.joss.dsyms.derived.DSCover; import org.gavrog.joss.dsyms.derived.Signature; import org.gavrog.joss.geometry.CoordinateChange; import org.gavrog.joss.geometry.Operator; import org.gavrog.joss.geometry.Point; import org.gavrog.joss.geometry.SpaceGroupCatalogue; import org.gavrog.joss.geometry.SpaceGroupFinder; import org.gavrog.joss.geometry.Vector; import org.gavrog.joss.pgraphs.basic.IEdge; import org.gavrog.joss.pgraphs.basic.INode; import org.gavrog.joss.pgraphs.basic.Morphism; import org.gavrog.joss.pgraphs.embed.Embedder; import org.gavrog.joss.pgraphs.io.GenericParser; import org.gavrog.joss.pgraphs.io.GenericParser.Block; import org.gavrog.joss.pgraphs.io.Net; import org.gavrog.joss.pgraphs.io.NetParser; import org.gavrog.joss.tilings.FaceList; import org.gavrog.joss.tilings.Tiling; import de.jreality.scene.Transformation; /** */ public class Document extends DisplayList { // --- the cache keys final protected static Tag TILES = new Tag(); final protected static Tag EMBEDDER = new Tag(); final protected static Tag EMBEDDER_OUTPUT = new Tag(); final protected static Tag FINDER = new Tag(); final protected static Tag SIGNATURE = new Tag(); final protected static Tag SPACEGROUP = new Tag(); final protected static Tag TILING = new Tag(); final protected static Tag CENTERING_VECTORS = new Tag(); // --- cache for this instance final protected Cache<Tag, Object> cache = new Cache<Tag, Object>(); // --- possible document types final static public class Type extends NamedConstant { public Type(final String name) { super(name); } } final static public Object TILING_3D = new Type("3d Tiling"); final static public Object TILING_2D = new Type("2d Tiling"); final static public Object NET = new Type("Net"); // --- The type of this instance, its name and source data private Object type; final private String name; private GenericParser.Block data = null; private DSymbol given_symbol = null; // --- The symbol and other deduced data private DSymbol symbol = null; private DSymbol effective_symbol = null; private DSCover<Integer> given_cover = null; private Map<Integer, Point> given_positions = null; private Matrix given_gram_matrix = null; // --- The last remembered viewing transformation private Transformation transformation = null; // --- The tile and face colors set for this instance //TODO this should probably be moved to the DisplayList class. private Color[] tileClassColor = null; private Map<Tiling.Facet, Color> facetClassColor = new HashMap<Tiling.Facet, Color>(); private Set<Tiling.Facet> hiddenFacetClasses = new HashSet<Tiling.Facet>(); // --- embedding options private int equalEdgePriority = 3; private int embedderStepLimit = 10000; private boolean ignoreInputCell = false; private boolean ignoreInputCoordinates = false; private boolean relaxCoordinates = true; // --- tiling options private boolean useMaximalSymmetry = false; // --- cell choice options private boolean usePrimitiveCell = false; // --- saved user options private Properties properties = new Properties(); // --- default file name for saving the scene in private File saveSceneFile; // --- random number generator private final static Random random = new Random(); // --- convert a 2d symbol to 3d by extrusion private <T> DSymbol extrusion(final DelaneySymbol<T> ds) { if (ds.dim() != 2) { throw new UnsupportedOperationException("dimension must be 2"); } final int s = ds.size(); final DynamicDSymbol tmp = new DynamicDSymbol(3); final List<Integer> elms_new = tmp.grow(s * 3); final List<T> elms_old = Iterators.asList(ds.elements()); for (int i = 0; i < ds.size(); ++i) { final int Da = elms_new.get(i); final int Db = elms_new.get(i + s); final int Dc = elms_new.get(i + s + s); final T D = elms_old.get(i); final int i0 = elms_old.indexOf(ds.op(0, D)); final int i1 = elms_old.indexOf(ds.op(1, D)); final int i2 = elms_old.indexOf(ds.op(2, D)); tmp.redefineOp(0, Da, elms_new.get(i0)); tmp.redefineOp(1, Da, elms_new.get(i1)); tmp.redefineOp(2, Da, Db); tmp.redefineOp(3, Da, Da); tmp.redefineOp(0, Db, elms_new.get(i0 + s)); tmp.redefineOp(1, Db, Dc); tmp.redefineOp(2, Db, Da); tmp.redefineOp(3, Db, elms_new.get(i2 + s)); tmp.redefineOp(0, Dc, Dc); tmp.redefineOp(1, Dc, Db); tmp.redefineOp(2, Dc, elms_new.get(i1 + s + s)); tmp.redefineOp(3, Dc, elms_new.get(i2 + s + s)); } for (int i = 0; i < ds.size(); ++i) { final int Da = elms_new.get(i); final int Db = elms_new.get(i + s); final int Dc = elms_new.get(i + s + s); final T D = elms_old.get(i); tmp.redefineV(0, 1, Da, ds.v(0, 1, D)); if (D.equals(ds.op(0, D))) { tmp.redefineV(0, 1, Db, 2); } else { tmp.redefineV(0, 1, Db, 1); } tmp.redefineV(1, 2, Da, 1); if (D.equals(ds.op(2, D))) { tmp.redefineV(2, 3, Da, 2); } else { tmp.redefineV(2, 3, Da, 1); } tmp.redefineV(2, 3, Dc, ds.v(1, 2, D)); } return new DSymbol(tmp); } // --- construct the 2d Delaney symbol for a given periodic net - private DSymbol symbolForNet(final Net net) { + public static DSymbol symbolForNet(final Net net) { // -- check if the argument is supported if (net.getDimension() != 2) { throw new UnsupportedOperationException( "Only nets of dimension 2 are supported"); } // -- helper class for sorting neighbors by angle class Neighbor implements Comparable<Neighbor> { final private IEdge edge; final private double angle; public Neighbor(final IEdge e, final double a) { this.edge = e; this.angle = a; } public int compareTo(final Neighbor other) { if (this.angle < other.angle) { return -1; } else if (this.angle > other.angle) { return 1; } else { return 0; } } } // -- initialize the Delaney symbol; map oriented net edges to chambers final Map<IEdge, Integer> edge2chamber = new HashMap<IEdge, Integer>(); final DynamicDSymbol ds = new DynamicDSymbol(2); for (final IEdge e: net.edges()) { final List<Integer> elms = ds.grow(4); - edge2chamber.put(e, elms.get(0)); - edge2chamber.put(e.reverse(), elms.get(2)); + edge2chamber.put(e.oriented(), elms.get(0)); + edge2chamber.put(e.oriented().reverse(), elms.get(2)); ds.redefineOp(2, elms.get(0), elms.get(1)); ds.redefineOp(2, elms.get(2), elms.get(3)); ds.redefineOp(0, elms.get(0), elms.get(3)); ds.redefineOp(0, elms.get(1), elms.get(2)); } // -- connect the edge orbits of the Delaney symbol final Map<INode, Point> pos = net.barycentricPlacement(); for (final INode v: net.nodes()) { final List<IEdge> incidences = net.allIncidences(v); if (!net.goodCombinations(incidences, pos).hasNext()) { throw new UnsupportedOperationException( "Only convex tilings are currently supported"); } final Point p = (Point) pos.get(v); final List<Neighbor> neighbors = new ArrayList<Neighbor>(); for (final IEdge e: incidences) { final Vector d = (Vector) net.getShift(e).plus(pos.get(e.target())).minus(p); final double[] a = d.getCoordinates().asDoubleArray()[0]; neighbors.add(new Neighbor(e, Math.atan2(a[1], a[0]))); } Collections.sort(neighbors); neighbors.add(neighbors.get(0)); for (int i = 0; i < neighbors.size() - 1; ++i) { final IEdge e = neighbors.get(i).edge; final IEdge f = neighbors.get(i + 1).edge; ds.redefineOp(1, ds.op(2, edge2chamber.get(e)), edge2chamber.get(f)); } } // -- set branching to one everywhere for (final int D: ds.elements()) { ds.redefineV(0, 1, D, 1); ds.redefineV(1, 2, D, 1); } // -- return the result return new DSymbol(ds); } /** * Constructs a tiling instance. * @param ds the Delaney symbol for the tiling. * @param name the name of this instance. */ public Document(final DSymbol ds, final String name) { this(ds, name, null); } /** * Constructs a tiling instance. * @param ds the Delaney symbol for the tiling. * @param name the name of this instance. * @param cov a pre-given (pseudo-) toroidal cover. */ public Document( final DSymbol ds, final String name, final DSCover<Integer> cov) { this.given_symbol = ds; this.name = name; this.given_cover = cov; if (ds.dim() == 2) { this.type = TILING_2D; } else if (ds.dim() == 3) { this.type = TILING_3D; } else { final String msg = "only dimensions 2 and 3 supported"; throw new UnsupportedOperationException(msg); } } public Document( final GenericParser.Block block, final String defaultName) { final String type = block.getType().toLowerCase(); if (type.equals("tiling")) { this.type = TILING_3D; } else { this.type = NET; } final String name = block.getEntriesAsString("name"); if (name == null || name.length() == 0) { this.name = defaultName; } else { this.name = name; } this.data = block; } public void clearCache() { this.cache.clear(); } public boolean isUnprocessed() { return this.symbol == null; } public Document cleanCopy() { if (this.data != null) return new Document(this.data, this.name); else return new Document(this.given_symbol, this.name, this.given_cover); } public String getName() { return this.name; } public Object getType() { return this.type; } public DSymbol getSymbol() { if (this.symbol == null) { if (this.data != null) { if (this.type == TILING_3D) extractFromFaceList(this.data); else extractFromNet(this.data); } else if (this.given_symbol != null) extractFromDSymbol(this.given_symbol); } return this.symbol; } private void extractFromDSymbol(final DSymbol ds) { if (this.useMaximalSymmetry) this.symbol = new DSymbol(this.given_symbol.minimal()); else this.symbol = this.given_symbol; if (this.type == TILING_2D) this.effective_symbol = extrusion(ds); else this.effective_symbol = ds; } private void extractFromFaceList(final Block data) { final FaceList fl = new FaceList(data); final DSymbol raw = fl.getSymbol(); final DSCover<Integer> cov = fl.getCover(); if (this.useMaximalSymmetry) { final DSymbol ds = this.symbol = new DSymbol(raw.minimal()); if (cov.size() == Covers.pseudoToroidalCover3D(ds).size()) { this.given_cover = new DSCover<Integer>(fl.getCover(), ds, 1); this.given_positions = fl.getPositions(); this.given_gram_matrix = fl.getGramMatrix(); } } else { this.symbol = raw; this.given_cover = cov; this.given_positions = fl.getPositions(); this.given_gram_matrix = fl.getGramMatrix(); } } private void extractFromNet(final Block data) { final Net net = new NetParser((BufferedReader) null).parseNet(data); if (net.getDimension() != 2) { throw new UnsupportedOperationException( "Only nets of dimension 2 are supported."); } final DSymbol ds = this.symbol = symbolForNet(net); this.effective_symbol = extrusion(ds); this.type = TILING_2D; } private DSymbol getEffectiveSymbol() { getSymbol(); if (this.effective_symbol == null) this.effective_symbol = this.symbol; return this.effective_symbol; } public Tiling getTiling() { try { return (Tiling) cache.get(TILING); } catch (CacheMissException ex) { return (Tiling) cache.put(TILING, new Tiling(getEffectiveSymbol(), given_cover)); } } public Tiling.Skeleton getNet() { return getTiling().getSkeleton(); } @SuppressWarnings("unchecked") public List<Tiling.Tile> getTiles() { try { return (List<Tiling.Tile>) cache.get(TILES); } catch (CacheMissException ex) { return (List<Tiling.Tile>) cache.put(TILES, getTiling().getTiles()); } } public Tiling.Tile getTile(final int k) { return (Tiling.Tile) getTiles().get(k); } private SpaceGroupFinder getFinder() { try { return (SpaceGroupFinder) cache.get(FINDER); } catch (CacheMissException ex) { return (SpaceGroupFinder) cache.put(FINDER, new SpaceGroupFinder( getTiling().getSpaceGroup())); } } private Map<INode, Point> getNodePositions() { final Tiling.Skeleton skel = getNet(); if (given_positions == null || getIgnoreInputCoordinates()) return skel.barycentricPlacement(); else { // Extract the given coordinates final Map<INode, Point> pos = new HashMap<INode, Point>(); for (int D: given_positions.keySet()) pos.put(skel.nodeForChamber(D), given_positions.get(D)); // Shift to put the first node on the coordinate origin final Point p0 = pos.get(skel.nodes().next()); final Point origin = Point.origin(p0.getDimension()); final Vector shift = (Vector) p0.minus(origin); for (final INode v: skel.nodes()) pos.put(v, (Point) pos.get(v).minus(shift)); // Symmetrize node positions // TODO also need to symmetrize within orbits for (final INode v: skel.nodes()) { final Point p = skel.barycentricPlacement().get(v); final int dim = p.getDimension(); Matrix s = Matrix.zero(dim + 1, dim + 1); for (final Morphism phi: skel.nodeStabilizer(v)) { final Operator a = phi.getAffineOperator(); final Vector d = (Vector) p.minus(p.times(a)); final Operator ad = (Operator) a.times(d); s = (Matrix) s.plus(ad.getCoordinates()); } pos.put(v, (Point) pos.get(v).times(new Operator(s))); } // Return the result return pos; } } private Embedder getEmbedder() { try { return (Embedder) cache.get(EMBEDDER); } catch (CacheMissException ex) { return (Embedder) cache.put(EMBEDDER, new Embedder(getNet(), getNodePositions(), false)); } } public void initializeEmbedder() { getEmbedder(); } public void invalidateEmbedding() { cache.remove(EMBEDDER_OUTPUT); } public void invalidateTiling() { removeAll(); cache.clear(); this.symbol = null; this.effective_symbol = null; this.given_cover = null; this.given_positions = null; this.given_gram_matrix = null; this.transformation = null; this.tileClassColor = null; this.facetClassColor.clear(); this.hiddenFacetClasses.clear(); } private class EmbedderOutput { final private Map<DSPair<Integer>, Point> positions; final private CoordinateChange change; private EmbedderOutput( final Map<DSPair<Integer>, Point> pos, final CoordinateChange change) { this.positions = pos; this.change = change; } } private EmbedderOutput getEmbedderOutput() { try { return (EmbedderOutput) cache.get(EMBEDDER_OUTPUT); } catch (CacheMissException ex) { final Embedder embedder = getEmbedder(); embedder.reset(); embedder.setPositions(getNodePositions()); embedder.setPasses(getEqualEdgePriority()); embedder.setGramMatrix(given_gram_matrix); if ((given_gram_matrix == null || getIgnoreInputCell()) && (embedder.getGraph().isStable() || !getRelaxCoordinates())) { embedder.setRelaxPositions(false); embedder.go(500); } if (getRelaxCoordinates()) { embedder.setRelaxPositions(true); embedder.go(getEmbedderStepLimit()); } embedder.normalize(); final Matrix G = embedder.getGramMatrix(); if (!G.equals(G.transposed())) { throw new RuntimeException("asymmetric Gram matrix:\n" + G); } final CoordinateChange change = new CoordinateChange(LinearAlgebra.orthonormalRowBasis(G)); final Map<DSPair<Integer>, Point> pos = getTiling().cornerPositions(embedder.getPositions()); return (EmbedderOutput) cache.put(EMBEDDER_OUTPUT, new EmbedderOutput(pos, change)); } } private Map<DSPair<Integer>, Point> getPositions() { return getEmbedderOutput().positions; } public CoordinateChange getEmbedderToWorld() { return getEmbedderOutput().change; } public double[] cornerPosition(final int i, final int D) { final Point p0 = getPositions().get(new DSPair<Integer>(i, D)); final Point p = (Point) p0.times(getEmbedderToWorld()); return p.getCoordinates().asDoubleArray()[0]; } public double volume() { double vol = 0.0; for (final int D: getTiling().getCover().elements()) { final double p[][] = new double[4][]; for (int i = 0; i < 4; ++i) p[i] = cornerPosition(i, D); for (int i = 1; i < 4; ++i) for (int j = 0; j < 3; ++j) p[i][j] -= p[0][j]; final double or = getTiling().coverOrientation(D); vol -= or * p[1][0] * p[2][1] * p[3][2]; vol -= or * p[1][1] * p[2][2] * p[3][0]; vol -= or * p[1][2] * p[2][0] * p[3][1]; vol += or * p[1][2] * p[2][1] * p[3][0]; vol += or * p[1][1] * p[2][0] * p[3][2]; vol += or * p[1][0] * p[2][2] * p[3][1]; } return vol / 6.0; } public Point nodePoint(final INode v) { final int D = getNet().chamberAtNode(v); final Point p = getPositions().get(new DSPair<Integer>(0, D)); return (Point) p.times(getEmbedderToWorld()); } public Point edgeSourcePoint(final IEdge e) { final int D = getNet().chamberAtNode(e.source()); final Point p = getPositions().get(new DSPair<Integer>(0, D)); return (Point) p.times(getEmbedderToWorld()); } public Point edgeTargetPoint(final IEdge e) { final int D = getNet().chamberAtNode(e.target()); final Vector s = getNet().getShift(e); final Point q0 = (Point) (getPositions().get(new DSPair<Integer>(0, D))).plus(s); return (Point) q0.times(getEmbedderToWorld()); } public List<Vector> centerIntoUnitCell(final Tiling.Tile t) { final int dim = getEffectiveSymbol().dim(); final DSPair<Integer> c = new DSPair<Integer>(dim, t.getChamber()); return pointIntoUnitCell(getPositions().get(c)); } public List<Vector> centerIntoUnitCell(final IEdge e) { final Tiling.Skeleton net = getNet(); final int C = net.chamberAtNode(e.source()); final int D = net.chamberAtNode(e.target()); final Vector s = net.getShift(e); final Point p = getPositions().get(new DSPair<Integer>(0, C)); final Point q = (Point) (getPositions().get(new DSPair<Integer>(0, D))).plus(s); return pointIntoUnitCell( (Point) p.plus(((Vector) q.minus(p)).times(0.5))); } public List<Vector> centerIntoUnitCell(final INode v) { final int D = getNet().chamberAtNode(v); return pointIntoUnitCell(getPositions().get(new DSPair<Integer>(0, D))); } private Vector shifted(final Point p0, final Vector s, final CoordinateChange c) { final int dim = p0.getDimension(); final Point p = (Point) p0.plus(s).times(c); final Real a[] = new Real[dim]; for (int i = 0; i < dim; ++i) { a[i] = (Real) p.get(i).plus(0.001).mod(Whole.ONE); } final Vector v = (Vector) new Point(a).minus(p).times(c.inverse()); final Whole b[] = new Whole[dim]; for (int i = 0; i < dim; ++i) { b[i] = (Whole) v.get(i).round(); } return (Vector) new Vector(b).plus(s); } public List<Vector> pointIntoUnitCell(final Point p) { final int dim = p.getDimension(); final CoordinateChange toStd; if (getUsePrimitiveCell()) { toStd = new CoordinateChange(Operator.identity(dim)); } else { toStd = getFinder().getToStd(); } final List<Vector> result = new ArrayList<Vector>(); for (final Vector s : getCenteringVectors()) { Vector v = shifted(p, s, toStd); if (getUsePrimitiveCell()) { v = (Vector) v.plus(originShiftForPrimitive()); } result.add(v); } return result; } public Color[] getPalette() { if (this.tileClassColor == null) { int n = getEffectiveSymbol().numberOfOrbits(new IndexList(0, 1, 2)); this.tileClassColor = new Color[n]; fillPalette(this.tileClassColor); } return this.tileClassColor; } private void fillPalette(final Color[] palette) { final int n = palette.length; final int map[] = randomPermutation(n); final float offset = random.nextFloat(); final float s = 0.6f; final float b = 1.0f; for (int i = 0; i < n; ++i) { final float h = (i / (float) n + offset) % 1.0f; palette[map[i]] = Color.getHSBColor(h, s, b); } } private int[] randomPermutation(final int n) { final int result[] = new int[n]; final List<Integer> free = new ArrayList<Integer>(); for (int i = 0; i < n; ++i) { free.add(i); } for (int i = 0; i < n; ++i) { final int j = random.nextInt(n - i); result[i] = free.remove(j); } return result; } public Color getEfffectiveColor(final Item item) { Color c = color(item); if (c == null && item.isFacet()) { c = getFacetClassColor(item.getFacet()); if (c == null) c = getDefaultTileColor(item.getFacet().getTile()); } if (c == null && item.isTile()) c = getDefaultTileColor(item.getTile()); return c; } public Color getTileClassColor(final int i) { return getPalette()[i]; } public Color getDefaultTileColor(final Tiling.Tile t) { return getTileClassColor(t.getKind()); } public Color getDefaultTileColor(final int i) { return getDefaultTileColor(getTile(i)); } public void setTileClassColor(final int i, final Color c) { getPalette()[i] = c; } public Color getFacetClassColor(final Tiling.Facet f) { return this.facetClassColor.get(f); } public Collection<Tiling.Facet> getColoredFacetClasses() { return Collections.unmodifiableSet(this.facetClassColor.keySet()); } public void setFacetClassColor(final Tiling.Facet f, final Color c) { this.facetClassColor.put(f, c); } public void removeFacetClassColor(final Tiling.Facet f) { this.facetClassColor.remove(f); } public boolean isHiddenFacetClass(final Tiling.Facet f) { return this.hiddenFacetClasses.contains(f); } public Collection<Tiling.Facet> getHiddenFacetClasses() { return Collections.unmodifiableSet(this.hiddenFacetClasses); } public void hideFacetClass(final Tiling.Facet f) { this.hiddenFacetClasses.add(f); } public void showFacetClass(final Tiling.Facet f) { this.hiddenFacetClasses.remove(f); } public void randomlyRecolorTiles() { fillPalette(getPalette()); } public String getSignature() { try { return (String) cache.get(SIGNATURE); } catch (CacheMissException ex) { final int dim = getSymbol().dim(); final String sig; if (dim == 2) { sig = Signature.ofTiling(getSymbol()); } else { sig = Signature.ofTiling(getTiling().getCover()); } return (String) cache.put(SIGNATURE, sig); } } public String getGroupName() { try { return (String) cache.get(SPACEGROUP); } catch (CacheMissException ex) { final int dim = getSymbol().dim(); final SpaceGroupFinder finder; if (dim == 2) { finder = new SpaceGroupFinder(new Tiling(getSymbol()) .getSpaceGroup()); } else { finder = getFinder(); } return (String) cache.put(SPACEGROUP, finder.getGroupName()); } } public CoordinateChange getCellToEmbedder() { return (CoordinateChange) getFinder().getToStd().inverse(); } public CoordinateChange getCellToWorld() { return (CoordinateChange) getCellToEmbedder().times(getEmbedderToWorld()); } public CoordinateChange getWorldToCell() { return (CoordinateChange) getCellToWorld().inverse(); } public double[][] getUnitCellVectors() { final int dim = getEffectiveSymbol().dim(); final CoordinateChange toStd = getFinder().getToStd(); final double result[][] = new double[dim][]; for (int i = 0; i < dim; ++i) { final Vector v; if (getUsePrimitiveCell()) { v = (Vector) Vector.unit(dim, i).times(toStd).times(getCellToWorld()); } else { v = (Vector) Vector.unit(dim, i).times(getCellToWorld()); } result[i] = v.getCoordinates().asDoubleArray()[0]; } return result; } public Vector[] getUnitCellVectorsInEmbedderCoordinates() { final int dim = getEffectiveSymbol().dim(); final CoordinateChange toStd = getFinder().getToStd(); final Vector result[] = new Vector[dim]; for (int i = 0; i < dim; ++i) { final Vector v; if (getUsePrimitiveCell()) { v = (Vector) Vector.unit(dim, i).times(toStd); } else { v = Vector.unit(dim, i); } result[i] = (Vector) v.times(getCellToEmbedder()); } return result; } @SuppressWarnings("unchecked") private List<Vector> getCenteringVectors() { try { return (List<Vector>) cache.get(CENTERING_VECTORS); } catch (CacheMissException ex) { final List<Vector> result = new ArrayList<Vector>(); final CoordinateChange fromStd = getFinder().getFromStd(); final int dim = getEffectiveSymbol().dim(); if (getUsePrimitiveCell()) { result.add(Vector.zero(dim)); } else { for (final Operator op : SpaceGroupCatalogue.operators(dim, getFinder().getExtendedGroupName())) { if (op.linearPart().isOne()) { result.add((Vector) op.translationalPart() .times(fromStd)); } } } return (List<Vector>) cache.put(CENTERING_VECTORS, result); } } private Vector originShiftForPrimitive() { final int dim = getEffectiveSymbol().dim(); Point p = Point.origin(dim); for (final Vector v: getUnitCellVectorsInEmbedderCoordinates()) { p = (Point) p.plus(v); } p = (Point) p.dividedBy(2); return shifted(p, Vector.zero(dim), getFinder().getToStd()); } public double[] getOrigin() { final int dim = getEffectiveSymbol().dim(); final CoordinateChange toStd = getFinder().getToStd(); final CoordinateChange id = new CoordinateChange(Operator.identity(dim)); final Point o; if (getUsePrimitiveCell()) { final Point p = (Point) Point.origin(dim).times(toStd.inverse()); o = (Point) p.plus(shifted(p, Vector.zero(dim), id)) .plus(originShiftForPrimitive()) .times(toStd).times(getCellToWorld()); } else { o = (Point) Point.origin(dim).times(getCellToWorld()); } return o.getCoordinates().asDoubleArray()[0]; } private static void add( final StringBuffer buf, final String key, final boolean val) { buf.append(key); buf.append(": "); buf.append(val); buf.append('\n'); } private static void add( final StringBuffer buf, final String key, final int val) { buf.append(key); buf.append(": "); buf.append(val); buf.append('\n'); } private static <T> void add( final StringBuffer buf, final String key, final T val) { buf.append(key); buf.append(": "); buf.append('"'); buf.append(val); buf.append('"'); buf.append('\n'); } public String info() { final DSymbol ds = getSymbol(); final StringBuffer buf = new StringBuffer(500); buf.append("---\n"); if (getName() == null) { add(buf, "name", "unnamed"); } else { add(buf, "name", getName().split("\\W+")[0]); } add(buf, "full_name", getName()); add(buf, "dsymbol", getSymbol().canonical().toString()); add(buf, "symbol_size", ds.size()); add(buf, "dimension", ds.dim()); add(buf, "transitivity", getTransitivity()); add(buf, "minimal", ds.isMinimal()); add(buf, "self_dual", ds.equals(ds.dual())); add(buf, "signature", getSignature()); add(buf, "spacegroup", getGroupName()); return buf.toString(); } public String getTransitivity() { final StringBuffer buf = new StringBuffer(10); final DelaneySymbol<Integer> ds = getSymbol(); for (int i = 0; i <= ds.dim(); ++i) { buf.append(showNumber(ds.numberOfOrbits(IndexList.except(ds, i)))); } return buf.toString(); } private static String showNumber(final int n) { if (n >= 0 && n < 10) { return String.valueOf(n); } else { return "(" + n + ")"; } } public static List<Document> load(final String path) throws FileNotFoundException { final String ext = path.substring(path.lastIndexOf('.') + 1) .toLowerCase(); return load(new FileReader(path), ext); } public static List<Document> load(final Reader input, final String ext) { final BufferedReader reader = new BufferedReader(input); final List<Document> result = new ArrayList<Document>(); if (ext.equals("cgd") || ext.equals("pgr")) { final GenericParser parser = new NetParser(reader); while (!parser.atEnd()) { final GenericParser.Block data = parser.parseDataBlock(); result.add(new Document(data, "#" + (result.size() + 1))); } } else if (ext.equals("ds") || ext.equals("tgs")){ final StringBuffer buffer = new StringBuffer(200); String name = null; while (true) { String line; try { line = reader.readLine(); } catch (IOException ex) { throw new RuntimeException(ex); } if (line == null) { break; } line = line.trim(); if (line.length() == 0) { continue; } if (line.charAt(0) == '#') { if (line.charAt(1) == '@') { line = line.substring(2).trim(); if (line.startsWith("name ")) { name = line.substring(5); } } } else { int i = line.indexOf('#'); if (i >= 0) { line = line.substring(0, i); } buffer.append(' '); buffer.append(line); if (buffer.toString().trim().endsWith(">")) { final DSymbol ds = new DSymbol(buffer.toString().trim()); buffer.delete(0, buffer.length()); if (name == null) { name = "#" + (result.size() + 1); } result.add(new Document(ds, name)); name = null; } } } } else if (ext.equals("gsl")) { try { final ObjectInputStream ostream = DocumentXStream.instance() .createObjectInputStream(reader); while (true) { final Document doc = (Document) ostream.readObject(); if (doc != null) { result.add(doc); } } } catch (EOFException ex) { ; // End of stream reached } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw new RuntimeException(ex); } } return result; } public String toXML() { return "<object-stream>\n" + DocumentXStream.instance().toXML(this) + "\n</object-stream>\n"; } public static void main(final String args[]) { final String path = args[0]; try { final List<Document> syms = load(path); for (final Document doc: syms) { if (doc.getName() != null) { System.out.println("#@ name " + doc.getName()); } System.out.println(doc.getSymbol().canonical()); System.out.println(doc.info()); } } catch (final FileNotFoundException ex) { ex.printStackTrace(); } } // --- getters and setters for options public int getEmbedderStepLimit() { return this.embedderStepLimit; } public void setEmbedderStepLimit(int embedderStepLimit) { if (embedderStepLimit != this.embedderStepLimit) { invalidateEmbedding(); this.embedderStepLimit = embedderStepLimit; } } public int getEqualEdgePriority() { return this.equalEdgePriority; } public void setEqualEdgePriority(int equalEdgePriority) { if (equalEdgePriority != this.equalEdgePriority) { invalidateEmbedding(); this.equalEdgePriority = equalEdgePriority; } } public boolean getIgnoreInputCell() { return this.ignoreInputCell; } public void setIgnoreInputCell(boolean ignoreInputCell) { if (ignoreInputCell != this.ignoreInputCell) { invalidateEmbedding(); this.ignoreInputCell = ignoreInputCell; } } public boolean getIgnoreInputCoordinates() { return this.ignoreInputCoordinates; } public void setIgnoreInputCoordinates(boolean ignoreInputCoordinates) { if (ignoreInputCoordinates != this.ignoreInputCoordinates) { invalidateEmbedding(); this.ignoreInputCoordinates = ignoreInputCoordinates; } } public boolean getRelaxCoordinates() { return this.relaxCoordinates; } public void setRelaxCoordinates(boolean relaxCoordinates) { if (relaxCoordinates != this.relaxCoordinates) { invalidateEmbedding(); this.relaxCoordinates = relaxCoordinates; } } public boolean getUseMaximalSymmetry() { return useMaximalSymmetry; } public void setUseMaximalSymmetry(boolean useMaximalSymmetry) { if (useMaximalSymmetry != this.useMaximalSymmetry) { invalidateTiling(); this.useMaximalSymmetry = useMaximalSymmetry; } } public boolean getUsePrimitiveCell() { return this.usePrimitiveCell; } public void setUsePrimitiveCell(final boolean value) { if (value != this.usePrimitiveCell) { cache.remove(CENTERING_VECTORS); this.usePrimitiveCell = value; } } public Properties getProperties() { return (Properties) this.properties.clone(); } public void setProperties(final Properties properties) { this.properties.clear(); this.properties.putAll(properties); } public Transformation getTransformation() { return this.transformation; } public void setTransformation(final Transformation transformation) { this.transformation = transformation; } public File getSaveSceneFile() { return this.saveSceneFile; } public void setSaveSceneFile(final File file) { this.saveSceneFile = file; } }
false
true
private DSymbol symbolForNet(final Net net) { // -- check if the argument is supported if (net.getDimension() != 2) { throw new UnsupportedOperationException( "Only nets of dimension 2 are supported"); } // -- helper class for sorting neighbors by angle class Neighbor implements Comparable<Neighbor> { final private IEdge edge; final private double angle; public Neighbor(final IEdge e, final double a) { this.edge = e; this.angle = a; } public int compareTo(final Neighbor other) { if (this.angle < other.angle) { return -1; } else if (this.angle > other.angle) { return 1; } else { return 0; } } } // -- initialize the Delaney symbol; map oriented net edges to chambers final Map<IEdge, Integer> edge2chamber = new HashMap<IEdge, Integer>(); final DynamicDSymbol ds = new DynamicDSymbol(2); for (final IEdge e: net.edges()) { final List<Integer> elms = ds.grow(4); edge2chamber.put(e, elms.get(0)); edge2chamber.put(e.reverse(), elms.get(2)); ds.redefineOp(2, elms.get(0), elms.get(1)); ds.redefineOp(2, elms.get(2), elms.get(3)); ds.redefineOp(0, elms.get(0), elms.get(3)); ds.redefineOp(0, elms.get(1), elms.get(2)); } // -- connect the edge orbits of the Delaney symbol final Map<INode, Point> pos = net.barycentricPlacement(); for (final INode v: net.nodes()) { final List<IEdge> incidences = net.allIncidences(v); if (!net.goodCombinations(incidences, pos).hasNext()) { throw new UnsupportedOperationException( "Only convex tilings are currently supported"); } final Point p = (Point) pos.get(v); final List<Neighbor> neighbors = new ArrayList<Neighbor>(); for (final IEdge e: incidences) { final Vector d = (Vector) net.getShift(e).plus(pos.get(e.target())).minus(p); final double[] a = d.getCoordinates().asDoubleArray()[0]; neighbors.add(new Neighbor(e, Math.atan2(a[1], a[0]))); } Collections.sort(neighbors); neighbors.add(neighbors.get(0)); for (int i = 0; i < neighbors.size() - 1; ++i) { final IEdge e = neighbors.get(i).edge; final IEdge f = neighbors.get(i + 1).edge; ds.redefineOp(1, ds.op(2, edge2chamber.get(e)), edge2chamber.get(f)); } } // -- set branching to one everywhere for (final int D: ds.elements()) { ds.redefineV(0, 1, D, 1); ds.redefineV(1, 2, D, 1); } // -- return the result return new DSymbol(ds); }
public static DSymbol symbolForNet(final Net net) { // -- check if the argument is supported if (net.getDimension() != 2) { throw new UnsupportedOperationException( "Only nets of dimension 2 are supported"); } // -- helper class for sorting neighbors by angle class Neighbor implements Comparable<Neighbor> { final private IEdge edge; final private double angle; public Neighbor(final IEdge e, final double a) { this.edge = e; this.angle = a; } public int compareTo(final Neighbor other) { if (this.angle < other.angle) { return -1; } else if (this.angle > other.angle) { return 1; } else { return 0; } } } // -- initialize the Delaney symbol; map oriented net edges to chambers final Map<IEdge, Integer> edge2chamber = new HashMap<IEdge, Integer>(); final DynamicDSymbol ds = new DynamicDSymbol(2); for (final IEdge e: net.edges()) { final List<Integer> elms = ds.grow(4); edge2chamber.put(e.oriented(), elms.get(0)); edge2chamber.put(e.oriented().reverse(), elms.get(2)); ds.redefineOp(2, elms.get(0), elms.get(1)); ds.redefineOp(2, elms.get(2), elms.get(3)); ds.redefineOp(0, elms.get(0), elms.get(3)); ds.redefineOp(0, elms.get(1), elms.get(2)); } // -- connect the edge orbits of the Delaney symbol final Map<INode, Point> pos = net.barycentricPlacement(); for (final INode v: net.nodes()) { final List<IEdge> incidences = net.allIncidences(v); if (!net.goodCombinations(incidences, pos).hasNext()) { throw new UnsupportedOperationException( "Only convex tilings are currently supported"); } final Point p = (Point) pos.get(v); final List<Neighbor> neighbors = new ArrayList<Neighbor>(); for (final IEdge e: incidences) { final Vector d = (Vector) net.getShift(e).plus(pos.get(e.target())).minus(p); final double[] a = d.getCoordinates().asDoubleArray()[0]; neighbors.add(new Neighbor(e, Math.atan2(a[1], a[0]))); } Collections.sort(neighbors); neighbors.add(neighbors.get(0)); for (int i = 0; i < neighbors.size() - 1; ++i) { final IEdge e = neighbors.get(i).edge; final IEdge f = neighbors.get(i + 1).edge; ds.redefineOp(1, ds.op(2, edge2chamber.get(e)), edge2chamber.get(f)); } } // -- set branching to one everywhere for (final int D: ds.elements()) { ds.redefineV(0, 1, D, 1); ds.redefineV(1, 2, D, 1); } // -- return the result return new DSymbol(ds); }
diff --git a/src/to/joe/j2mc/info/command/PlayerListCommand.java b/src/to/joe/j2mc/info/command/PlayerListCommand.java index 9da1119..89d6aaf 100644 --- a/src/to/joe/j2mc/info/command/PlayerListCommand.java +++ b/src/to/joe/j2mc/info/command/PlayerListCommand.java @@ -1,86 +1,86 @@ package to.joe.j2mc.info.command; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import to.joe.j2mc.core.J2MC_Manager; import to.joe.j2mc.core.command.MasterCommand; import to.joe.j2mc.info.J2MC_Info; public class PlayerListCommand extends MasterCommand { J2MC_Info plugin; public PlayerListCommand(J2MC_Info Info) { super(Info); this.plugin = Info; } @Override public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) { if (!sender.hasPermission("j2mc.core.admin")) { int total = 0; for(Player derp : plugin.getServer().getOnlinePlayers()){ if(!J2MC_Manager.getVisibility().isVanished(derp)){ total++; } } sender.sendMessage(ChatColor.AQUA + "Players (" + total + "/" + plugin.getServer().getMaxPlayers() + "):"); StringBuilder builder = new StringBuilder(); for (Player pl : plugin.getServer().getOnlinePlayers()) { if (!J2MC_Manager.getVisibility().isVanished(pl)) { String toAdd; toAdd = pl.getDisplayName(); if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){ toAdd = ChatColor.GOLD + pl.getName(); } builder.append(toAdd + ChatColor.WHITE + ", "); if (builder.length() > 119) { - builder.substring(0, (builder.length() - ((toAdd + ChatColor.WHITE + ", ").length()))); + builder.setLength(builder.length() - (toAdd + ChatColor.WHITE + ", ").length()); sender.sendMessage(builder.toString()); builder = new StringBuilder(); builder.append(toAdd + ChatColor.WHITE + ", "); } } } builder.setLength(builder.length() - 2); sender.sendMessage(builder.toString()); } else { sender.sendMessage(ChatColor.AQUA + "Players (" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers() + "):"); StringBuilder builder = new StringBuilder(); for (Player pl : plugin.getServer().getOnlinePlayers()) { String toAdd = ""; toAdd = ChatColor.GREEN + pl.getName(); if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 't')){ toAdd = ChatColor.DARK_GREEN + pl.getName(); } if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){ toAdd = ChatColor.GOLD + pl.getName(); } if(pl.hasPermission("j2mc-chat.mute")){ toAdd = ChatColor.YELLOW + pl.getName(); } if(pl.hasPermission("j2mc.core.admin")){ toAdd = ChatColor.RED + pl.getName(); } if(J2MC_Manager.getVisibility().isVanished(pl)){ toAdd = ChatColor.AQUA + pl.getName(); } if(pl.hasPermission("j2mc-chat.admin.nsa")){ toAdd += ChatColor.DARK_AQUA + "��"; } builder.append(toAdd + ChatColor.WHITE + ", "); if (builder.length() > 119) { - builder.substring(0, (builder.length() - (toAdd + ChatColor.WHITE + ", ").length())); + builder.setLength(builder.length() - (toAdd + ChatColor.WHITE + ", ").length()); sender.sendMessage(builder.toString()); builder = new StringBuilder(); builder.append(toAdd + ChatColor.WHITE + ", "); } } builder.setLength(builder.length() - 2); sender.sendMessage(builder.toString()); } } }
false
true
public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) { if (!sender.hasPermission("j2mc.core.admin")) { int total = 0; for(Player derp : plugin.getServer().getOnlinePlayers()){ if(!J2MC_Manager.getVisibility().isVanished(derp)){ total++; } } sender.sendMessage(ChatColor.AQUA + "Players (" + total + "/" + plugin.getServer().getMaxPlayers() + "):"); StringBuilder builder = new StringBuilder(); for (Player pl : plugin.getServer().getOnlinePlayers()) { if (!J2MC_Manager.getVisibility().isVanished(pl)) { String toAdd; toAdd = pl.getDisplayName(); if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){ toAdd = ChatColor.GOLD + pl.getName(); } builder.append(toAdd + ChatColor.WHITE + ", "); if (builder.length() > 119) { builder.substring(0, (builder.length() - ((toAdd + ChatColor.WHITE + ", ").length()))); sender.sendMessage(builder.toString()); builder = new StringBuilder(); builder.append(toAdd + ChatColor.WHITE + ", "); } } } builder.setLength(builder.length() - 2); sender.sendMessage(builder.toString()); } else { sender.sendMessage(ChatColor.AQUA + "Players (" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers() + "):"); StringBuilder builder = new StringBuilder(); for (Player pl : plugin.getServer().getOnlinePlayers()) { String toAdd = ""; toAdd = ChatColor.GREEN + pl.getName(); if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 't')){ toAdd = ChatColor.DARK_GREEN + pl.getName(); } if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){ toAdd = ChatColor.GOLD + pl.getName(); } if(pl.hasPermission("j2mc-chat.mute")){ toAdd = ChatColor.YELLOW + pl.getName(); } if(pl.hasPermission("j2mc.core.admin")){ toAdd = ChatColor.RED + pl.getName(); } if(J2MC_Manager.getVisibility().isVanished(pl)){ toAdd = ChatColor.AQUA + pl.getName(); } if(pl.hasPermission("j2mc-chat.admin.nsa")){ toAdd += ChatColor.DARK_AQUA + "��"; } builder.append(toAdd + ChatColor.WHITE + ", "); if (builder.length() > 119) { builder.substring(0, (builder.length() - (toAdd + ChatColor.WHITE + ", ").length())); sender.sendMessage(builder.toString()); builder = new StringBuilder(); builder.append(toAdd + ChatColor.WHITE + ", "); } } builder.setLength(builder.length() - 2); sender.sendMessage(builder.toString()); } }
public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) { if (!sender.hasPermission("j2mc.core.admin")) { int total = 0; for(Player derp : plugin.getServer().getOnlinePlayers()){ if(!J2MC_Manager.getVisibility().isVanished(derp)){ total++; } } sender.sendMessage(ChatColor.AQUA + "Players (" + total + "/" + plugin.getServer().getMaxPlayers() + "):"); StringBuilder builder = new StringBuilder(); for (Player pl : plugin.getServer().getOnlinePlayers()) { if (!J2MC_Manager.getVisibility().isVanished(pl)) { String toAdd; toAdd = pl.getDisplayName(); if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){ toAdd = ChatColor.GOLD + pl.getName(); } builder.append(toAdd + ChatColor.WHITE + ", "); if (builder.length() > 119) { builder.setLength(builder.length() - (toAdd + ChatColor.WHITE + ", ").length()); sender.sendMessage(builder.toString()); builder = new StringBuilder(); builder.append(toAdd + ChatColor.WHITE + ", "); } } } builder.setLength(builder.length() - 2); sender.sendMessage(builder.toString()); } else { sender.sendMessage(ChatColor.AQUA + "Players (" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers() + "):"); StringBuilder builder = new StringBuilder(); for (Player pl : plugin.getServer().getOnlinePlayers()) { String toAdd = ""; toAdd = ChatColor.GREEN + pl.getName(); if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 't')){ toAdd = ChatColor.DARK_GREEN + pl.getName(); } if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){ toAdd = ChatColor.GOLD + pl.getName(); } if(pl.hasPermission("j2mc-chat.mute")){ toAdd = ChatColor.YELLOW + pl.getName(); } if(pl.hasPermission("j2mc.core.admin")){ toAdd = ChatColor.RED + pl.getName(); } if(J2MC_Manager.getVisibility().isVanished(pl)){ toAdd = ChatColor.AQUA + pl.getName(); } if(pl.hasPermission("j2mc-chat.admin.nsa")){ toAdd += ChatColor.DARK_AQUA + "��"; } builder.append(toAdd + ChatColor.WHITE + ", "); if (builder.length() > 119) { builder.setLength(builder.length() - (toAdd + ChatColor.WHITE + ", ").length()); sender.sendMessage(builder.toString()); builder = new StringBuilder(); builder.append(toAdd + ChatColor.WHITE + ", "); } } builder.setLength(builder.length() - 2); sender.sendMessage(builder.toString()); } }
diff --git a/srcj/com/sun/electric/tool/user/tecEdit/LibToTech.java b/srcj/com/sun/electric/tool/user/tecEdit/LibToTech.java index 7a287fd7c..a998069d4 100644 --- a/srcj/com/sun/electric/tool/user/tecEdit/LibToTech.java +++ b/srcj/com/sun/electric/tool/user/tecEdit/LibToTech.java @@ -1,3658 +1,3658 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: LibToTech.java * Technology Editor, conversion of technology libraries to technologies * Written by Steven M. Rubin, Sun Microsystems. * * Copyright (c) 2005 Sun Microsystems and Static Free Software * * Electric(tm) 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. * * Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.user.tecEdit; import com.sun.electric.database.CellId; import com.sun.electric.database.geometry.DBMath; import com.sun.electric.database.geometry.EPoint; import com.sun.electric.database.geometry.Poly; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.database.hierarchy.EDatabase; import com.sun.electric.database.hierarchy.Library; import com.sun.electric.database.network.Netlist; import com.sun.electric.database.network.Network; import com.sun.electric.database.prototype.NodeProto; import com.sun.electric.database.text.TextUtils; import com.sun.electric.database.text.Version; import com.sun.electric.database.topology.ArcInst; import com.sun.electric.database.topology.NodeInst; import com.sun.electric.database.variable.TextDescriptor; import com.sun.electric.database.variable.Variable; import com.sun.electric.technology.DRCTemplate; import com.sun.electric.technology.EdgeH; import com.sun.electric.technology.EdgeV; import com.sun.electric.technology.PrimitiveNode; import com.sun.electric.technology.SizeOffset; import com.sun.electric.technology.Technology; import com.sun.electric.technology.Xml; import com.sun.electric.technology.technologies.Artwork; import com.sun.electric.technology.technologies.Generic; import com.sun.electric.tool.Job; import com.sun.electric.tool.io.FileType; import com.sun.electric.tool.user.User; import com.sun.electric.tool.user.dialogs.EDialog; import com.sun.electric.tool.user.dialogs.OpenFile; import com.sun.electric.tool.user.ui.WindowFrame; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; /** * This class creates technologies from technology libraries. */ public class LibToTech { /* the meaning of "us_tecflags" */ // private static final int HASDRCMINWID = 01; /* has DRC minimum width information */ // private static final int HASDRCMINWIDR = 02; /* has DRC minimum width information */ // private static final int HASCOLORMAP = 04; /* has color map */ // private static final int HASARCWID = 010; /* has arc width offset factors */ // private static final int HASCIF = 020; /* has CIF layers */ // private static final int HASDXF = 040; /* has DXF layers */ // private static final int HASGDS = 0100; /* has Calma GDS-II layers */ // private static final int HASGRAB = 0200; /* has grab point information */ // private static final int HASSPIRES = 0400; /* has SPICE resistance information */ // private static final int HASSPICAP = 01000; /* has SPICE capacitance information */ // private static final int HASSPIECAP = 02000; /* has SPICE edge capacitance information */ // private static final int HAS3DINFO = 04000; /* has 3D height/thickness information */ // private static final int HASCONDRC = 010000; /* has connected design rules */ // private static final int HASCONDRCR = 020000; /* has connected design rules reasons */ // private static final int HASUNCONDRC = 040000; /* has unconnected design rules */ // private static final int HASUNCONDRCR = 0100000; /* has unconnected design rules reasons */ // private static final int HASCONDRCW = 0200000; /* has connected wide design rules */ // private static final int HASCONDRCWR = 0400000; /* has connected wide design rules reasons */ // private static final int HASUNCONDRCW = 01000000; /* has unconnected wide design rules */ // private static final int HASUNCONDRCWR = 02000000; /* has unconnected wide design rules reasons */ // private static final int HASCONDRCM = 04000000; /* has connected multicut design rules */ // private static final int HASCONDRCMR = 010000000; /* has connected multicut design rules reasons */ // private static final int HASUNCONDRCM = 020000000; /* has unconnected multicut design rules */ // private static final int HASUNCONDRCMR = 040000000; /* has unconnected multicut design rules reasons */ // private static final int HASEDGEDRC = 0100000000; /* has edge design rules */ // private static final int HASEDGEDRCR = 0200000000; /* has edge design rules reasons */ // private static final int HASMINNODE = 0400000000; /* has minimum node size */ // private static final int HASMINNODER = 01000000000; /* has minimum node size reasons */ // private static final int HASPRINTCOL = 02000000000; /* has print colors */ /* the globals that define a technology */ // static int us_tecflags; // static INTBIG us_teclayer_count; // static CHAR **us_teclayer_iname = 0; // static CHAR **us_teclayer_names = 0; // static DRCRULES *us_tecdrc_rules = 0; // static INTBIG *us_tecnode_grab = 0; // static INTBIG us_tecnode_grabcount; private TechConversionResult error; /************************************* API AND USER INTERFACE *************************************/ /** * Method to convert the current library to a technology in a new job. * Starts with a dialog to control the process. */ public static void makeTechFromLib() { new GenerateTechnology(); } /** * This class displays a dialog for converting a library to a technology. */ private static class GenerateTechnology extends EDialog { private JLabel lab2, lab3; private JTextField renameName, newName; private JCheckBox alsoXML; /** Creates new form convert library to technology */ private GenerateTechnology() { super(null, true); initComponents(); setVisible(true); } protected void escapePressed() { exit(false); } // Call this method when the user clicks the OK button private void exit(boolean goodButton) { if (goodButton) new TechFromLibJob(newName.getText(), alsoXML.isSelected()); dispose(); } private void nameChanged() { String techName = newName.getText(); if (Technology.findTechnology(techName) != null) { // name exists, offer to rename it lab2.setEnabled(true); lab3.setEnabled(true); renameName.setEnabled(true); renameName.setEditable(true); } else { // name is unique, don't offer to rename it lab2.setEnabled(false); lab3.setEnabled(false); renameName.setEnabled(false); renameName.setEditable(false); } } private void initComponents() { getContentPane().setLayout(new GridBagLayout()); setTitle("Convert Library to Technology"); setName(""); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { exit(false); } }); JLabel lab1 = new JLabel("Creating new technology:"); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(4, 4, 4, 4); getContentPane().add(lab1, gbc); newName = new JTextField(Library.getCurrent().getName()); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 0; gbc.gridwidth = 2; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1; gbc.insets = new Insets(4, 4, 4, 4); getContentPane().add(newName, gbc); newName.getDocument().addDocumentListener(new TechNameDocumentListener()); lab2 = new JLabel("Already a technology with this name"); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 3; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(4, 4, 4, 4); getContentPane().add(lab2, gbc); lab3 = new JLabel("Rename existing technology to:"); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 2; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(4, 4, 4, 4); getContentPane().add(lab3, gbc); renameName = new JTextField(); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 2; gbc.gridwidth = 2; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1; gbc.insets = new Insets(4, 4, 4, 4); getContentPane().add(renameName, gbc); alsoXML = new JCheckBox("Also write XML code"); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 3; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(4, 4, 4, 4); getContentPane().add(alsoXML, gbc); // OK and Cancel JButton cancel = new JButton("Cancel"); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 3; gbc.insets = new Insets(4, 4, 4, 4); getContentPane().add(cancel, gbc); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { exit(false); } }); JButton ok = new JButton("OK"); getRootPane().setDefaultButton(ok); gbc = new GridBagConstraints(); gbc.gridx = 2; gbc.gridy = 3; gbc.insets = new Insets(4, 4, 4, 4); getContentPane().add(ok, gbc); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { exit(true); } }); pack(); } /** * Class to handle special changes to the new technology name. */ private class TechNameDocumentListener implements DocumentListener { public void changedUpdate(DocumentEvent e) { nameChanged(); } public void insertUpdate(DocumentEvent e) { nameChanged(); } public void removeUpdate(DocumentEvent e) { nameChanged(); } } } /************************************* BUILDING TECHNOLOGY FROM LIBRARY *************************************/ /** * Class to create a technology-library from a technology (in a Job). */ private static class TechFromLibJob extends Job { private String newName; private String fileName; private TechConversionResult tcr; private TechFromLibJob(String newName, boolean alsoXML) { super("Make Technology from Technolog Library", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER); this.newName = newName; if (alsoXML) { // print the technology as XML fileName = OpenFile.chooseOutputFile(FileType.XML, "File for Technology's XML Code", newName + ".xml"); } startJob(); } @Override public boolean doIt() { LibToTech ltt = new LibToTech(); tcr = new TechConversionResult(); ltt.makeTech(newName, fileName, tcr); fieldVariableChanged("tcr"); return true; } public void terminateOK() { if (tcr.failed()) { tcr.showError(); System.out.println("Failed to convert the library to a technology"); } } } /** * Method to convert the current Library to a Technology. * @param newName the name of the Technology to create. * @param fileName the name of the XML file to write (null to skip XML output). * @param error the structure for storing error status. * @return the new Technology. Returns null on error (and fills in "error"). */ public Technology makeTech(String newName, String fileName, TechConversionResult error) { this.error = error; Library lib = Library.getCurrent(); // get a new name for the technology String newTechName = newName; boolean modified = false; for(;;) { // search by hand because "gettechnology" handles partial matches if (Technology.findTechnology(newTechName) == null) break; newTechName += "X"; modified = true; } if (modified) System.out.println("Warning: already a technology called " + newName + ". Naming this " + newTechName); // get list of dependent libraries Library [] dependentLibs = Info.getDependentLibraries(lib); // get general information from the "factors" cell Cell np = null; for(int i=dependentLibs.length-1; i>=0; i--) { np = dependentLibs[i].findNodeProto("factors"); if (np != null) break; } if (np == null) { error.markError(null, null, "Cell with general information, called 'factors', is missing"); return null; } GeneralInfo gi = parseCell(np); // get layer information LayerInfo [] lList = extractLayers(dependentLibs); if (lList == null) return null; // get arc information ArcInfo [] aList = extractArcs(dependentLibs, lList); if (aList == null) return null; // get node information NodeInfo [] nList = extractNodes(dependentLibs, lList, aList); if (nList == null) return null; for(NodeInfo ni: nList) ni.arcsShrink = ni.func == PrimitiveNode.Function.PIN && !ni.wipes; // create the pure-layer associations for(int i=0; i<lList.length; i++) { if (lList[i].pseudo) continue; // find the pure layer node for(int j=0; j<nList.length; j++) { if (nList[j].func != PrimitiveNode.Function.NODE) continue; NodeInfo.LayerDetails nld = nList[j].nodeLayers[0]; if (nld.layer == lList[i]) { lList[i].pureLayerNode = nList[j]; break; } } } // add the component menu information if available Variable var = Library.getCurrent().getVar(Info.COMPMENU_KEY); if (var != null) { String compMenuXML = (String)var.getObject(); List<Xml.PrimitiveNode> nodes = new ArrayList<Xml.PrimitiveNode>(); for(int i=0; i<nList.length; i++) { Xml.PrimitiveNode xnp = new Xml.PrimitiveNode(); xnp.name = nList[i].name; xnp.function = nList[i].func; nodes.add(xnp); } List<Xml.ArcProto> arcs = new ArrayList<Xml.ArcProto>(); for(int i=0; i<aList.length; i++) { Xml.ArcProto xap = new Xml.ArcProto(); xap.name = aList[i].name; arcs.add(xap); } Xml.MenuPalette xmp = Xml.parseComponentMenuXMLTechEdit(compMenuXML, nodes, arcs); int menuWid = xmp.numColumns; int menuHei = xmp.menuBoxes.size() / menuWid; gi.menuPalette = new Object[menuHei][menuWid]; int i = 0; for(int y=0; y<menuHei; y++) { for(int x=0; x<menuWid; x++) { List<Object> items = xmp.menuBoxes.get(i++); Object item = null; if (items.size() == 1) { item = items.get(0); } else if (items.size() > 1) { List<Object> convItems = new ArrayList<Object>(); for(Object obj : items) convItems.add(obj); item = convItems; } gi.menuPalette[y][x] = item; } } } Xml.Technology t = makeXml(newTechName, gi, lList, nList, aList); if (fileName != null) t.writeXml(fileName); Technology tech = new Technology(t); tech.setup(); // switch to this technology System.out.println("Technology " + tech.getTechName() + " built."); WindowFrame.updateTechnologyLists(); return tech; } // private void checkAndWarn(LayerInfo [] lList, ArcInfo [] aList, NodeInfo [] nList) // { // // make sure there is a pure-layer node for every nonpseudo layer // for(int i=0; i<lList.length; i++) // { // if (lList[i].pseudo) continue; // boolean found = false; // for(int j=0; j<nList.length; j++) // { // NodeInfo nIn = nList[j]; // if (nIn.func != PrimitiveNode.Function.NODE) continue; // if (nIn.nodeLayers[0].layer == lList[i]) // { // found = true; // break; // } // } // if (found) continue; // System.out.println("Warning: Layer " + lList[i].name + " has no associated pure-layer node"); // } // // // make sure there is a pin for every arc and that it uses pseudo-layers // for(int i=0; i<aList.length; i++) // { // // find that arc's pin // boolean found = false; // for(int j=0; j<nList.length; j++) // { // NodeInfo nIn = nList[j]; // if (nIn.func != PrimitiveNode.Function.PIN) continue; // // for(int k=0; k<nIn.nodePortDetails.length; k++) // { // ArcInfo [] connections = nIn.nodePortDetails[k].connections; // for(int l=0; l<connections.length; l++) // { // if (connections[l] == aList[i]) // { // // pin found: make sure it uses pseudo-layers // boolean allPseudo = true; // for(int m=0; m<nIn.nodeLayers.length; m++) // { // LayerInfo lin = nIn.nodeLayers[m].layer; // if (!lin.pseudo) { allPseudo = false; break; } // } // if (!allPseudo) // System.out.println("Warning: Pin " + nIn.name + " is not composed of pseudo-layers"); // // found = true; // break; // } // } // if (found) break; // } // if (found) break; // } // if (!found) // System.out.println("Warning: Arc " + aList[i].name + " has no associated pin node"); // } // } /** * Method to parse the miscellaneous-info cell in "np" and return a GeneralInfo object that describes it. */ private GeneralInfo parseCell(Cell np) { // create and initialize the GRAPHICS structure GeneralInfo gi = new GeneralInfo(); for(Iterator<NodeInst> it = np.getNodes(); it.hasNext(); ) { NodeInst ni = it.next(); int opt = Manipulate.getOptionOnNode(ni); String str = Info.getValueOnNode(ni); switch (opt) { case Info.TECHSHORTNAME: gi.shortName = str; break; case Info.TECHSCALE: gi.scale = TextUtils.atof(str); gi.scaleRelevant = true; break; case Info.TECHFOUNDRY: gi.defaultFoundry = str; break; case Info.TECHDEFMETALS: gi.defaultNumMetals = TextUtils.atoi(str); break; case Info.TECHDESCRIPT: gi.description = str; break; case Info.TECHSPICEMINRES: gi.minRes = TextUtils.atof(str); break; case Info.TECHSPICEMINCAP: gi.minCap = TextUtils.atof(str); break; case Info.TECHMAXSERIESRES: gi.maxSeriesResistance = TextUtils.atof(str); break; case Info.TECHGATESHRINK: gi.gateShrinkage = TextUtils.atof(str); break; case Info.TECHGATEINCLUDED: gi.includeGateInResistance = str.equalsIgnoreCase("yes"); break; case Info.TECHGROUNDINCLUDED: gi.includeGround = str.equalsIgnoreCase("yes"); break; case Info.TECHTRANSPCOLORS: Color [] colors = GeneralInfo.getTransparentColors(ni); if (colors != null) gi.transparentColors = colors; break; case Info.CENTEROBJ: break; default: error.markError(ni, np, "Unknown node in miscellaneous-information cell"); break; } } return gi; } /************************************* LAYER ANALYSIS *************************************/ /** * Method to scan the "dependentlibcount" libraries in "dependentLibs", * and build the layer structures for it in technology "tech". Returns true on error. */ private LayerInfo [] extractLayers(Library [] dependentLibs) { // first find the number of layers Cell [] layerCells = Info.findCellSequence(dependentLibs, "layer-", Info.LAYERSEQUENCE_KEY); if (layerCells.length <= 0) { System.out.println("No layers found"); return null; } // create the layers LayerInfo [] lis = new LayerInfo[layerCells.length]; for(int i=0; i<layerCells.length; i++) { lis[i] = LayerInfo.parseCell(layerCells[i]); if (lis[i] == null) { error.markError(null, layerCells[i], "Error parsing layer information"); continue; } } // // get the design rules // drcsize = us_teclayer_count*us_teclayer_count/2 + (us_teclayer_count+1)/2; // us_tecedgetlayernamelist(); // if (us_tecdrc_rules != 0) // { // dr_freerules(us_tecdrc_rules); // us_tecdrc_rules = 0; // } // nodecount = Info.findCellSequence(dependentLibs, "node-", Generate.NODERSEQUENCE_KEY); // us_tecdrc_rules = dr_allocaterules(us_teceddrclayers, nodecount, x_("EDITED TECHNOLOGY")); // if (us_tecdrc_rules == NODRCRULES) return(TRUE); // for(i=0; i<us_teceddrclayers; i++) // (void)allocstring(&us_tecdrc_rules.layernames[i], us_teceddrclayernames[i], el_tempcluster); // for(i=0; i<nodecount; i++) // (void)allocstring(&us_tecdrc_rules.nodenames[i], &nodesequence[i].protoname[5], el_tempcluster); // if (nodecount > 0) efree((CHAR *)nodesequence); // var = NOVARIABLE; // for(i=dependentlibcount-1; i>=0; i--) // { // var = getval((INTBIG)dependentLibs[i], VLIBRARY, VSTRING|VISARRAY, x_("EDTEC_DRC")); // if (var != NOVARIABLE) break; // } // us_teceditgetdrcarrays(var, us_tecdrc_rules); // // see which design rules exist // for(i=0; i<us_teceddrclayers; i++) // { // if (us_tecdrc_rules.minwidth[i] >= 0) us_tecflags |= HASDRCMINWID; // if (*us_tecdrc_rules.minwidthR[i] != 0) us_tecflags |= HASDRCMINWIDR; // } // for(i=0; i<drcsize; i++) // { // if (us_tecdrc_rules.conlist[i] >= 0) us_tecflags |= HASCONDRC; // if (*us_tecdrc_rules.conlistR[i] != 0) us_tecflags |= HASCONDRCR; // if (us_tecdrc_rules.unconlist[i] >= 0) us_tecflags |= HASUNCONDRC; // if (*us_tecdrc_rules.unconlistR[i] != 0) us_tecflags |= HASUNCONDRCR; // if (us_tecdrc_rules.conlistW[i] >= 0) us_tecflags |= HASCONDRCW; // if (*us_tecdrc_rules.conlistWR[i] != 0) us_tecflags |= HASCONDRCWR; // if (us_tecdrc_rules.unconlistW[i] >= 0) us_tecflags |= HASUNCONDRCW; // if (*us_tecdrc_rules.unconlistWR[i] != 0) us_tecflags |= HASUNCONDRCWR; // if (us_tecdrc_rules.conlistM[i] >= 0) us_tecflags |= HASCONDRCM; // if (*us_tecdrc_rules.conlistMR[i] != 0) us_tecflags |= HASCONDRCMR; // if (us_tecdrc_rules.unconlistM[i] >= 0) us_tecflags |= HASUNCONDRCM; // if (*us_tecdrc_rules.unconlistMR[i] != 0) us_tecflags |= HASUNCONDRCMR; // if (us_tecdrc_rules.edgelist[i] >= 0) us_tecflags |= HASEDGEDRC; // if (*us_tecdrc_rules.edgelistR[i] != 0) us_tecflags |= HASEDGEDRCR; // } // for(i=0; i<us_tecdrc_rules.numnodes; i++) // { // if (us_tecdrc_rules.minnodesize[i*2] > 0 || // us_tecdrc_rules.minnodesize[i*2+1] > 0) us_tecflags |= HASMINNODE; // if (*us_tecdrc_rules.minnodesizeR[i] != 0) us_tecflags |= HASMINNODER; // } // // store this information on the technology object // if ((us_tecflags&(HASCONDRCW|HASUNCONDRCW)) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_wide_limitkey, us_tecdrc_rules.widelimit, // VFRACT|VDONTSAVE); // if ((us_tecflags&HASDRCMINWID) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_min_widthkey, (INTBIG)us_tecdrc_rules.minwidth, // VFRACT|VDONTSAVE|VISARRAY|(tech.layercount<<VLENGTHSH)); // if ((us_tecflags&HASDRCMINWIDR) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_min_width_rulekey, (INTBIG)us_tecdrc_rules.minwidthR, // VSTRING|VDONTSAVE|VISARRAY|(tech.layercount<<VLENGTHSH)); // if ((us_tecflags&HASCONDRC) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_connected_distanceskey, // (INTBIG)us_tecdrc_rules.conlist, VFRACT|VDONTSAVE|VISARRAY|(drcsize<<VLENGTHSH)); // if ((us_tecflags&HASCONDRCR) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_connected_distances_rulekey, // (INTBIG)us_tecdrc_rules.conlistR, VSTRING|VDONTSAVE|VISARRAY|(drcsize<<VLENGTHSH)); // if ((us_tecflags&HASUNCONDRC) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_unconnected_distanceskey, // (INTBIG)us_tecdrc_rules.unconlist, VFRACT|VDONTSAVE|VISARRAY|(drcsize<<VLENGTHSH)); // if ((us_tecflags&HASUNCONDRCR) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_unconnected_distances_rulekey, // (INTBIG)us_tecdrc_rules.unconlistR, VSTRING|VDONTSAVE|VISARRAY|(drcsize<<VLENGTHSH)); // if ((us_tecflags&HASCONDRCW) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_connected_distancesWkey, // (INTBIG)us_tecdrc_rules.conlistW, VFRACT|VDONTSAVE|VISARRAY|(drcsize<<VLENGTHSH)); // if ((us_tecflags&HASCONDRCWR) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_connected_distancesW_rulekey, // (INTBIG)us_tecdrc_rules.conlistWR, VSTRING|VDONTSAVE|VISARRAY|(drcsize<<VLENGTHSH)); // if ((us_tecflags&HASUNCONDRCW) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_unconnected_distancesWkey, // (INTBIG)us_tecdrc_rules.unconlistW, VFRACT|VDONTSAVE|VISARRAY|(drcsize<<VLENGTHSH)); // if ((us_tecflags&HASUNCONDRCWR) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_unconnected_distancesW_rulekey, // (INTBIG)us_tecdrc_rules.unconlistWR, VSTRING|VDONTSAVE|VISARRAY|(drcsize<<VLENGTHSH)); // if ((us_tecflags&HASCONDRCM) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_connected_distancesMkey, // (INTBIG)us_tecdrc_rules.conlistM, VFRACT|VDONTSAVE|VISARRAY|(drcsize<<VLENGTHSH)); // if ((us_tecflags&HASCONDRCMR) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_connected_distancesM_rulekey, // (INTBIG)us_tecdrc_rules.conlistMR, VSTRING|VDONTSAVE|VISARRAY|(drcsize<<VLENGTHSH)); // if ((us_tecflags&HASUNCONDRCM) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_unconnected_distancesMkey, // (INTBIG)us_tecdrc_rules.unconlistM, VFRACT|VDONTSAVE|VISARRAY|(drcsize<<VLENGTHSH)); // if ((us_tecflags&HASUNCONDRCMR) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_unconnected_distancesM_rulekey, // (INTBIG)us_tecdrc_rules.unconlistMR, VSTRING|VDONTSAVE|VISARRAY|(drcsize<<VLENGTHSH)); // if ((us_tecflags&HASEDGEDRC) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_edge_distanceskey, // (INTBIG)us_tecdrc_rules.edgelist, VFRACT|VDONTSAVE|VISARRAY|(drcsize<<VLENGTHSH)); // if ((us_tecflags&HASEDGEDRCR) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_edge_distances_rulekey, // (INTBIG)us_tecdrc_rules.edgelistR, VSTRING|VDONTSAVE|VISARRAY|(drcsize<<VLENGTHSH)); // if ((us_tecflags&HASMINNODE) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_min_node_sizekey, // (INTBIG)us_tecdrc_rules.minnodesize, VFRACT|VDONTSAVE|VISARRAY|((us_tecdrc_rules.numnodes*2)<<VLENGTHSH)); // if ((us_tecflags&HASMINNODER) != 0) // (void)setvalkey((INTBIG)tech, VTECHNOLOGY, dr_min_node_size_rulekey, // (INTBIG)us_tecdrc_rules.minnodesizeR, VSTRING|VDONTSAVE|VISARRAY|(us_tecdrc_rules.numnodes<<VLENGTHSH)); return lis; } /************************************* ARC ANALYSIS *************************************/ /** * Method to scan the "dependentlibcount" libraries in "dependentLibs", * and build the arc structures for it in technology "tech". Returns true on error. */ private ArcInfo [] extractArcs(Library [] dependentLibs, LayerInfo [] lList) { // count the number of arcs in the technology Cell [] arcCells = Info.findCellSequence(dependentLibs, "arc-", Info.ARCSEQUENCE_KEY); if (arcCells.length <= 0) { System.out.println("No arcs found"); return null; } ArcInfo [] allArcs = new ArcInfo[arcCells.length]; for(int i=0; i<arcCells.length; i++) { Cell np = arcCells[i]; allArcs[i] = ArcInfo.parseCell(np); // build a list of examples found in this arc List<Example> neList = Example.getExamples(np, false, error); if (neList == null) return null; if (neList.size() > 1) { error.markError(null, np, "Can only be one drawing of an arc, but more were found"); return null; } Example arcEx = neList.get(0); // sort the layers in the example Collections.sort(arcEx.samples, new SamplesByLayerOrder(lList)); // get width and polygon count information double maxWid = -1, hWid = -1; int count = 0; for(Sample ns : arcEx.samples) { double wid = Math.min(ns.node.getXSize(), ns.node.getYSize()); if (wid > maxWid) maxWid = wid; if (ns.layer == null) hWid = wid; else count++; } allArcs[i].widthOffset = maxWid - hWid; allArcs[i].maxWidth = maxWid; // error if there is no highlight box if (hWid < 0) { error.markError(null, np, "No highlight layer found"); return null; } allArcs[i].arcDetails = new ArcInfo.LayerDetails[count]; // fill the individual arc layer structures int layerIndex = 0; for(int k=0; k<2; k++) { for(Sample ns : arcEx.samples) { if (ns.layer == null) continue; // get the layer index String sampleLayer = ns.layer.getName().substring(6); LayerInfo li = null; for(int j=0; j<lList.length; j++) { if (sampleLayer.equals(lList[j].name)) { li = lList[j]; break; } } if (li == null) { error.markError(ns.node, np, "Unknown layer: " + sampleLayer); return null; } // only add transparent layers when k=0 if (k == 0) { if (li.desc.getTransparentLayer() == 0) continue; } else { if (li.desc.getTransparentLayer() != 0) continue; } allArcs[i].arcDetails[layerIndex] = new ArcInfo.LayerDetails(); allArcs[i].arcDetails[layerIndex].layer = li; // determine the style of this arc layer Poly.Type style = Poly.Type.CLOSED; if (ns.node.getProto() == Artwork.tech.filledBoxNode) style = Poly.Type.FILLED; allArcs[i].arcDetails[layerIndex].style = style; // determine the width offset of this arc layer double wid = Math.min(ns.node.getXSize(), ns.node.getYSize()); allArcs[i].arcDetails[layerIndex].width = maxWid-wid; layerIndex++; } } } return allArcs; } /************************************* NODE ANALYSIS *************************************/ /** * Method to scan the "dependentlibcount" libraries in "dependentLibs", * and build the node structures for it in technology "tech". Returns true on error. */ private NodeInfo [] extractNodes(Library [] dependentLibs, LayerInfo [] lList, ArcInfo [] aList) { Cell [] nodeCells = Info.findCellSequence(dependentLibs, "node-", Info.NODESEQUENCE_KEY); if (nodeCells.length <= 0) { System.out.println("No nodes found"); return null; } NodeInfo [] nList = new NodeInfo[nodeCells.length]; // get the nodes int nodeIndex = 0; for(int pass=0; pass<3; pass++) for(int m=0; m<nodeCells.length; m++) { // make sure this is the right type of node for this pass of the nodes Cell np = nodeCells[m]; NodeInfo nIn = NodeInfo.parseCell(np); Netlist netList = np.acquireUserNetlist(); if (netList == null) { System.out.println("Sorry, a deadlock technology generation (network information unavailable). Please try again"); return null; } // only want pins on pass 0, pure-layer nodes on pass 2 if (pass == 0 && nIn.func != PrimitiveNode.Function.PIN) continue; if (pass == 1 && (nIn.func == PrimitiveNode.Function.PIN || nIn.func == PrimitiveNode.Function.NODE)) continue; if (pass == 2 && nIn.func != PrimitiveNode.Function.NODE) continue; if (nIn.func == PrimitiveNode.Function.NODE) { if (nIn.serp) { error.markError(null, np, "Pure layer " + nIn.name + " can not be serpentine"); return null; } nIn.specialType = PrimitiveNode.POLYGONAL; } nList[nodeIndex] = nIn; nIn.name = np.getName().substring(5); // build a list of examples found in this node List<Example> neList = Example.getExamples(np, true, error); if (neList == null || neList.size() == 0) { System.out.println("Cannot analyze " + np); return null; } Example firstEx = neList.get(0); nIn.xSize = firstEx.hx - firstEx.lx; nIn.ySize = firstEx.hy - firstEx.ly; // sort the layers in the main example Collections.sort(firstEx.samples, new SamplesByLayerOrder(lList)); // associate the samples in each example if (associateExamples(neList, np)) return null; // derive primitives from the examples nIn.nodeLayers = makePrimitiveNodeLayers(neList, np, lList); if (nIn.nodeLayers == null) return null; // count the number of ports on this node int portCount = 0; for(Sample ns : firstEx.samples) { if (ns.layer == Generic.tech.portNode) portCount++; } if (portCount == 0) { error.markError(null, np, "No ports found"); return null; } // fill the port structures List<NodeInfo.PortDetails> ports = new ArrayList<NodeInfo.PortDetails>(); Map<NodeInfo.PortDetails,Sample> portSamples = new HashMap<NodeInfo.PortDetails,Sample>(); for(Sample ns : firstEx.samples) { if (ns.layer != Generic.tech.portNode) continue; // port connections NodeInfo.PortDetails nipd = new NodeInfo.PortDetails(); portSamples.put(nipd, ns); // port name nipd.name = Info.getPortName(ns.node); if (nipd.name == null) { error.markError(ns.node, np, "Port does not have a name"); return null; } for(int c=0; c<nipd.name.length(); c++) { char str = nipd.name.charAt(c); if (str <= ' ' || str >= 0177) { error.markError(ns.node, np, "Invalid port name"); return null; } } // port angle and range nipd.angle = 0; Variable varAngle = ns.node.getVar(Info.PORTANGLE_KEY); if (varAngle != null) nipd.angle = ((Integer)varAngle.getObject()).intValue(); nipd.range = 180; Variable varRange = ns.node.getVar(Info.PORTRANGE_KEY); if (varRange != null) nipd.range = ((Integer)varRange.getObject()).intValue(); // port area rule nipd.values = ns.values; ports.add(nipd); } // sort the ports by name within angle Collections.sort(ports, new PortsByAngleAndName()); // now find the poly/active ports for transistor rearranging int pol1Port = -1, pol2Port = -1, dif1Port = -1, dif2Port = -1; for(int i=0; i<ports.size(); i++) { NodeInfo.PortDetails nipd = ports.get(i); Sample ns = portSamples.get(nipd); nipd.connections = new ArcInfo[0]; Variable var = ns.node.getVar(Info.CONNECTION_KEY); if (var != null) { // convert "arc-CELL" pointers to indices CellId [] arcCells = (CellId [])var.getObject(); List<ArcInfo> validArcCells = new ArrayList<ArcInfo>(); for(int j=0; j<arcCells.length; j++) { // find arc that connects if (arcCells[j] == null) continue; Cell arcCell = EDatabase.serverDatabase().getCell(arcCells[j]); if (arcCell == null) continue; String cellName = arcCell.getName().substring(4); for(int k=0; k<aList.length; k++) { if (aList[k].name.equalsIgnoreCase(cellName)) { validArcCells.add(aList[k]); break; } } } ArcInfo [] connections = new ArcInfo[validArcCells.size()]; nipd.connections = connections; for(int j=0; j<validArcCells.size(); j++) connections[j] = validArcCells.get(j); for(int j=0; j<connections.length; j++) { // find port characteristics for possible transistors Variable meaningVar = ns.node.getVar(Info.PORTMEANING_KEY); int meaning = 0; if (meaningVar != null) meaning = ((Integer)meaningVar.getObject()).intValue(); if (connections[j].func.isPoly() || meaning == 1) { if (pol1Port < 0) { pol1Port = i; break; } else if (pol2Port < 0) { pol2Port = i; break; } } else if (connections[j].func.isDiffusion() || meaning == 2) { if (dif1Port < 0) { dif1Port = i; break; } else if (dif2Port < 0) { dif2Port = i; break; } } } } } // save the ports in an array nIn.nodePortDetails = new NodeInfo.PortDetails[ports.size()]; for(int j=0; j<ports.size(); j++) nIn.nodePortDetails[j] = ports.get(j); // on MOS transistors, make sure the first 4 ports are poly/active/poly/active if (nIn.func == PrimitiveNode.Function.TRANMOS || nIn.func == PrimitiveNode.Function.TRADMOS || nIn.func == PrimitiveNode.Function.TRAPMOS || nIn.func == PrimitiveNode.Function.TRADMES || nIn.func == PrimitiveNode.Function.TRAEMES) { if (pol1Port < 0 || pol2Port < 0 || dif1Port < 0 || dif2Port < 0) { error.markError(null, np, "Need 2 gate (poly) and 2 gated (active) ports on field-effect transistor"); return null; } // also make sure that dif1Port is positive and dif2Port is negative double x1Pos = (nIn.nodePortDetails[dif1Port].values[0].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[dif1Port].values[0].getX().getAdder() + nIn.nodePortDetails[dif1Port].values[1].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[dif1Port].values[1].getX().getAdder()) / 2; double x2Pos = (nIn.nodePortDetails[dif2Port].values[0].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[dif2Port].values[0].getX().getAdder() + nIn.nodePortDetails[dif2Port].values[1].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[dif2Port].values[1].getX().getAdder()) / 2; double y1Pos = (nIn.nodePortDetails[dif1Port].values[0].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[dif1Port].values[0].getY().getAdder() + nIn.nodePortDetails[dif1Port].values[1].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[dif1Port].values[1].getY().getAdder()) / 2; double y2Pos = (nIn.nodePortDetails[dif2Port].values[0].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[dif2Port].values[0].getY().getAdder() + nIn.nodePortDetails[dif2Port].values[1].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[dif2Port].values[1].getY().getAdder()) / 2; if (Math.abs(x1Pos-x2Pos) > Math.abs(y1Pos-y2Pos)) { if (x1Pos < x2Pos) { int k = dif1Port; dif1Port = dif2Port; dif2Port = k; } } else { if (y1Pos < y2Pos) { int k = dif1Port; dif1Port = dif2Port; dif2Port = k; } } // also make sure that pol1Port is negative and pol2Port is positive x1Pos = (nIn.nodePortDetails[pol1Port].values[0].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[pol1Port].values[0].getX().getAdder() + nIn.nodePortDetails[pol1Port].values[1].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[pol1Port].values[1].getX().getAdder()) / 2; x2Pos = (nIn.nodePortDetails[pol2Port].values[0].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[pol2Port].values[0].getX().getAdder() + nIn.nodePortDetails[pol2Port].values[1].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[pol2Port].values[1].getX().getAdder()) / 2; y1Pos = (nIn.nodePortDetails[pol1Port].values[0].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[pol1Port].values[0].getY().getAdder() + nIn.nodePortDetails[pol1Port].values[1].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[pol1Port].values[1].getY().getAdder()) / 2; y2Pos = (nIn.nodePortDetails[pol2Port].values[0].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[pol2Port].values[0].getY().getAdder() + nIn.nodePortDetails[pol2Port].values[1].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[pol2Port].values[1].getY().getAdder()) / 2; if (Math.abs(x1Pos-x2Pos) > Math.abs(y1Pos-y2Pos)) { if (x1Pos > x2Pos) { int k = pol1Port; pol1Port = pol2Port; pol2Port = k; } } else { if (y1Pos > y2Pos) { int k = pol1Port; pol1Port = pol2Port; pol2Port = k; } } // gather extra ports that go at the end List<NodeInfo.PortDetails> extras = new ArrayList<NodeInfo.PortDetails>(); for(int j=0; j<ports.size(); j++) { if (j != pol1Port && j != dif1Port && j != pol2Port && j != dif2Port) extras.add(ports.get(j)); } // rearrange the ports NodeInfo.PortDetails port0 = nIn.nodePortDetails[pol1Port]; NodeInfo.PortDetails port1 = nIn.nodePortDetails[dif1Port]; NodeInfo.PortDetails port2 = nIn.nodePortDetails[pol2Port]; NodeInfo.PortDetails port3 = nIn.nodePortDetails[dif2Port]; nIn.nodePortDetails[pol1Port=0] = port0; nIn.nodePortDetails[dif1Port=1] = port1; nIn.nodePortDetails[pol2Port=2] = port2; nIn.nodePortDetails[dif2Port=3] = port3; for(int j=0; j<extras.size(); j++) nIn.nodePortDetails[j+4] = extras.get(j); // establish port connectivity for(int i=0; i<nIn.nodePortDetails.length; i++) { NodeInfo.PortDetails nipd = nIn.nodePortDetails[i]; Sample ns = portSamples.get(nipd); nipd.netIndex = i; if (ns.node.hasConnections()) { ArcInst ai1 = ns.node.getConnections().next().getArc(); Network net1 = netList.getNetwork(ai1, 0); for(int j=0; j<i; j++) { NodeInfo.PortDetails onipd = nIn.nodePortDetails[j]; Sample oNs = portSamples.get(onipd); if (oNs.node.hasConnections()) { ArcInst ai2 = oNs.node.getConnections().next().getArc(); Network net2 = netList.getNetwork(ai2, 0); if (net1 == net2) { nipd.netIndex = j; break; } } } } } // make sure implant layers are not connected to ports for(int k=0; k<nIn.nodeLayers.length; k++) { NodeInfo.LayerDetails nld = nIn.nodeLayers[k]; if (nld.layer.fun.isSubstrate()) nld.portIndex = -1; } } if (nIn.serp) { // finish up serpentine transistors nIn.specialType = PrimitiveNode.SERPTRANS; // determine port numbers for serpentine transistors int polIndex = -1, difIndex = -1; for(int k=0; k<nIn.nodeLayers.length; k++) { NodeInfo.LayerDetails nld = nIn.nodeLayers[k]; if (nld.layer.fun.isPoly()) { polIndex = k; } else if (nld.layer.fun.isDiff()) { if (difIndex >= 0) { // figure out which layer is the basic active layer int funExtraOld = nIn.nodeLayers[difIndex].layer.funExtra; int funExtraNew = nld.layer.funExtra; if (funExtraOld == funExtraNew) continue; if (funExtraOld == 0) // if ((funExtraOld & ~(Layer.Function.PTYPE|Layer.Function.NTYPE)) == 0) continue; } difIndex = k; } } if (difIndex < 0 || polIndex < 0) { error.markError(null, np, "No diffusion and polysilicon layers in serpentine transistor"); return null; } // find width and extension from comparison to poly layer Sample polNs = nIn.nodeLayers[polIndex].ns; Rectangle2D polNodeBounds = polNs.node.getBounds(); Sample difNs = nIn.nodeLayers[difIndex].ns; Rectangle2D difNodeBounds = difNs.node.getBounds(); for(int k=0; k<nIn.nodeLayers.length; k++) { NodeInfo.LayerDetails nld = nIn.nodeLayers[k]; Sample ns = nld.ns; Rectangle2D nodeBounds = ns.node.getBounds(); if (polNodeBounds.getWidth() > polNodeBounds.getHeight()) { // horizontal layer nld.lWidth = nodeBounds.getMaxY() - (ns.parent.ly + ns.parent.hy)/2; nld.rWidth = (ns.parent.ly + ns.parent.hy)/2 - nodeBounds.getMinY(); nld.extendT = difNodeBounds.getMinX() - nodeBounds.getMinX(); } else { // vertical layer nld.lWidth = nodeBounds.getMaxX() - (ns.parent.lx + ns.parent.hx)/2; nld.rWidth = (ns.parent.lx + ns.parent.hx)/2 - nodeBounds.getMinX(); nld.extendT = difNodeBounds.getMinY() - nodeBounds.getMinY(); } nld.extendB = nld.extendT; } // add in electrical layers for diffusion NodeInfo.LayerDetails [] addedLayers = new NodeInfo.LayerDetails[nIn.nodeLayers.length+2]; for(int k=0; k<nIn.nodeLayers.length; k++) addedLayers[k] = nIn.nodeLayers[k]; NodeInfo.LayerDetails diff1 = nIn.nodeLayers[difIndex].duplicate(); NodeInfo.LayerDetails diff2 = nIn.nodeLayers[difIndex].duplicate(); addedLayers[nIn.nodeLayers.length] = diff1; addedLayers[nIn.nodeLayers.length+1] = diff2; nIn.nodeLayers = addedLayers; diff1.inLayers = diff2.inLayers = false; nIn.nodeLayers[difIndex].inElectricalLayers = false; - diff1.portIndex = dif2Port; - diff2.portIndex = dif1Port; + diff1.portIndex = dif1Port; + diff2.portIndex = dif2Port; // compute port extension factors nIn.specialValues = new double[6]; int layerCount = 0; for(Sample ns : firstEx.samples) { if (ns.values != null && ns.layer != Generic.tech.portNode && ns.layer != Generic.tech.cellCenterNode && ns.layer != null) layerCount++; } nIn.specialValues[0] = layerCount+1; if (nIn.nodePortDetails[dif1Port].values[0].getX().getAdder() > nIn.nodePortDetails[dif1Port].values[0].getY().getAdder()) { // vertical diffusion layer: determine polysilicon width nIn.specialValues[3] = (nIn.ySize * nIn.nodeLayers[polIndex].values[1].getY().getMultiplier() + nIn.nodeLayers[polIndex].values[1].getY().getAdder()) - (nIn.ySize * nIn.nodeLayers[polIndex].values[0].getY().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getY().getAdder()); // determine diffusion port rule nIn.specialValues[1] = (nIn.xSize * nIn.nodePortDetails[dif1Port].values[0].getX().getMultiplier() + nIn.nodePortDetails[dif1Port].values[0].getX().getAdder()) - (nIn.xSize * nIn.nodeLayers[difIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[difIndex].values[0].getX().getAdder()); nIn.specialValues[2] = (nIn.ySize * nIn.nodePortDetails[dif1Port].values[0].getY().getMultiplier() + nIn.nodePortDetails[dif1Port].values[0].getY().getAdder()) - (nIn.ySize * nIn.nodeLayers[polIndex].values[1].getY().getMultiplier() + nIn.nodeLayers[polIndex].values[1].getY().getAdder()); // determine polysilicon port rule nIn.specialValues[4] = (nIn.ySize * nIn.nodePortDetails[pol1Port].values[0].getY().getMultiplier() + nIn.nodePortDetails[pol1Port].values[0].getY().getAdder()) - (nIn.ySize * nIn.nodeLayers[polIndex].values[0].getY().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getY().getAdder()); nIn.specialValues[5] = (nIn.xSize * nIn.nodeLayers[difIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[difIndex].values[0].getX().getAdder()) - (nIn.xSize * nIn.nodePortDetails[pol1Port].values[1].getX().getMultiplier() + nIn.nodePortDetails[pol1Port].values[1].getX().getAdder()); // setup electrical layers for diffusion diff1.values[0].getY().setMultiplier(0); diff1.values[0].getY().setAdder(0); diff1.rWidth = 0; diff2.values[1].getY().setMultiplier(0); diff2.values[1].getY().setAdder(0); diff2.lWidth = 0; } else { // horizontal diffusion layer: determine polysilicon width nIn.specialValues[3] = (nIn.xSize * nIn.nodeLayers[polIndex].values[1].getX().getMultiplier() + nIn.nodeLayers[polIndex].values[1].getX().getAdder()) - (nIn.xSize * nIn.nodeLayers[polIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getX().getAdder()); // determine diffusion port rule nIn.specialValues[1] = (nIn.ySize * nIn.nodePortDetails[dif1Port].values[0].getY().getMultiplier() + nIn.nodePortDetails[dif1Port].values[0].getY().getAdder()) - (nIn.ySize * nIn.nodeLayers[difIndex].values[0].getY().getMultiplier() + nIn.nodeLayers[difIndex].values[0].getY().getAdder()); nIn.specialValues[2] = (nIn.xSize * nIn.nodeLayers[polIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getX().getAdder()) - (nIn.xSize * nIn.nodePortDetails[dif1Port].values[1].getX().getMultiplier() + nIn.nodePortDetails[dif1Port].values[1].getX().getAdder()); // determine polysilicon port rule nIn.specialValues[4] = (nIn.xSize * nIn.nodePortDetails[pol1Port].values[0].getX().getMultiplier() + nIn.nodePortDetails[pol1Port].values[0].getX().getAdder()) - (nIn.xSize * nIn.nodeLayers[polIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getX().getAdder()); nIn.specialValues[5] = (nIn.ySize * nIn.nodeLayers[difIndex].values[0].getY().getMultiplier() + nIn.nodeLayers[difIndex].values[0].getY().getAdder()) - (nIn.ySize * nIn.nodePortDetails[pol1Port].values[1].getY().getMultiplier() + nIn.nodePortDetails[pol1Port].values[1].getY().getAdder()); // setup electrical layers for diffusion diff1.values[0].getX().setMultiplier(0); diff1.values[0].getX().setAdder(0); diff1.rWidth = 0; diff2.values[1].getX().setMultiplier(0); diff2.values[1].getX().setAdder(0); diff2.lWidth = 0; } } // extract width offset information from highlight box double lX = 0, hX = 0, lY = 0, hY = 0; boolean found = false; for(Sample ns : firstEx.samples) { if (ns.layer != null) continue; found = true; if (ns.values != null) { boolean err = false; if (ns.values[0].getX().getMultiplier() == -0.5) // left edge offset { lX = ns.values[0].getX().getAdder(); } else if (ns.values[0].getX().getMultiplier() == 0.5) { lX = nIn.xSize + ns.values[0].getX().getAdder(); } else err = true; if (ns.values[0].getY().getMultiplier() == -0.5) // bottom edge offset { lY = ns.values[0].getY().getAdder(); } else if (ns.values[0].getY().getMultiplier() == 0.5) { lY = nIn.ySize + ns.values[0].getY().getAdder();; } else err = true; if (ns.values[1].getX().getMultiplier() == 0.5) // right edge offset { hX = -ns.values[1].getX().getAdder(); } else if (ns.values[1].getX().getMultiplier() == -0.5) { hX = nIn.xSize - ns.values[1].getX().getAdder(); } else err = true; if (ns.values[1].getY().getMultiplier() == 0.5) // top edge offset { hY = -ns.values[1].getY().getAdder(); } else if (ns.values[1].getY().getMultiplier() == -0.5) { hY = nIn.ySize - ns.values[1].getY().getAdder(); } else err = true; if (err) { error.markError(ns.node, np, "Highlighting cannot scale from center"); return null; } } else { error.markError(ns.node, np, "No rule found for highlight"); return null; } } if (!found) { error.markError(null, np, "No highlight found"); return null; } if (lX != 0 || hX != 0 || lY != 0 || hY != 0) { nList[nodeIndex].so = new SizeOffset(lX, hX, lY, hY); } // // get grab point information // for(ns = neList.firstSample; ns != NOSAMPLE; ns = ns.nextSample) // if (ns.layer == Generic.tech.cellCenterNode) break; // if (ns != NOSAMPLE) // { // us_tecnode_grab[us_tecnode_grabcount++] = nodeindex+1; // us_tecnode_grab[us_tecnode_grabcount++] = (ns.node.geom.lowx + // ns.node.geom.highx - neList.lx - neList.hx)/2 * // el_curlib.lambda[tech.techindex] / lambda; // us_tecnode_grab[us_tecnode_grabcount++] = (ns.node.geom.lowy + // ns.node.geom.highy - neList.ly - neList.hy)/2 * // el_curlib.lambda[tech.techindex] / lambda; // us_tecflags |= HASGRAB; // } // advance the fill pointer nodeIndex++; } return nList; } private NodeInfo.LayerDetails [] makePrimitiveNodeLayers(List<Example> neList, Cell np, LayerInfo [] lis) { // if there is only one example: make sample scale with edge Example firstEx = neList.get(0); if (neList.size() <= 1) { return makeNodeScaledUniformly(neList, np, lis); } // count the number of real layers in the node int count = 0; for(Sample ns : firstEx.samples) { if (ns.layer != null && ns.layer != Generic.tech.portNode) count++; } NodeInfo.LayerDetails [] nodeLayers = new NodeInfo.LayerDetails[count]; count = 0; // look at every sample "ns" in the main example "neList" for(Sample ns : firstEx.samples) { // ignore grab point specification if (ns.layer == Generic.tech.cellCenterNode) continue; AffineTransform trans = ns.node.rotateOut(); Rectangle2D nodeBounds = getBoundingBox(ns.node); // determine the layer LayerInfo giLayer = null; if (ns.layer != null && ns.layer != Generic.tech.portNode) { String desiredLayer = ns.layer.getName().substring(6); for(int i=0; i<lis.length; i++) { if (desiredLayer.equals(lis[i].name)) { giLayer = lis[i]; break; } } if (giLayer == null) { System.out.println("Cannot find layer " + desiredLayer); return null; } } // look at other examples and find samples associated with this firstEx.studySample = ns; NodeInfo.LayerDetails multiRule = null; for(int n=1; n<neList.size(); n++) { Example ne = neList.get(n); // count number of samples associated with the main sample int total = 0; for(Sample nso : ne.samples) { if (nso.assoc == ns) { ne.studySample = nso; total++; } } if (total == 0) { error.markError(ns.node, np, "Still unassociated sample (shouldn't happen)"); return null; } // if there are multiple associations, it must be a contact cut if (total > 1) { // make sure the layer is real geometry, not highlight or a port if (ns.layer == null || ns.layer == Generic.tech.portNode) { error.markError(ns.node, np, "Only contact layers may be iterated in examples"); return null; } // add the rule multiRule = getMultiCutRule(ns, neList, np); if (multiRule != null) break; } } if (multiRule != null) { multiRule.layer = giLayer; nodeLayers[count] = multiRule; count++; continue; } // associations done for this sample, now analyze them Point2D [] pointList = null; int [] pointFactor = null; Point2D [] points = null; if (ns.node.getProto() == Artwork.tech.filledPolygonNode || ns.node.getProto() == Artwork.tech.closedPolygonNode || ns.node.getProto() == Artwork.tech.openedPolygonNode || ns.node.getProto() == Artwork.tech.openedDottedPolygonNode || ns.node.getProto() == Artwork.tech.openedDashedPolygonNode || ns.node.getProto() == Artwork.tech.openedThickerPolygonNode) { points = ns.node.getTrace(); } int trueCount = 0; int minFactor = 0; if (points != null) { // make sure the arrays hold "count" points pointList = new Point2D[points.length]; pointFactor = new int[points.length]; for(int i=0; i<points.length; i++) { pointList[i] = new Point2D.Double(nodeBounds.getCenterX() + points[i].getX(), nodeBounds.getCenterY() + points[i].getY()); trans.transform(pointList[i], pointList[i]); } trueCount = points.length; } else { double [] angles = null; if (ns.node.getProto() == Artwork.tech.circleNode || ns.node.getProto() == Artwork.tech.thickCircleNode) { angles = ns.node.getArcDegrees(); if (angles[0] == 0 && angles[1] == 0) angles = null; } // if (angles == null) // { // Variable var2 = ns.node.getVar(Info.MINSIZEBOX_KEY); // if (var2 != null) minFactor = 2; // } // set sample description if (angles != null) { // handle circular arc sample pointList = new Point2D[3]; pointFactor = new int[3]; pointList[0] = new Point2D.Double(nodeBounds.getCenterX(), nodeBounds.getCenterY()); double dist = nodeBounds.getMaxX() - nodeBounds.getCenterX(); pointList[1] = new Point2D.Double(nodeBounds.getCenterX() + dist * Math.cos(angles[0]), nodeBounds.getCenterY() + dist * Math.sin(angles[0])); trans.transform(pointList[1], pointList[1]); trueCount = 3; } else if (ns.node.getProto() == Artwork.tech.circleNode || ns.node.getProto() == Artwork.tech.thickCircleNode || ns.node.getProto() == Artwork.tech.filledCircleNode) { // handle circular sample pointList = new Point2D[2+minFactor]; pointFactor = new int[2+minFactor]; pointList[0] = new Point2D.Double(nodeBounds.getCenterX(), nodeBounds.getCenterY()); pointList[1] = new Point2D.Double(nodeBounds.getMaxX(), nodeBounds.getCenterY()); trueCount = 2; } else { // rectangular sample: get the bounding box in (pointListx, pointListy) pointList = new Point2D[2+minFactor]; pointFactor = new int[2+minFactor]; pointList[0] = new Point2D.Double(nodeBounds.getMinX(), nodeBounds.getMinY()); pointList[1] = new Point2D.Double(nodeBounds.getMaxX(), nodeBounds.getMaxY()); trueCount = 2; } // if (minFactor > 1) // { // pointList[2] = new Point2D.Double(pointList[0].getX(),pointList[0].getY()); // pointList[3] = new Point2D.Double(pointList[1].getX(),pointList[1].getY()); // } } double [] pointLeftDist = new double[pointFactor.length]; double [] pointRightDist = new double[pointFactor.length]; double [] pointBottomDist = new double[pointFactor.length]; double [] pointTopDist = new double[pointFactor.length]; double [] centerXDist = new double[pointFactor.length]; double [] centerYDist = new double[pointFactor.length]; double [] pointXRatio = new double[pointFactor.length]; double [] pointYRatio = new double[pointFactor.length]; for(int i=0; i<pointFactor.length; i++) { pointLeftDist[i] = pointList[i].getX() - firstEx.lx; pointRightDist[i] = firstEx.hx - pointList[i].getX(); pointBottomDist[i] = pointList[i].getY() - firstEx.ly; pointTopDist[i] = firstEx.hy - pointList[i].getY(); centerXDist[i] = pointList[i].getX() - (firstEx.lx+firstEx.hx)/2; centerYDist[i] = pointList[i].getY() - (firstEx.ly+firstEx.hy)/2; if (firstEx.hx == firstEx.lx) pointXRatio[i] = 0; else pointXRatio[i] = (pointList[i].getX() - (firstEx.lx+firstEx.hx)/2) / (firstEx.hx-firstEx.lx); if (firstEx.hy == firstEx.ly) pointYRatio[i] = 0; else pointYRatio[i] = (pointList[i].getY() - (firstEx.ly+firstEx.hy)/2) / (firstEx.hy-firstEx.ly); if (i < trueCount) pointFactor[i] = TOEDGELEFT | TOEDGERIGHT | TOEDGETOP | TOEDGEBOT | FROMCENTX | FROMCENTY | RATIOCENTX | RATIOCENTY; else pointFactor[i] = FROMCENTX | FROMCENTY; } Point2D [] pointCoords = new Point2D[pointFactor.length]; for(int n = 1; n<neList.size(); n++) { Example ne = neList.get(n); NodeInst ni = ne.studySample.node; AffineTransform oTrans = ni.rotateOut(); Rectangle2D oNodeBounds = getBoundingBox(ni); Point2D [] oPoints = null; if (ni.getProto() == Artwork.tech.filledPolygonNode || ni.getProto() == Artwork.tech.closedPolygonNode || ni.getProto() == Artwork.tech.openedPolygonNode || ni.getProto() == Artwork.tech.openedDottedPolygonNode || ni.getProto() == Artwork.tech.openedDashedPolygonNode || ni.getProto() == Artwork.tech.openedThickerPolygonNode) { oPoints = ni.getTrace(); } int newCount = 2; if (oPoints != null) { newCount = oPoints.length; int numPoints = Math.min(trueCount, newCount); int bestOffset = 0; double bestDist = Double.MAX_VALUE; for(int offset = 0; offset < numPoints; offset++) { // determine total distance between points double dist = 0; for(int i=0; i<numPoints; i++) { double dX = points[i].getX() - oPoints[(i+offset)%numPoints].getX(); double dY = points[i].getY() - oPoints[(i+offset)%numPoints].getY(); dist += Math.hypot(dX, dY); } if (dist < bestDist) { bestDist = dist; bestOffset = offset; } } for(int i=0; i<numPoints; i++) { pointCoords[i] = new Point2D.Double(oNodeBounds.getCenterX() + oPoints[(i+bestOffset)%numPoints].getX(), oNodeBounds.getCenterY() + oPoints[(i+bestOffset)%numPoints].getY()); oTrans.transform(pointCoords[i], pointCoords[i]); } } else { double [] angles = null; if (ni.getProto() == Artwork.tech.circleNode || ni.getProto() == Artwork.tech.thickCircleNode) { angles = ni.getArcDegrees(); if (angles[0] == 0 && angles[1] == 0) angles = null; } if (angles != null) { pointCoords[0] = new Point2D.Double(oNodeBounds.getCenterX(), oNodeBounds.getCenterY()); double dist = oNodeBounds.getMaxX() - oNodeBounds.getCenterX(); pointCoords[1] = new Point2D.Double(oNodeBounds.getCenterX() + dist * Math.cos(angles[0]), oNodeBounds.getCenterY() + dist * Math.sin(angles[0])); oTrans.transform(pointCoords[1], pointCoords[1]); } else if (ni.getProto() == Artwork.tech.circleNode || ni.getProto() == Artwork.tech.thickCircleNode || ni.getProto() == Artwork.tech.filledCircleNode) { pointCoords[0] = new Point2D.Double(oNodeBounds.getCenterX(), oNodeBounds.getCenterY()); pointCoords[1] = new Point2D.Double(oNodeBounds.getMaxX(), oNodeBounds.getCenterY()); } else { pointCoords[0] = new Point2D.Double(oNodeBounds.getMinX(), oNodeBounds.getMinY()); pointCoords[1] = new Point2D.Double(oNodeBounds.getMaxX(), oNodeBounds.getMaxY()); } } if (newCount != trueCount) { error.markError(ni, np, "Main example of layer " + Info.getSampleName(ne.studySample.layer) + " has " + trueCount + " points but this has " + newCount); return null; } for(int i=0; i<trueCount; i++) { // see if edges are fixed distance from example edge if (!DBMath.areEquals(pointLeftDist[i], pointCoords[i].getX() - ne.lx)) pointFactor[i] &= ~TOEDGELEFT; if (!DBMath.areEquals(pointRightDist[i], ne.hx - pointCoords[i].getX())) pointFactor[i] &= ~TOEDGERIGHT; if (!DBMath.areEquals(pointBottomDist[i], pointCoords[i].getY() - ne.ly)) pointFactor[i] &= ~TOEDGEBOT; if (!DBMath.areEquals(pointTopDist[i], ne.hy - pointCoords[i].getY())) pointFactor[i] &= ~TOEDGETOP; // see if edges are fixed distance from example center if (!DBMath.areEquals(centerXDist[i], pointCoords[i].getX() - (ne.lx+ne.hx)/2)) pointFactor[i] &= ~FROMCENTX; if (!DBMath.areEquals(centerYDist[i], pointCoords[i].getY() - (ne.ly+ne.hy)/2)) pointFactor[i] &= ~FROMCENTY; // see if edges are fixed ratio from example center double r = 0; if (ne.hx != ne.lx) r = (pointCoords[i].getX() - (ne.lx+ne.hx)/2) / (ne.hx-ne.lx); if (!DBMath.areEquals(r, pointXRatio[i])) pointFactor[i] &= ~RATIOCENTX; if (ne.hy == ne.ly) r = 0; else r = (pointCoords[i].getY() - (ne.ly+ne.hy)/2) / (ne.hy-ne.ly); if (!DBMath.areEquals(r, pointYRatio[i])) pointFactor[i] &= ~RATIOCENTY; } // make sure port information is on the primary example if (ns.layer != Generic.tech.portNode) continue; // check port angle Variable var = ns.node.getVar(Info.PORTANGLE_KEY); Variable var2 = ni.getVar(Info.PORTANGLE_KEY); if (var == null && var2 != null) { System.out.println("Warning: moving port angle to main example of " + np); ns.node.newVar(Info.PORTANGLE_KEY, var2.getObject()); } // check port range var = ns.node.getVar(Info.PORTRANGE_KEY); var2 = ni.getVar(Info.PORTRANGE_KEY); if (var == null && var2 != null) { System.out.println("Warning: moving port range to main example of " + np); ns.node.newVar(Info.PORTRANGE_KEY, var2.getObject()); } // check connectivity var = ns.node.getVar(Info.CONNECTION_KEY); var2 = ni.getVar(Info.CONNECTION_KEY); if (var == null && var2 != null) { System.out.println("Warning: moving port connections to main example of " + np); ns.node.newVar(Info.CONNECTION_KEY, var2.getObject()); } } // error check for the highlight layer if (ns.layer == null) { for(int i=0; i<trueCount; i++) if ((pointFactor[i]&(TOEDGELEFT|TOEDGERIGHT)) == 0 || (pointFactor[i]&(TOEDGETOP|TOEDGEBOT)) == 0) { error.markError(ns.node, np, "Highlight must be constant distance from edge"); return null; } } // finally, make a rule for this sample Technology.TechPoint [] newRule = stretchPoints(pointList, pointFactor, ns, np, neList); if (newRule == null) return null; // add the rule to the global list ns.msg = Info.getValueOnNode(ns.node); if (ns.msg != null && ns.msg.length() == 0) ns.msg = null; ns.values = newRule; // stop now if a highlight or port object if (ns.layer == null || ns.layer == Generic.tech.portNode) continue; nodeLayers[count] = new NodeInfo.LayerDetails(); nodeLayers[count].layer = giLayer; nodeLayers[count].ns = ns; nodeLayers[count].style = getStyle(ns.node); nodeLayers[count].representation = Technology.NodeLayer.POINTS; nodeLayers[count].values = fixValues(np, ns.values); if (nodeLayers[count].values.length == 2) { if (nodeLayers[count].style == Poly.Type.CROSSED || nodeLayers[count].style == Poly.Type.FILLED || nodeLayers[count].style == Poly.Type.CLOSED) { nodeLayers[count].representation = Technology.NodeLayer.BOX; // if (minFactor != 0) // nodeLayers[count].representation = Technology.NodeLayer.MINBOX; } } count++; } if (count != nodeLayers.length) System.out.println("Warning: Generated only " + count + " of " + nodeLayers.length + " layers for " + np); return nodeLayers; } private NodeInfo.LayerDetails [] makeNodeScaledUniformly(List<Example> neList, Cell np, LayerInfo [] lis) { Example firstEx = neList.get(0); // count the number of real layers in the node int count = 0; for(Sample ns : firstEx.samples) { if (ns.layer != null && ns.layer != Generic.tech.portNode) count++; } NodeInfo.LayerDetails [] nodeLayers = new NodeInfo.LayerDetails[count]; count = 0; for(Sample ns : firstEx.samples) { Rectangle2D nodeBounds = getBoundingBox(ns.node); AffineTransform trans = ns.node.rotateOut(); // see if there is polygonal information Point2D [] pointList = null; int [] pointFactor = null; Point2D [] points = null; if (ns.node.getProto() == Artwork.tech.filledPolygonNode || ns.node.getProto() == Artwork.tech.closedPolygonNode || ns.node.getProto() == Artwork.tech.openedPolygonNode || ns.node.getProto() == Artwork.tech.openedDottedPolygonNode || ns.node.getProto() == Artwork.tech.openedDashedPolygonNode || ns.node.getProto() == Artwork.tech.openedThickerPolygonNode) { points = ns.node.getTrace(); } if (points != null) { // fill the array pointList = new Point2D[points.length]; pointFactor = new int[points.length]; for(int i=0; i<points.length; i++) { pointList[i] = new Point2D.Double(nodeBounds.getCenterX() + points[i].getX(), nodeBounds.getCenterY() + points[i].getY()); trans.transform(pointList[i], pointList[i]); pointFactor[i] = RATIOCENTX|RATIOCENTY; } } else { // see if it is an arc of a circle double [] angles = null; if (ns.node.getProto() == Artwork.tech.circleNode || ns.node.getProto() == Artwork.tech.thickCircleNode) { angles = ns.node.getArcDegrees(); if (angles[0] == 0 && angles[1] == 0) angles = null; } // set sample description if (angles != null) { // handle circular arc sample pointList = new Point2D[3]; pointFactor = new int[3]; pointList[0] = new Point2D.Double(nodeBounds.getCenterX(), nodeBounds.getCenterY()); double dist = nodeBounds.getMaxX() - nodeBounds.getCenterX(); pointList[1] = new Point2D.Double(nodeBounds.getCenterX() + dist * Math.cos(angles[0]), nodeBounds.getCenterY() + dist * Math.sin(angles[0])); trans.transform(pointList[1], pointList[1]); pointFactor[0] = FROMCENTX|FROMCENTY; pointFactor[1] = RATIOCENTX|RATIOCENTY; pointFactor[2] = RATIOCENTX|RATIOCENTY; } else if (ns.node.getProto() == Artwork.tech.circleNode || ns.node.getProto() == Artwork.tech.thickCircleNode || ns.node.getProto() == Artwork.tech.filledCircleNode) { // handle circular sample pointList = new Point2D[2]; pointFactor = new int[2]; pointList[0] = new Point2D.Double(nodeBounds.getCenterX(), nodeBounds.getCenterY()); pointList[1] = new Point2D.Double(nodeBounds.getMaxX(), nodeBounds.getCenterY()); pointFactor[0] = FROMCENTX|FROMCENTY; pointFactor[1] = TOEDGERIGHT|FROMCENTY; } else { // rectangular sample: get the bounding box in (px, py) pointList = new Point2D[2]; pointFactor = new int[2]; pointList[0] = new Point2D.Double(nodeBounds.getMinX(), nodeBounds.getMinY()); pointList[1] = new Point2D.Double(nodeBounds.getMaxX(), nodeBounds.getMaxY()); // preset stretch factors to go to the edges of the box pointFactor[0] = TOEDGELEFT|TOEDGEBOT; pointFactor[1] = TOEDGERIGHT|TOEDGETOP; } } // add the rule to the collection Technology.TechPoint [] newRule = stretchPoints(pointList, pointFactor, ns, np, neList); if (newRule == null) return null; ns.msg = Info.getValueOnNode(ns.node); if (ns.msg != null && ns.msg.length() == 0) ns.msg = null; ns.values = newRule; // stop now if a highlight or port object if (ns.layer == null || ns.layer == Generic.tech.portNode) continue; // determine the layer LayerInfo layer = null; String desiredLayer = ns.layer.getName().substring(6); for(int i=0; i<lis.length; i++) { if (desiredLayer.equals(lis[i].name)) { layer = lis[i]; break; } } if (layer == null) { error.markError(ns.node, np, "Unknown layer: " + desiredLayer); return null; } nodeLayers[count] = new NodeInfo.LayerDetails(); nodeLayers[count].layer = layer; nodeLayers[count].ns = ns; nodeLayers[count].style = getStyle(ns.node); nodeLayers[count].representation = Technology.NodeLayer.POINTS; nodeLayers[count].values = fixValues(np, ns.values); if (nodeLayers[count].values.length == 2) { if (nodeLayers[count].style == Poly.Type.CROSSED || nodeLayers[count].style == Poly.Type.FILLED || nodeLayers[count].style == Poly.Type.CLOSED) { nodeLayers[count].representation = Technology.NodeLayer.BOX; // Variable var2 = ns.node.getVar(Info.MINSIZEBOX_KEY); // if (var2 != null) nodeLayers[count].representation = Technology.NodeLayer.MINBOX; } } count++; } return nodeLayers; } /** * Method to build a rule for multiple contact-cut sample "ns" from the * overall example list in "neList". Returns true on error. */ private NodeInfo.LayerDetails getMultiCutRule(Sample ns, List<Example> neList, Cell np) { // find the highlight layer Example firstEx = neList.get(0); Sample hs = needHighlightLayer(firstEx, np); if (hs == null) return null; Rectangle2D highlightBounds = hs.node.getBounds(); // determine size of each cut Rectangle2D nodeBounds = ns.node.getBounds(); double multiXS = nodeBounds.getWidth(); double multiYS = nodeBounds.getHeight(); // determine indentation of cuts double multiIndent = nodeBounds.getMinX() - highlightBounds.getMinX(); double realIndentX = nodeBounds.getMinX() - firstEx.lx + multiXS/2; double realIndentY = nodeBounds.getMinY() - firstEx.ly + multiYS/2; if (highlightBounds.getMaxX() - nodeBounds.getMaxX() != multiIndent || nodeBounds.getMinY() - highlightBounds.getMinY() != multiIndent || highlightBounds.getMaxY() - nodeBounds.getMaxY() != multiIndent) { error.markError(ns.node, np, "Multiple contact cuts must be indented uniformly"); return null; } // look at every example after the first double xSep = -1, ySep = -1; for(int n=1; n<neList.size(); n++) { Example ne = neList.get(n); // count number of samples equivalent to the main sample int total = 0; for(Sample nso : ne.samples) { if (nso.assoc == ns) { // make sure size is proper Rectangle2D oNodeBounds = nso.node.getBounds(); if (multiXS != oNodeBounds.getWidth() || multiYS != oNodeBounds.getHeight()) { error.markError(nso.node, np, "Multiple contact cuts must not differ in size"); return null; } total++; } } // allocate space for these samples Sample [] nsList = new Sample[total]; // fill the list of samples int fill = 0; for(Sample nso : ne.samples) { if (nso.assoc == ns) nsList[fill++] = nso; } // analyze the samples for separation for(int i=1; i<total; i++) { // find separation Rectangle2D thisNodeBounds = nsList[i].node.getBounds(); Rectangle2D lastNodeBounds = nsList[i-1].node.getBounds(); double sepX = Math.abs(lastNodeBounds.getCenterX() - thisNodeBounds.getCenterX()); double sepY = Math.abs(lastNodeBounds.getCenterY() - thisNodeBounds.getCenterY()); // check for validity if (sepX < multiXS && sepY < multiYS) { error.markError(nsList[i].node, np, "Multiple contact cuts must not overlap"); return null; } // accumulate minimum separation if (sepX >= multiXS) { if (xSep < 0) xSep = sepX; else { if (xSep > sepX) xSep = sepX; } } if (sepY >= multiYS) { if (ySep < 0) ySep = sepY; else { if (ySep > sepY) ySep = sepY; } } } // finally ensure that all separations are multiples of "multiSep" for(int i=1; i<total; i++) { // find X separation Rectangle2D thisNodeBounds = nsList[i].node.getBounds(); Rectangle2D lastNodeBounds = nsList[i-1].node.getBounds(); double sepX = Math.abs(lastNodeBounds.getCenterX() - thisNodeBounds.getCenterX()); double sepY = Math.abs(lastNodeBounds.getCenterY() - thisNodeBounds.getCenterY()); if (sepX / xSep * xSep != sepX) { error.markError(nsList[i].node, np, "Multiple contact cut X spacing must be uniform"); return null; } // find Y separation if (sepY / ySep * ySep != sepY) { error.markError(nsList[i].node, np, "Multiple contact cut Y spacing must be uniform"); return null; } } } double multiSepX = xSep - multiXS; double multiSepY = ySep - multiYS; if (multiSepX != multiSepY) { error.markError(null, np, "Multiple contact cut X and Y spacing must be the same"); return null; } ns.values = new Technology.TechPoint[2]; ns.values[0] = new Technology.TechPoint(EdgeH.fromLeft(realIndentX), EdgeV.fromBottom(realIndentY)); ns.values[1] = new Technology.TechPoint(EdgeH.fromRight(realIndentX), EdgeV.fromTop(realIndentY)); NodeInfo.LayerDetails multiDetails = new NodeInfo.LayerDetails(); multiDetails.style = getStyle(ns.node); multiDetails.representation = Technology.NodeLayer.POINTS; if (multiDetails.style == Poly.Type.CROSSED || multiDetails.style == Poly.Type.FILLED || multiDetails.style == Poly.Type.CLOSED) { multiDetails.representation = Technology.NodeLayer.BOX; // Variable var2 = ns.node.getVar(Info.MINSIZEBOX_KEY); // if (var2 != null) multiDetails.representation = Technology.NodeLayer.MINBOX; } multiDetails.values = ns.values; multiDetails.ns = ns; multiDetails.multiCut = true; multiDetails.representation = Technology.NodeLayer.MULTICUTBOX; multiDetails.multiXS = multiXS; multiDetails.multiYS = multiYS; multiDetails.multiIndent = multiIndent; multiDetails.multiSep = multiSepX; multiDetails.multiSep2D = multiSepX; return multiDetails; } /** * Method to adjust the "count"-long array of points in "px" and "py" according * to the stretch factor bits in "factor" and return an array that describes * these points. Returns zero on error. */ private Technology.TechPoint [] stretchPoints(Point2D [] pts, int [] factor, Sample ns, Cell np, List<Example> neList) { Example firstEx = neList.get(0); Technology.TechPoint [] newRule = new Technology.TechPoint[pts.length]; for(int i=0; i<pts.length; i++) { // determine the X algorithm EdgeH horiz = null; if ((factor[i]&TOEDGELEFT) != 0) { // left edge rule horiz = EdgeH.fromLeft(pts[i].getX()-firstEx.lx); } else if ((factor[i]&TOEDGERIGHT) != 0) { // right edge rule horiz = EdgeH.fromRight(firstEx.hx-pts[i].getX()); } else if ((factor[i]&FROMCENTX) != 0) { // center rule horiz = EdgeH.fromCenter(pts[i].getX()-(firstEx.lx+firstEx.hx)/2); } else if ((factor[i]&RATIOCENTX) != 0) { // constant stretch rule if (firstEx.hx == firstEx.lx) { horiz = EdgeH.makeCenter(); } else { horiz = new EdgeH((pts[i].getX()-(firstEx.lx+firstEx.hx)/2) / (firstEx.hx-firstEx.lx), 0); } } else { error.markStretchProblem(neList, ns, np, pts[i].getX(), true); return null; } // determine the Y algorithm EdgeV vert = null; if ((factor[i]&TOEDGEBOT) != 0) { // bottom edge rule vert = EdgeV.fromBottom(pts[i].getY()-firstEx.ly); } else if ((factor[i]&TOEDGETOP) != 0) { // top edge rule vert = EdgeV.fromTop(firstEx.hy-pts[i].getY()); } else if ((factor[i]&FROMCENTY) != 0) { // center rule vert = EdgeV.fromCenter(pts[i].getY()-(firstEx.ly+firstEx.hy)/2); } else if ((factor[i]&RATIOCENTY) != 0) { // constant stretch rule if (firstEx.hy == firstEx.ly) { vert = EdgeV.makeCenter(); } else { vert = new EdgeV((pts[i].getY()-(firstEx.ly+firstEx.hy)/2) / (firstEx.hy-firstEx.ly), 0); } } else { error.markStretchProblem(neList, ns, np, pts[i].getY(), false); return null; } newRule[i] = new Technology.TechPoint(horiz, vert); } return newRule; } private Technology.TechPoint [] fixValues(NodeProto np, Technology.TechPoint [] currentList) { EdgeH h1 = null, h2 = null, h3 = null; EdgeV v1 = null, v2 = null, v3 = null; for(int p=0; p<currentList.length; p++) { EdgeH h = currentList[p].getX(); if (h.equals(h1) || h.equals(h2) || h.equals(h3)) continue; if (h1 == null) h1 = h; else if (h2 == null) h2 = h; else h3 = h; EdgeV v = currentList[p].getY(); if (v.equals(v1) || v.equals(v2) || v.equals(v3)) continue; if (v1 == null) v1 = v; else if (v2 == null) v2 = v; else v3 = v; } if (h1 != null && h2 != null && h3 == null && v1 != null && v2 != null && v3 == null) { // reduce to a box with two points currentList = new Technology.TechPoint[2]; currentList[0] = new Technology.TechPoint(h1, v1); currentList[1] = new Technology.TechPoint(h2, v2); } return currentList; } /************************************* SUPPORT *************************************/ /** * Method to associate the samples of example "neList" in cell "np" * Returns true if there is an error */ private boolean associateExamples(List<Example> neList, Cell np) { // if there is only one example, no association if (neList.size() <= 1) return false; // associate each example "ne" with the original in "neList" Example firstEx = neList.get(0); for(int n=1; n<neList.size(); n++) { Example ne = neList.get(n); // clear associations for every sample "ns" in the example "ne" for(Sample ns : ne.samples) ns.assoc = null; // associate every sample "ns" in the example "ne" for(Sample ns : ne.samples) { if (ns.assoc != null) continue; // cannot have center in other examples if (ns.layer == Generic.tech.cellCenterNode) { error.markError(ns.node, np, "Grab point should only be in main example"); return true; } // count number of similar layers in original example "neList" int total = 0; Sample nsFound = null; for(Sample nsList : firstEx.samples) { if (nsList.layer != ns.layer) continue; total++; nsFound = nsList; } // no similar layer found in the original: error if (total == 0) { error.markError(ns.node, np, "Layer " + Info.getSampleName(ns.layer) + " not found in main example"); return true; } // just one in the original: simple association if (total == 1) { ns.assoc = nsFound; continue; } // if it is a port, associate by port name if (ns.layer == Generic.tech.portNode) { String name = Info.getPortName(ns.node); if (name == null) { error.markError(ns.node, np, "Port does not have a name"); return true; } // search the original for that port boolean found = false; for(Sample nsList : firstEx.samples) { if (nsList.layer == Generic.tech.portNode) { String otherName = Info.getPortName(nsList.node); if (otherName == null) { error.markError(nsList.node, np, "Port does not have a name"); return true; } if (!name.equalsIgnoreCase(otherName)) continue; ns.assoc = nsList; found = true; break; } } if (!found) { error.markError(null, np, "Could not find port " + name + " in all examples"); return true; } continue; } // count the number of this layer in example "ne" int i = 0; for(Sample nsList : ne.samples) { if (nsList.layer == ns.layer) i++; } // if number of similar layers differs: error if (total != i) { error.markError(ns.node, np, "Layer " + Info.getSampleName(ns.layer) + " found " + total + " times in main example, " + i + " in others"); return true; } // make a list of samples on this layer in original List<Sample> mainList = new ArrayList<Sample>(); i = 0; for(Sample nsList : firstEx.samples) { if (nsList.layer == ns.layer) mainList.add(nsList); } // make a list of samples on this layer in example "ne" List<Sample> thisList = new ArrayList<Sample>(); i = 0; for(Sample nsList : ne.samples) { if (nsList.layer == ns.layer) thisList.add(nsList); } // sort each list in X/Y/shape Collections.sort(mainList, new SampleCoordAscending()); Collections.sort(thisList, new SampleCoordAscending()); // see if the lists have duplication for(i=1; i<total; i++) { Sample thisSample = thisList.get(i); Sample lastSample = thisList.get(i-1); Sample thisMainSample = mainList.get(i); Sample lastMainSample = mainList.get(i-1); if ((thisSample.xPos == lastSample.xPos && thisSample.yPos == lastSample.yPos && thisSample.node.getProto() == lastSample.node.getProto()) || (thisMainSample.xPos == lastMainSample.xPos && thisMainSample.yPos == lastMainSample.yPos && thisMainSample.node.getProto() == lastMainSample.node.getProto())) break; } if (i >= total) { // association can be made in X for(i=0; i<total; i++) { Sample thisSample = thisList.get(i); thisSample.assoc = mainList.get(i); } continue; } // don't know how to associate this sample Sample thisSample = thisList.get(i); error.markError(thisSample.node, np, "Sample " + Info.getSampleName(thisSample.layer) + " is unassociated"); return true; } // final check: make sure every sample in original example associates for(Sample nsList : firstEx.samples) { nsList.assoc = null; } for(Sample ns : ne.samples) { ns.assoc.assoc = ns; } for(Sample nsList : firstEx.samples) { if (nsList.assoc == null) { if (nsList.layer == Generic.tech.cellCenterNode) continue; error.markError(nsList.node, np, "Layer " + Info.getSampleName(nsList.layer) + " found in main example, but not others"); return true; } } } return false; } private static class SamplesByLayerOrder implements Comparator<Sample> { private LayerInfo [] lList; SamplesByLayerOrder(LayerInfo [] lList) { this.lList = lList; } public int compare(Sample s1, Sample s2) { int i1 = -1; if (s1.layer != null && s1.layer != Generic.tech.portNode) { String s1Name = s1.layer.getName().substring(6); for(int i = 0; i < lList.length; i++) if (lList[i].name.equals(s1Name)) { i1 = i; break; } } int i2 = -1; if (s2.layer != null && s2.layer != Generic.tech.portNode) { String s2Name = s2.layer.getName().substring(6); for(int i = 0; i < lList.length; i++) if (lList[i].name.equals(s2Name)) { i2 = i; break; } } return i1-i2; } } private static class PortsByAngleAndName implements Comparator<NodeInfo.PortDetails> { public int compare(NodeInfo.PortDetails s1, NodeInfo.PortDetails s2) { if (s1.angle != s2.angle) return s1.angle - s2.angle; return s1.name.compareTo(s2.name); } } private static class SampleCoordAscending implements Comparator<Sample> { public int compare(Sample s1, Sample s2) { if (s1.xPos != s2.xPos) return (int)(s1.xPos - s2.xPos); if (s1.yPos != s2.yPos) return (int)(s1.yPos - s2.yPos); return s1.node.getName().compareTo(s2.node.getName()); } } /* flags about the edge positions in the examples */ private static final int TOEDGELEFT = 01; /* constant to left edge */ private static final int TOEDGERIGHT = 02; /* constant to right edge */ private static final int TOEDGETOP = 04; /* constant to top edge */ private static final int TOEDGEBOT = 010; /* constant to bottom edge */ private static final int FROMCENTX = 020; /* constant in X to center */ private static final int FROMCENTY = 040; /* constant in Y to center */ private static final int RATIOCENTX = 0100; /* fixed ratio from X center to edge */ private static final int RATIOCENTY = 0200; /* fixed ratio from Y center to edge */ private Poly.Type getStyle(NodeInst ni) { // layer style Poly.Type sty = null; if (ni.getProto() == Artwork.tech.filledBoxNode) sty = Poly.Type.FILLED; else if (ni.getProto() == Artwork.tech.boxNode) sty = Poly.Type.CLOSED; else if (ni.getProto() == Artwork.tech.crossedBoxNode) sty = Poly.Type.CROSSED; else if (ni.getProto() == Artwork.tech.filledPolygonNode) sty = Poly.Type.FILLED; else if (ni.getProto() == Artwork.tech.closedPolygonNode) sty = Poly.Type.CLOSED; else if (ni.getProto() == Artwork.tech.openedPolygonNode) sty = Poly.Type.OPENED; else if (ni.getProto() == Artwork.tech.openedDottedPolygonNode) sty = Poly.Type.OPENEDT1; else if (ni.getProto() == Artwork.tech.openedDashedPolygonNode) sty = Poly.Type.OPENEDT2; else if (ni.getProto() == Artwork.tech.openedThickerPolygonNode) sty = Poly.Type.OPENEDT3; else if (ni.getProto() == Artwork.tech.filledCircleNode) sty = Poly.Type.DISC; else if (ni.getProto() == Artwork.tech.circleNode) { sty = Poly.Type.CIRCLE; double [] angles = ni.getArcDegrees(); if (angles[0] != 0 || angles[1] != 0) sty = Poly.Type.CIRCLEARC; } else if (ni.getProto() == Artwork.tech.thickCircleNode) { sty = Poly.Type.THICKCIRCLE; double [] angles = ni.getArcDegrees(); if (angles[0] != 0 || angles[1] != 0) sty = Poly.Type.THICKCIRCLEARC; } else if (ni.getProto() == Generic.tech.invisiblePinNode) { Variable var = ni.getVar(Artwork.ART_MESSAGE); if (var != null) { TextDescriptor.Position pos = var.getTextDescriptor().getPos(); if (pos == TextDescriptor.Position.BOXED) sty = Poly.Type.TEXTBOX; else if (pos == TextDescriptor.Position.CENT) sty = Poly.Type.TEXTCENT; else if (pos == TextDescriptor.Position.UP) sty = Poly.Type.TEXTBOT; else if (pos == TextDescriptor.Position.DOWN) sty = Poly.Type.TEXTTOP; else if (pos == TextDescriptor.Position.LEFT) sty = Poly.Type.TEXTRIGHT; else if (pos == TextDescriptor.Position.RIGHT) sty = Poly.Type.TEXTLEFT; else if (pos == TextDescriptor.Position.UPLEFT) sty = Poly.Type.TEXTBOTRIGHT; else if (pos == TextDescriptor.Position.UPRIGHT) sty = Poly.Type.TEXTBOTLEFT; else if (pos == TextDescriptor.Position.DOWNLEFT) sty = Poly.Type.TEXTTOPRIGHT; else if (pos == TextDescriptor.Position.DOWNRIGHT) sty = Poly.Type.TEXTTOPLEFT; } } if (sty == null) { System.out.println("Warning: Cannot determine style to use for " + ni.describe(false) + " node in " + ni.getParent() + ", assuming FILLED"); sty = Poly.Type.FILLED; } return sty; } /** * Method to return the actual bounding box of layer node "ni" in the * reference variables "lx", "hx", "ly", and "hy" */ private Rectangle2D getBoundingBox(NodeInst ni) { Rectangle2D bounds = ni.getBounds(); if (ni.getProto() == Generic.tech.portNode) { double portShrink = 2; bounds.setRect(bounds.getMinX() + portShrink, bounds.getMinY() + portShrink, bounds.getWidth()-portShrink*2, bounds.getHeight()-portShrink*2); } bounds.setRect(DBMath.round(bounds.getMinX()), DBMath.round(bounds.getMinY()), DBMath.round(bounds.getWidth()), DBMath.round(bounds.getHeight())); return bounds; } private Sample needHighlightLayer(Example neList, Cell np) { // find the highlight layer for(Sample ns : neList.samples) { if (ns.layer == null) return ns; } error.markError(null, np, "No highlight layer on contact"); return null; } /************************************* WRITE TECHNOLOGY AS "JAVA" CODE *************************************/ // private static int NUM_FRACTIONS = 0; // was 3 // // /** // * Dump technology information to Java // * @param fileName name of file to write // * @param newTechName new technology name // * @param gi general technology information // * @param lList information about layers // * @param nList information about primitive nodes // * @param aList information about primitive arcs. // */ // private void dumpToJava(String fileName, String newTechName, GeneralInfo gi, LayerInfo[] lList, NodeInfo[] nList, ArcInfo[] aList) { // try { // PrintStream buffWriter = new PrintStream(new FileOutputStream(fileName)); // dumpToJava(buffWriter, newTechName, gi, lList, nList, aList); // buffWriter.close(); // System.out.println("Wrote " + fileName); // } catch (IOException e) { // System.out.println("Error creating " + fileName); // } // } // // /** // * write the layers, arcs, and nodes // */ // private void dumpToJava(PrintStream buffWriter, String newTechName, GeneralInfo gi, LayerInfo[] lList, NodeInfo[] nList, ArcInfo[] aList) { // // write the layers, arcs, and nodes // dumpLayersToJava(buffWriter, newTechName, lList, gi); // dumpArcsToJava(buffWriter, newTechName, aList, gi); // dumpNodesToJava(buffWriter, newTechName, nList, lList, gi); // dumpPaletteToJava(buffWriter, gi.menuPalette); // dumpFoundryToJava(buffWriter, gi, lList); // buffWriter.println("\t};"); // // // write method to reset rules // if (gi.conDist != null || gi.unConDist != null) // { // String conword = gi.conDist != null ? "conDist" : "null"; // String unconword = gi.unConDist != null ? "unConDist" : "null"; // buffWriter.println("\t/**"); // buffWriter.println("\t * Method to return the \"factory \"design rules for this Technology."); // buffWriter.println("\t * @return the design rules for this Technology."); // buffWriter.println("\t * @param resizeNodes"); // buffWriter.println("\t */"); // buffWriter.println("\tpublic DRCRules getFactoryDesignRules(boolean resizeNodes)"); // buffWriter.println("\t{"); // buffWriter.println("\t\treturn MOSRules.makeSimpleRules(this, " + conword + ", " + unconword + ");"); // buffWriter.println("\t}"); // } // buffWriter.println("}"); // } // // /** // * Method to dump the layer information in technology "tech" to the stream in // * "f". // */ // private void dumpLayersToJava(PrintStream buffWriter, String techName, LayerInfo [] lList, GeneralInfo gi) // { // // write header // buffWriter.println("// BE SURE TO INCLUDE THIS TECHNOLOGY IN Technology.initAllTechnologies()"); // buffWriter.println(); // buffWriter.println("/* -*- tab-width: 4 -*-"); // buffWriter.println(" *"); // buffWriter.println(" * Electric(tm) VLSI Design System"); // buffWriter.println(" *"); // buffWriter.println(" * File: " + techName + ".java"); // buffWriter.println(" * " + techName + " technology description"); // buffWriter.println(" * Generated automatically from a library"); // buffWriter.println(" *"); // Calendar cal = Calendar.getInstance(); // cal.setTime(new Date()); // buffWriter.println(" * Copyright (c) " + cal.get(Calendar.YEAR) + " Sun Microsystems and Static Free Software"); // buffWriter.println(" *"); // buffWriter.println(" * Electric(tm) is free software; you can redistribute it and/or modify"); // buffWriter.println(" * it under the terms of the GNU General Public License as published by"); // buffWriter.println(" * the Free Software Foundation; either version 3 of the License, or"); // buffWriter.println(" * (at your option) any later version."); // buffWriter.println(" *"); // buffWriter.println(" * Electric(tm) is distributed in the hope that it will be useful,"); // buffWriter.println(" * but WITHOUT ANY WARRANTY; without even the implied warranty of"); // buffWriter.println(" * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the"); // buffWriter.println(" * GNU General Public License for more details."); // buffWriter.println(" *"); // buffWriter.println(" * You should have received a copy of the GNU General Public License"); // buffWriter.println(" * along with Electric(tm); see the file COPYING. If not, write to"); // buffWriter.println(" * the Free Software Foundation, Inc., 59 Temple Place, Suite 330,"); // buffWriter.println(" * Boston, Mass 02111-1307, USA."); // buffWriter.println(" */"); // buffWriter.println("package com.sun.electric.technology.technologies;"); // buffWriter.println(); // // // write imports // buffWriter.println("import com.sun.electric.database.geometry.EGraphics;"); // buffWriter.println("import com.sun.electric.database.geometry.Poly;"); // buffWriter.println("import com.sun.electric.database.prototype.PortCharacteristic;"); // buffWriter.println("import com.sun.electric.technology.ArcProto;"); // buffWriter.println("import com.sun.electric.technology.DRCRules;"); // buffWriter.println("import com.sun.electric.technology.EdgeH;"); // buffWriter.println("import com.sun.electric.technology.EdgeV;"); // buffWriter.println("import com.sun.electric.technology.Foundry;"); // buffWriter.println("import com.sun.electric.technology.Layer;"); // buffWriter.println("import com.sun.electric.technology.PrimitiveNode;"); // buffWriter.println("import com.sun.electric.technology.PrimitivePort;"); // buffWriter.println("import com.sun.electric.technology.SizeOffset;"); // buffWriter.println("import com.sun.electric.technology.Technology;"); // buffWriter.println("import com.sun.electric.technology.technologies.utils.MOSRules;"); // buffWriter.println("import com.sun.electric.tool.erc.ERC;"); // buffWriter.println(); // buffWriter.println("import java.awt.Color;"); // buffWriter.println(); // // buffWriter.println("/**"); // buffWriter.println(" * This is the " + gi.description + " Technology."); // buffWriter.println(" */"); // buffWriter.println("public class " + techName + " extends Technology"); // buffWriter.println("{"); // buffWriter.println("\t/** the " + gi.description + " Technology object. */ public static final " + // techName + " tech = new " + techName + "();"); // buffWriter.println(); // if (gi.conDist != null || gi.unConDist != null) { // buffWriter.println("\tprivate static final double XX = -1;"); // buffWriter.println("\tprivate double [] conDist, unConDist;"); // buffWriter.println(); // } // // buffWriter.println(" // -------------------- private and protected methods ------------------------"); // buffWriter.println("\tprivate " + techName + "()"); // buffWriter.println("\t{"); // buffWriter.println("\t\tsuper(\"" + techName + "\", Foundry.Type." + gi.defaultFoundry + ", " + gi.defaultNumMetals + ");"); // buffWriter.println("\t\tsetTechShortName(\"" + gi.shortName + "\");"); // buffWriter.println("\t\tsetTechDesc(\"" + gi.description + "\");"); // buffWriter.println("\t\tsetFactoryScale(" + TextUtils.formatDouble(gi.scale, NUM_FRACTIONS) + ", true); // in nanometers: really " + // (gi.scale / 1000) + " microns"); // buffWriter.println("\t\tsetFactoryResolution(" + gi.resolution + ");"); // if (gi.nonElectrical) // buffWriter.println("\t\tsetNonElectrical();"); // buffWriter.println("\t\tsetNoNegatedArcs();"); // buffWriter.println("\t\tsetStaticTechnology();"); // // if (gi.transparentColors != null && gi.transparentColors.length > 0) // { // buffWriter.println("\t\tsetFactoryTransparentLayers(new Color []"); // buffWriter.println("\t\t{"); // for(int i=0; i<gi.transparentColors.length; i++) // { // Color col = gi.transparentColors[i]; // buffWriter.print("\t\t\tnew Color(" + col.getRed() + "," + col.getGreen() + "," + col.getBlue() + ")"); // if (i+1 < gi.transparentColors.length) buffWriter.print(","); // buffWriter.println(); // } // buffWriter.println("\t\t});"); // } // buffWriter.println(); // // // write the layer declarations // buffWriter.println("\t\t//**************************************** LAYERS ****************************************"); // for(int i=0; i<lList.length; i++) // { // lList[i].javaName = makeJavaName(lList[i].name); // buffWriter.println("\t\t/** " + lList[i].name + " layer */"); // buffWriter.println("\t\tLayer " + lList[i].javaName + "_lay = Layer.newInstance(this, \"" + lList[i].name + "\","); // EGraphics desc = lList[i].desc; // buffWriter.print("\t\t\tnew EGraphics("); // if (desc.isPatternedOnDisplay()) buffWriter.print("true"); else // buffWriter.print("false"); // buffWriter.print(", "); // // if (desc.isPatternedOnPrinter()) buffWriter.print("true"); else // buffWriter.print("false"); // buffWriter.print(", "); // // EGraphics.Outline o = desc.getOutlined(); // if (o == EGraphics.Outline.NOPAT) buffWriter.print("null"); else // buffWriter.print("EGraphics.Outline." + o.getConstName()); // buffWriter.print(", "); // // String transparent = "0"; // if (desc.getTransparentLayer() > 0) // transparent = "EGraphics.TRANSPARENT_" + desc.getTransparentLayer(); // int red = desc.getColor().getRed(); // int green = desc.getColor().getGreen(); // int blue = desc.getColor().getBlue(); // if (red < 0 || red > 255) red = 0; // if (green < 0 || green > 255) green = 0; // if (blue < 0 || blue > 255) blue = 0; // buffWriter.println(transparent + ", " + red + "," + green + "," + blue + ", " + desc.getOpacity() + ", " + desc.getForeground() + ","); // // boolean hasPattern = false; // int [] pattern = desc.getPattern(); // for(int j=0; j<16; j++) if (pattern[j] != 0) hasPattern = true; // if (hasPattern) // { // for(int j=0; j<16; j++) // { // buffWriter.print("\t\t\t"); // if (j == 0) buffWriter.print("new int[] { "); else // buffWriter.print("\t\t\t"); // String hexValue = Integer.toHexString(pattern[j] & 0xFFFF); // while (hexValue.length() < 4) hexValue = "0" + hexValue; // buffWriter.print("0x" + hexValue); // if (j == 15) buffWriter.print("}));"); else // buffWriter.print(", "); // // buffWriter.print("// "); // for(int k=0; k<16; k++) // if ((pattern[j] & (1 << (15-k))) != 0) // buffWriter.print("X"); else buffWriter.print(" "); // buffWriter.println(); // } // buffWriter.println(); // } else // { // buffWriter.println("\t\t\tnew int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}));"); // } // } // // // write the layer functions // buffWriter.println(); // buffWriter.println("\t\t// The layer functions"); // for(int i=0; i<lList.length; i++) // { // Layer.Function fun = lList[i].fun; // int funExtra = lList[i].funExtra; // String infstr = lList[i].javaName + "_lay.setFunction(Layer.Function."; // infstr += fun.getConstantName(); // boolean extraFunction = false; // int [] extras = Layer.Function.getFunctionExtras(); // for(int j=0; j<extras.length; j++) // { // if ((funExtra&extras[j]) != 0) // { // if (extraFunction) infstr += "|"; else // infstr += ", "; // infstr += "Layer.Function."; // infstr += Layer.Function.getExtraConstantName(extras[j]); // extraFunction = true; // } // } // if (lList[i].pseudo) { // if (extraFunction) infstr += "|"; else // infstr += ", "; // infstr += "Layer.Function.PSEUDO"; // } // infstr += ");"; // buffWriter.println("\t\t" + infstr + "\t\t// " + lList[i].name); // } // // // write the CIF layer names // for(int j=0; j<lList.length; j++) // { // if (lList[j].cif.length() > 0) // { // buffWriter.println("\n\t\t// The CIF names"); // for(int i=0; i<lList.length; i++) { // if (lList[i].pseudo) continue; // buffWriter.println("\t\t" + lList[i].javaName + "_lay.setFactoryCIFLayer(\"" + lList[i].cif + // "\");\t\t// " + lList[i].name); // } // break; // } // } // // // write the DXF layer names // for(int j=0; j<lList.length; j++) // { // if (lList[j].dxf != null && lList[j].dxf.length() > 0) // { // buffWriter.println("\n\t\t// The DXF names"); // for(int i=0; i<lList.length; i++) { // if (lList[i].pseudo) continue; // buffWriter.println("\t\t" + lList[i].javaName + "_lay.setFactoryDXFLayer(\"" + lList[i].dxf + // "\");\t\t// " + lList[i].name); // } // break; // } // } // // // write the Skill layer names // for(int j=0; j<lList.length; j++) // { // if (lList[j].skill != null && lList[j].skill.length() > 0) // { // buffWriter.println("\n\t\t// The Skill names"); // for(int i=0; i<lList.length; i++) { // if (lList[i].pseudo) continue; // buffWriter.println("\t\t" + lList[i].javaName + "_lay.setFactorySkillLayer(\"" + lList[i].skill + // "\");\t\t// " + lList[i].name); // } // break; // } // } // // // write the 3D information // for(int j=0; j<lList.length; j++) // { // if (lList[j].thick3d != 0 || lList[j].height3d != 0) // { // buffWriter.println("\n\t\t// The layer height"); // for(int i=0; i<lList.length; i++) { // if (lList[i].pseudo) continue; // buffWriter.println("\t\t" + lList[i].javaName + "_lay.setFactory3DInfo(" + // TextUtils.formatDouble(lList[i].thick3d, NUM_FRACTIONS) + ", " + TextUtils.formatDouble(lList[i].height3d, NUM_FRACTIONS) + // ");\t\t// " + lList[i].name); // } // break; // } // } // // // write the SPICE information // for(int j=0; j<lList.length; j++) // { // if (lList[j].spiRes != 0 || lList[j].spiCap != 0 || lList[j].spiECap != 0) // { // buffWriter.println("\n\t\t// The SPICE information"); // for(int i=0; i<lList.length; i++) // buffWriter.println("\t\t" + lList[i].javaName + "_lay.setFactoryParasitics(" + // TextUtils.formatDouble(lList[i].spiRes, NUM_FRACTIONS) + ", " + // TextUtils.formatDouble(lList[i].spiCap, NUM_FRACTIONS) + ", " + // TextUtils.formatDouble(lList[i].spiECap, NUM_FRACTIONS) + ");\t\t// " + lList[i].name); // break; // } // } // buffWriter.println("\t\tsetFactoryParasitics(" + gi.minRes + ", " + gi.minCap + ");"); // // dumpSpiceHeader(buffWriter, 1, gi.spiceLevel1Header); // dumpSpiceHeader(buffWriter, 2, gi.spiceLevel2Header); // dumpSpiceHeader(buffWriter, 3, gi.spiceLevel3Header); // // // write design rules // if (gi.conDist != null || gi.unConDist != null) { // buffWriter.println("\n\t\t//******************** DESIGN RULES ********************"); // // if (gi.conDist != null) { // buffWriter.println("\n\t\tconDist = new double[] {"); // dumpJavaDrcTab(buffWriter, gi.conDist, lList); // } // if (gi.unConDist != null) { // buffWriter.println("\n\t\tunConDist = new double[] {"); // dumpJavaDrcTab(buffWriter, gi.unConDist, lList); // } // } // } // // private void dumpJavaDrcTab(PrintStream buffWriter, double[] distances, LayerInfo[] lList/*), void *distances, TECHNOLOGY *tech, BOOLEAN isstring*/) // { //// REGISTER INTBIG i, j; //// REGISTER INTBIG amt, *amtlist; //// CHAR shortname[7], *msg, **distlist; //// // for(int i=0; i<6; i++) // { // buffWriter.print("\t\t\t// "); // for(int j=0; j<lList.length; j++) // { // if (lList[j].name.length() <= i) buffWriter.print(" "); else // buffWriter.print(lList[j].name.charAt(i)); // buffWriter.print(" "); // } // buffWriter.println(); // } //// if (isstring) distlist = (CHAR **)distances; else //// amtlist = (INTBIG *)distances; // int ruleNum = 0; // for(int j=0; j<lList.length; j++) // { // String shortName = lList[j].name; // if (shortName.length() > 6) // shortName = shortName.substring(0, 6); // while (shortName.length() < 6) // shortName += ' '; // buffWriter.print("\t\t\t/* " + shortName + " */ "); // for(int i=0; i<j; i++) buffWriter.print(" "); // for(int i=j; i<lList.length; i++) // { //// if (isstring) //// { //// msg = *distlist++; //// buffWriter.println("x_(\"%s\")"), msg); //// } else //// { // double amt = distances[ruleNum++]; // if (amt < 0) buffWriter.print("XX"); else // { // String amtStr = Double.toString(amt); // if (amtStr.endsWith(".0")) // amtStr = amtStr.substring(0, amtStr.length() - 2); // while (amtStr.length() < 2) // amtStr = ' ' + amtStr; // buffWriter.print(amtStr)/*, (float)amt/WHOLE)*/; //// } // } // if (j != lList.length-1 || i != lList.length-1) // buffWriter.print(","); // } // buffWriter.println(); // } // buffWriter.println("\t\t};"); // } // // private void dumpSpiceHeader(PrintStream buffWriter, int level, String[] headerLines) { // if (headerLines == null) return; // buffWriter.println("\t\tString [] headerLevel" + level + " ="); // buffWriter.println("\t\t{"); // for (int i = 0; i < headerLines.length; i++) { // buffWriter.print("\t\t\t\"" + headerLines[i] + "\""); // if (i < headerLines.length - 1) // buffWriter.print(','); // buffWriter.println(); // } // buffWriter.println("\t\t};"); // buffWriter.println("\t\tsetSpiceHeaderLevel" + level + "(headerLevel" + level + ");"); // } // // /** // * Method to dump the arc information in technology "tech" to the stream in // * "f". // */ // private void dumpArcsToJava(PrintStream buffWriter, String techName, ArcInfo [] aList, GeneralInfo gi) // { // // print the header // buffWriter.println(); // buffWriter.println("\t\t//******************** ARCS ********************"); // // // now write the arcs // for(int i=0; i<aList.length; i++) // { // ArcInfo aIn = aList[i]; // aIn.javaName = makeJavaName(aIn.name); // buffWriter.println("\n\t\t/** " + aIn.name + " arc */"); // buffWriter.println("\t\tArcProto " + aIn.javaName + "_arc = newArcProto(\"" + aIn.name + // "\", " + TextUtils.formatDouble(aIn.widthOffset, NUM_FRACTIONS) + // ", " + TextUtils.formatDouble(aIn.maxWidth, NUM_FRACTIONS) + // ", ArcProto.Function." + aIn.func.getConstantName() + ","); // for(int k=0; k<aIn.arcDetails.length; k++) // { // ArcInfo.LayerDetails al = aList[i].arcDetails[k]; // buffWriter.print("\t\t\tnew Technology.ArcLayer(" + al.layer.javaName + "_lay, "); // buffWriter.print(TextUtils.formatDouble(al.width, NUM_FRACTIONS) + ","); // buffWriter.print(" Poly.Type." + al.style.name() + ")"); // if (k+1 < aList[i].arcDetails.length) buffWriter.print(","); // buffWriter.println(); // } // buffWriter.println("\t\t);"); // if (aIn.wipes) // buffWriter.println("\t\t" + aIn.javaName + "_arc.setWipable();"); // if (aIn.curvable) // buffWriter.println("\t\t" + aIn.javaName + "_arc.setCurvable();"); // if (aIn.special) // buffWriter.println("\t\t" + aIn.javaName + "_arc.setSpecialArc();"); // if (aIn.notUsed) // buffWriter.println("\t\t" + aIn.javaName + "_arc.setNotUsed(true);"); // if (aIn.skipSizeInPalette) // buffWriter.println("\t\t" + aIn.javaName + "_arc.setSkipSizeInPalette();"); // buffWriter.println("\t\t" + aIn.javaName + "_arc.setFactoryFixedAngle(" + aIn.fixAng + ");"); // if (!aIn.slidable) // buffWriter.println("\t\t" + aIn.javaName + "_arc.setFactorySlidable(" + aIn.slidable + ");"); // buffWriter.println("\t\t" + aIn.javaName + "_arc.setFactoryExtended(" + !aIn.noExtend + ");"); // buffWriter.println("\t\t" + aIn.javaName + "_arc.setFactoryAngleIncrement(" + aIn.angInc + ");"); // buffWriter.println("\t\tERC.getERCTool().setAntennaRatio(" + aIn.javaName + "_arc, " + // TextUtils.formatDouble(aIn.antennaRatio, NUM_FRACTIONS) + ");"); // } // } // // /** // * Method to make an abbreviation for a string. // * @param pt the string to abbreviate. // * @param upper true to make it an upper-case abbreviation. // * @return the abbreviation for the string. // */ // private String makeabbrev(String pt, boolean upper) // { // // generate an abbreviated name for this prototype // StringBuffer infstr = new StringBuffer(); // for(int i=0; i<pt.length(); ) // { // char chr = pt.charAt(i); // if (Character.isLetterOrDigit(chr)) // { // if (i == 0 && Character.isDigit(chr)) // infstr.append("_"); // if (upper) infstr.append(Character.toUpperCase(chr)); else // infstr.append(Character.toLowerCase(chr)); // while (Character.isLetterOrDigit(chr)) // { // i++; // if (i >= pt.length()) break; // chr = pt.charAt(i); // } // } // while (!Character.isLetterOrDigit(chr)) // { // i++; // if (i >= pt.length()) break; // chr = pt.charAt(i); // } // } // return infstr.toString(); // } // // /** // * Method to dump the node information in technology "tech" to the stream in // * "f". // */ // private void dumpNodesToJava(PrintStream buffWriter, String techName, NodeInfo [] nList, // LayerInfo [] lList, GeneralInfo gi) // { // // make abbreviations for each node // HashSet<String> abbrevs = new HashSet<String>(); // for(int i=0; i<nList.length; i++) // { // String ab = makeabbrev(nList[i].name, false); // // // loop until the name is unique // for(;;) // { // // see if a previously assigned abbreviation is the same // if (!abbrevs.contains(ab)) break; // // // name conflicts: change it // int l = ab.length() - 1; // char last = ab.charAt(l); // if (last >= '0' && last <= '8') // { // ab = ab.substring(0, l) + (char)(last+1); // } else // { // ab += "0"; // } // } // abbrevs.add(ab); // nList[i].abbrev = ab; // } // buffWriter.println(); // // // print node information // buffWriter.println("\t\t//******************** NODES ********************"); // for(int i=0; i<nList.length; i++) // { // NodeInfo nIn = nList[i]; // // header comment // String ab = nIn.abbrev; // buffWriter.println(); // buffWriter.println("\t\t/** " + nIn.name + " */"); // // buffWriter.print("\t\tPrimitiveNode " + ab + "_node = PrimitiveNode.newInstance(\"" + // nIn.name + "\", this, " + TextUtils.formatDouble(nIn.xSize, NUM_FRACTIONS) + ", " + // TextUtils.formatDouble(nList[i].ySize, NUM_FRACTIONS) + ", "); // if (nIn.so == null) buffWriter.println("null,"); else // { // buffWriter.println("new SizeOffset(" + TextUtils.formatDouble(nIn.so.getLowXOffset(), NUM_FRACTIONS) + ", " + // TextUtils.formatDouble(nIn.so.getHighXOffset(), NUM_FRACTIONS) + ", " + // TextUtils.formatDouble(nIn.so.getLowYOffset(), NUM_FRACTIONS) + ", " + // TextUtils.formatDouble(nIn.so.getHighYOffset(), NUM_FRACTIONS) + "),"); // } // // // print layers // dumpNodeLayersToJava(buffWriter, nIn.nodeLayers, nIn.specialType == PrimitiveNode.SERPTRANS, false); // for(int k=0; k<nIn.nodeLayers.length; k++) { // NodeInfo.LayerDetails nld = nIn.nodeLayers[k]; // if (nld.message != null) // buffWriter.println("\t\t" + ab + "_node.getLayers()[" + k + "].setMessage(\"" + nld.message + "\");"); // TextDescriptor td = nld.descriptor; // if (td != null) { // buffWriter.println("\t\t" + ab + "_node.getLayers()[" + k + "].setDescriptor(TextDescriptor.newTextDescriptor("); // buffWriter.println("\t\t\tnew MutableTextDescriptor(" + td.lowLevelGet() + ", " + td.getColorIndex() + ", " + td.isDisplay() + // ", TextDescriptor.Code." + td.getCode().name() + ")));"); // } // } // // // print ports // buffWriter.println("\t\t" + ab + "_node.addPrimitivePorts(new PrimitivePort[]"); // buffWriter.println("\t\t\t{"); // int numPorts = nIn.nodePortDetails.length; // for(int j=0; j<numPorts; j++) // { // NodeInfo.PortDetails portDetail = nIn.nodePortDetails[j]; // buffWriter.print("\t\t\t\tPrimitivePort.newInstance(this, " + ab + "_node, new ArcProto [] {"); // ArcInfo [] conns = portDetail.connections; // for(int l=0; l<conns.length; l++) // { // buffWriter.print(conns[l].javaName + "_arc"); // if (l+1 < conns.length) buffWriter.print(", "); // } // PortCharacteristic characteristic = portDetail.characterisitic; // if (characteristic == null) // characteristic = PortCharacteristic.UNKNOWN; // buffWriter.println("}, \"" + portDetail.name + "\", " + portDetail.angle + "," + // portDetail.range + ", " + portDetail.netIndex + ", PortCharacteristic." + characteristic.name() + ","); // buffWriter.print("\t\t\t\t\t" + getEdgeLabel(portDetail.values[0], false) + ", " + // getEdgeLabel(portDetail.values[0], true) + ", " + // getEdgeLabel(portDetail.values[1], false) + ", " + // getEdgeLabel(portDetail.values[1], true) + ")"); // // if (j+1 < numPorts) buffWriter.print(","); // buffWriter.println(); // } // buffWriter.println("\t\t\t});"); // boolean needElectricalLayers = false; // for (NodeInfo.LayerDetails nld: nIn.nodeLayers) { // if (!(nld.inLayers && nld.inElectricalLayers)) // needElectricalLayers = true; // } // if (needElectricalLayers) { // buffWriter.println("\t\t" + ab + "_node.setElectricalLayers("); // dumpNodeLayersToJava(buffWriter, nIn.nodeLayers, nIn.specialType == PrimitiveNode.SERPTRANS, true); // } // for (int j = 0; j < numPorts; j++) { // NodeInfo.PortDetails portDetail = nIn.nodePortDetails[j]; // if (portDetail.isolated) // buffWriter.println("\t\t" + ab + "_node.getPortId(" + j + ").setIsolated();"); // if (portDetail.negatable) // buffWriter.println("\t\t" + ab + "_node.getPortId(" + j + ").setNegatable(true);"); // } // // // print the node information // PrimitiveNode.Function fun = nIn.func; // buffWriter.println("\t\t" + ab + "_node.setFunction(PrimitiveNode.Function." + fun.name() + ");"); // // if (nIn.wipes) buffWriter.println("\t\t" + ab + "_node.setWipeOn1or2();"); // if (nIn.square) buffWriter.println("\t\t" + ab + "_node.setSquare();"); // if (nIn.canBeZeroSize) buffWriter.println("\t\t" + ab + "_node.setCanBeZeroSize();"); // if (nIn.lockable) buffWriter.println("\t\t" + ab + "_node.setLockedPrim();"); // if (nIn.edgeSelect) buffWriter.println("\t\t" + ab + "_node.setEdgeSelect();"); // if (nIn.skipSizeInPalette) buffWriter.println("\t\t" + ab + "_node.setSkipSizeInPalette();"); // if (nIn.lowVt) buffWriter.println("\t\t" + ab + "_node.setNodeBit(PrimitiveNode.LOWVTBIT);"); // if (nIn.highVt) buffWriter.println("\t\t" + ab + "_node.setNodeBit(PrimitiveNode.HIGHVTBIT);"); // if (nIn.nativeBit) buffWriter.println("\t\t" + ab + "_node.setNodeBit(PrimitiveNode.NATIVEBIT);"); // if (nIn.od18) buffWriter.println("\t\t" + ab + "_node.setNodeBit(PrimitiveNode.OD18BIT);"); // if (nIn.od25) buffWriter.println("\t\t" + ab + "_node.setNodeBit(PrimitiveNode.OD25BIT);"); // if (nIn.od33) buffWriter.println("\t\t" + ab + "_node.setNodeBit(PrimitiveNode.OD33BIT);"); // if (nIn.notUsed) buffWriter.println("\t\t" + ab + "_node.setNotUsed(true);"); // if (nIn.arcsShrink) // buffWriter.println("\t\t" + ab + "_node.setArcsWipe();"); // buffWriter.println("\t\t" + ab + "_node.setArcsShrink();"); // if (nIn.nodeSizeRule != null) { // buffWriter.println("\t\t" + ab + "_node.setMinSize(" + nIn.nodeSizeRule.getWidth() + ", " + nIn.nodeSizeRule.getHeight() + // ", \"" + nIn.nodeSizeRule.getRuleName() + "\");"); // } // if (nIn.autoGrowth != null) { // buffWriter.println("\t\t" + ab + "_node.setAutoGrowth(" + nIn.autoGrowth.getWidth() + ", " + nIn.autoGrowth.getHeight() + ");"); // } // if (nIn.specialType != 0) // { // switch (nIn.specialType) // { // case PrimitiveNode.SERPTRANS: // buffWriter.println("\t\t" + ab + "_node.setHoldsOutline();"); // buffWriter.println("\t\t" + ab + "_node.setCanShrink();"); // buffWriter.println("\t\t" + ab + "_node.setSpecialType(PrimitiveNode.SERPTRANS);"); // buffWriter.println("\t\t" + ab + "_node.setSpecialValues(new double [] {" + // nIn.specialValues[0] + ", " + nIn.specialValues[1] + ", " + // nIn.specialValues[2] + ", " + nIn.specialValues[3] + ", " + // nIn.specialValues[4] + ", " + nIn.specialValues[5] + "});"); // break; // case PrimitiveNode.POLYGONAL: // buffWriter.println("\t\t" + ab + "_node.setHoldsOutline();"); // buffWriter.println("\t\t" + ab + "_node.setSpecialType(PrimitiveNode.POLYGONAL);"); // break; // } // } // } // // // write the pure-layer associations // buffWriter.println(); // buffWriter.println("\t\t// The pure layer nodes"); // for(int i=0; i<lList.length; i++) // { // if (lList[i].pseudo) continue; // // // find the pure layer node // for(int j=0; j<nList.length; j++) // { // if (nList[j].func != PrimitiveNode.Function.NODE) continue; // NodeInfo.LayerDetails nld = nList[j].nodeLayers[0]; // if (nld.layer == lList[i]) // { // buffWriter.println("\t\t" + lList[i].javaName + "_lay.setPureLayerNode(" + // nList[j].abbrev + "_node);\t\t// " + lList[i].name); // break; // } // } // } // buffWriter.println(); // } // // private void dumpNodeLayersToJava(PrintStream buffWriter, NodeInfo.LayerDetails[] mergedLayerDetails, boolean isSerpentine, boolean electrical) { // // print layers // buffWriter.println("\t\t\tnew Technology.NodeLayer []"); // buffWriter.println("\t\t\t{"); // ArrayList<NodeInfo.LayerDetails> layerDetails = new ArrayList<NodeInfo.LayerDetails>(); // for (NodeInfo.LayerDetails nld: mergedLayerDetails) { // if (electrical ? nld.inElectricalLayers : nld.inLayers) // layerDetails.add(nld); // } // int tot = layerDetails.size(); // for(int j=0; j<tot; j++) { // NodeInfo.LayerDetails nld = layerDetails.get(j); // int portNum = nld.portIndex; // switch (nld.representation) { // case Technology.NodeLayer.BOX: // buffWriter.print("\t\t\t\tnew Technology.NodeLayer(" + // nld.layer.javaName + "_lay, " + portNum + ", Poly.Type." + // nld.style.name() + ", Technology.NodeLayer.BOX,"); // break; // case Technology.NodeLayer.MINBOX: // buffWriter.print("\t\t\t\tnew Technology.NodeLayer(" + // nld.layer.javaName + "_lay, " + portNum + ", Poly.Type." + // nld.style.name() + ", Technology.NodeLayer.MINBOX,"); // break; // case Technology.NodeLayer.POINTS: // buffWriter.print("\t\t\t\tnew Technology.NodeLayer(" + // nld.layer.javaName + "_lay, " + portNum + ", Poly.Type." + // nld.style.name() + ", Technology.NodeLayer.POINTS,"); // break; // case Technology.NodeLayer.MULTICUTBOX: // buffWriter.print("\t\t\t\tTechnology.NodeLayer.makeMulticut(" + // nld.layer.javaName + "_lay, " + portNum + ", Poly.Type." + // nld.style.name() + ","); // break; // default: // buffWriter.print(" Technology.NodeLayer.????,"); // break; // } // buffWriter.println(" new Technology.TechPoint [] {"); // int totLayers = nld.values.length; // for(int k=0; k<totLayers; k++) { // Technology.TechPoint tp = nld.values[k]; // buffWriter.print("\t\t\t\t\tnew Technology.TechPoint(" + // getEdgeLabel(tp, false) + ", " + getEdgeLabel(tp, true) + ")"); // if (k < totLayers-1) buffWriter.println(","); else // buffWriter.print("}"); // } // if (isSerpentine) { // buffWriter.print(", " + nld.lWidth + ", " + nld.rWidth + ", " + // nld.extendB + ", " + nld.extendT); // } else if (nld.representation == Technology.NodeLayer.MULTICUTBOX) { // buffWriter.print(", " + nld.multiXS + ", " + nld.multiYS + ", " + nld.multiSep + ", " + nld.multiSep2D); // } // buffWriter.print(")"); // if (j+1 < tot) buffWriter.print(","); // buffWriter.println(); // } // buffWriter.println("\t\t\t});"); // } // // private void dumpPaletteToJava(PrintStream buffWriter, Object[][] menuPalette) { // int numRows = menuPalette.length; // int numCols = menuPalette[0].length; // buffWriter.println("\t\t// Building information for palette"); // buffWriter.println("\t\tnodeGroups = new Object[" + numRows + "][" + numCols + "];"); // buffWriter.println("\t\tint count = -1;"); // buffWriter.println(); // for (int row = 0; row < numRows; row++) { // buffWriter.print("\t\t"); // for (int col = 0; col < numCols; col++) { // if (col != 0) buffWriter.print(" "); // buffWriter.print("nodeGroups["); // if (col == 0) buffWriter.print("++"); // buffWriter.print("count][" + col + "] = "); // Object menuObject = menuPalette[row][col]; // if (menuObject instanceof ArcInfo) { // buffWriter.print(((ArcInfo)menuObject).javaName + "_arc"); // } else if (menuObject instanceof NodeInfo) { // buffWriter.print(((NodeInfo)menuObject).abbrev + "_node"); // } else if (menuObject instanceof String) { // buffWriter.print("\"" + menuObject + "\""); // } else if (menuObject == null) { // buffWriter.print("null"); // } // buffWriter.print(";"); // } // buffWriter.println(); // } // buffWriter.println(); // } // // private void dumpFoundryToJava(PrintStream buffWriter, GeneralInfo gi, LayerInfo[] lList) { // List<String> gdsStrings = new ArrayList<String>(); // for (LayerInfo li: lList) { // if (li.gds == null || li.gds.length() == 0) continue; // gdsStrings.add(li.name + " " + li.gds); // } // buffWriter.println("\t\t//Foundry"); // buffWriter.print("\t\tnewFoundry(Foundry.Type." + gi.defaultFoundry + ", null"); // for (String s: gdsStrings) { // buffWriter.println(","); // buffWriter.print("\t\t\t\"" + s + "\""); // } // buffWriter.println(");"); // buffWriter.println(); // } // // /** // * Method to remove illegal Java charcters from "string". // */ // private String makeJavaName(String string) // { // StringBuffer infstr = new StringBuffer(); // for(int i=0; i<string.length(); i++) // { // char chr = string.charAt(i); // if (i == 0) // { // if (!Character.isJavaIdentifierStart(chr)) chr = '_'; else // chr = Character.toLowerCase(chr); // } else // { // if (!Character.isJavaIdentifierPart(chr)) chr = '_'; // } // infstr.append(chr); // } // return infstr.toString(); // } // // /** // * Method to convert the multiplication and addition factors in "mul" and // * "add" into proper constant names. The "yAxis" is false for X and 1 for Y // */ // private String getEdgeLabel(Technology.TechPoint pt, boolean yAxis) // { // double mul, add; // if (yAxis) // { // add = pt.getY().getAdder(); // mul = pt.getY().getMultiplier(); // } else // { // add = pt.getX().getAdder(); // mul = pt.getX().getMultiplier(); // } // StringBuffer infstr = new StringBuffer(); // // // handle constant distance from center // if (mul == 0) // { // if (yAxis) infstr.append("EdgeV."); else // infstr.append("EdgeH."); // if (add == 0) // { // infstr.append("makeCenter()"); // } else // { // infstr.append("fromCenter(" + TextUtils.formatDouble(add, NUM_FRACTIONS) + ")"); // } // return infstr.toString(); // } // // // handle constant distance from edge // if (mul == 0.5 || mul == -0.5) // { // if (yAxis) infstr.append("EdgeV."); else // infstr.append("EdgeH."); // double amt = Math.abs(add); // if (!yAxis) // { // if (mul < 0) // { // if (add == 0) infstr.append("makeLeftEdge()"); else // infstr.append("fromLeft(" + TextUtils.formatDouble(amt, NUM_FRACTIONS) + ")"); // } else // { // if (add == 0) infstr.append("makeRightEdge()"); else // infstr.append("fromRight(" + TextUtils.formatDouble(amt, NUM_FRACTIONS) + ")"); // } // } else // { // if (mul < 0) // { // if (add == 0) infstr.append("makeBottomEdge()"); else // infstr.append("fromBottom(" + TextUtils.formatDouble(amt, NUM_FRACTIONS) + ")"); // } else // { // if (add == 0) infstr.append("makeTopEdge()"); else // infstr.append("fromTop(" + TextUtils.formatDouble(amt, NUM_FRACTIONS) + ")"); // } // } // return infstr.toString(); // } // // // generate two-value description // if (!yAxis) // infstr.append("new EdgeH(" + TextUtils.formatDouble(mul, NUM_FRACTIONS) + ", " + TextUtils.formatDouble(add, NUM_FRACTIONS) + ")"); else // infstr.append("new EdgeV(" + TextUtils.formatDouble(mul, NUM_FRACTIONS) + ", " + TextUtils.formatDouble(add, NUM_FRACTIONS) + ")"); // return infstr.toString(); // } /************************************* WRITE TECHNOLOGY AS "XML" *************************************/ /** * Method to convert tech-edit information to an Xml.Technology. * @param newTechName new technology name. * @param gi general technology information. * @param lList information about layers. * @param nList information about primitive nodes. * @param aList information about primitive arcs. */ private Xml.Technology makeXml(String newTechName, GeneralInfo gi, LayerInfo[] lList, NodeInfo[] nList, ArcInfo[] aList) { Xml.Technology t = new Xml.Technology(); t.techName = newTechName; t.shortTechName = gi.shortName; t.description = gi.description; Xml.Version version = new Xml.Version(); version.techVersion = 1; version.electricVersion = Version.parseVersion("8.05g"); t.versions.add(version); version = new Xml.Version(); version.techVersion = 2; version.electricVersion = Version.parseVersion("8.05o"); t.versions.add(version); t.minNumMetals = t.maxNumMetals = t.defaultNumMetals = gi.defaultNumMetals; t.scaleValue = gi.scale; t.scaleRelevant = gi.scaleRelevant; t.defaultFoundry = gi.defaultFoundry; t.minResistance = gi.minRes; t.minCapacitance = gi.minCap; if (gi.transparentColors != null) { for (int i = 0; i < gi.transparentColors.length; i++) t.transparentLayers.add(gi.transparentColors[i]); } for (LayerInfo li: lList) { if (li.pseudo) continue; Xml.Layer layer = new Xml.Layer(); layer.name = li.name; layer.function = li.fun; layer.extraFunction = li.funExtra; layer.desc = li.desc; layer.thick3D = li.thick3d; layer.height3D = li.height3d; layer.mode3D = li.mode3d; layer.factor3D = li.factor3d; layer.cif = li.cif; layer.resistance = li.spiRes; layer.capacitance = li.spiCap; layer.edgeCapacitance = li.spiECap; // if (li.myPseudo != null) // layer.pseudoLayer = li.myPseudo.name; if (li.pureLayerNode != null) { layer.pureLayerNode = new Xml.PureLayerNode(); layer.pureLayerNode.name = li.pureLayerNode.name; layer.pureLayerNode.style = li.pureLayerNode.nodeLayers[0].style; layer.pureLayerNode.port = li.pureLayerNode.nodePortDetails[0].name; layer.pureLayerNode.size.value = DBMath.round(li.pureLayerNode.xSize); for (ArcInfo a: li.pureLayerNode.nodePortDetails[0].connections) layer.pureLayerNode.portArcs.add(a.name); } t.layers.add(layer); } for (ArcInfo ai: aList) { Xml.ArcProto ap = new Xml.ArcProto(); ap.name = ai.name; ap.function = ai.func; ap.wipable = ai.wipes; ap.curvable = ai.curvable; ap.special = ai.special; ap.notUsed = ai.notUsed; ap.skipSizeInPalette = ai.skipSizeInPalette; ap.extended = !ai.noExtend; ap.fixedAngle = ai.fixAng; ap.angleIncrement = ai.angInc; ap.antennaRatio = ai.antennaRatio; if (ai.widthOffset != 0) { ap.diskOffset.put(Integer.valueOf(1), new Double(DBMath.round(0.5*ai.maxWidth))); ap.diskOffset.put(Integer.valueOf(2), new Double(DBMath.round(0.5*(ai.maxWidth - ai.widthOffset)))); } else { ap.diskOffset.put(Integer.valueOf(2), new Double(DBMath.round(0.5*ai.maxWidth))); } ap.defaultWidth.value = 0; for (ArcInfo.LayerDetails al: ai.arcDetails) { Xml.ArcLayer l = new Xml.ArcLayer(); l.layer = al.layer.name; l.style = al.style == Poly.Type.FILLED ? Poly.Type.FILLED : Poly.Type.CLOSED; l.extend.value = DBMath.round((ai.maxWidth - al.width)/2); ap.arcLayers.add(l); } t.arcs.add(ap); } for (NodeInfo ni: nList) { if (ni.func == PrimitiveNode.Function.NODE && ni.nodeLayers[0].layer.pureLayerNode == ni) continue; Xml.PrimitiveNode pn = new Xml.PrimitiveNode(); pn.name = ni.name; pn.function = ni.func; pn.shrinkArcs = ni.arcsShrink; pn.square = ni.square; pn.canBeZeroSize = ni.canBeZeroSize; pn.wipes = ni.wipes; pn.lockable = ni.lockable; pn.edgeSelect = ni.edgeSelect; pn.skipSizeInPalette = ni.skipSizeInPalette; pn.notUsed = ni.notUsed; pn.lowVt = ni.lowVt; pn.highVt = ni.highVt; pn.nativeBit = ni.nativeBit; pn.od18 = ni.od18; pn.od25 = ni.od25; pn.od33 = ni.od33; EPoint minFullSize = EPoint.fromLambda(0.5*ni.xSize, 0.5*ni.ySize); SizeOffset so = ni.so; if (so != null && so.getLowXOffset() == 0 && so.getHighXOffset() == 0 && so.getLowYOffset() == 0 && so.getHighYOffset() == 0) so = null; if (so != null) { EPoint p2 = EPoint.fromGrid( minFullSize.getGridX() - ((so.getLowXGridOffset() + so.getHighXGridOffset()) >> 1), minFullSize.getGridY() - ((so.getLowYGridOffset() + so.getHighYGridOffset()) >> 1)); pn.diskOffset.put(Integer.valueOf(1), minFullSize); pn.diskOffset.put(Integer.valueOf(2), p2); } else { pn.diskOffset.put(Integer.valueOf(2), minFullSize); } // pn.defaultWidth.value = DBMath.round(ni.xSize); // pn.defaultHeight.value = DBMath.round(ni.ySize); pn.sizeOffset = so; for(int j=0; j<ni.nodeLayers.length; j++) { NodeInfo.LayerDetails nl = ni.nodeLayers[j]; pn.nodeLayers.add(makeNodeLayerDetails(nl, ni.serp, minFullSize)); } for (int j = 0; j < ni.nodePortDetails.length; j++) { NodeInfo.PortDetails pd = ni.nodePortDetails[j]; Xml.PrimitivePort pp = new Xml.PrimitivePort(); pp.name = pd.name; pp.portAngle = pd.angle; pp.portRange = pd.range; pp.portTopology = pd.netIndex; EdgeH left = pd.values[0].getX(); EdgeH right = pd.values[1].getX(); EdgeV bottom = pd.values[0].getY(); EdgeV top = pd.values[1].getY(); pp.lx.k = left.getMultiplier()*2; pp.lx.value = left.getAdder() + minFullSize.getLambdaX()*left.getMultiplier()*2; pp.hx.k = right.getMultiplier()*2; pp.hx.value = right.getAdder() + minFullSize.getLambdaX()*right.getMultiplier()*2; pp.ly.k = bottom.getMultiplier()*2; pp.ly.value = bottom.getAdder() + minFullSize.getLambdaY()*bottom.getMultiplier()*2; pp.hy.k = top.getMultiplier()*2; pp.hy.value = top.getAdder() + minFullSize.getLambdaY()*top.getMultiplier()*2; // pp.p0 = pd.values[0]; // pp.p1 = pd.values[1]; for (ArcInfo a: pd.connections) pp.portArcs.add(a.name); pn.ports.add(pp); } pn.specialType = ni.specialType; if (pn.specialType == PrimitiveNode.SERPTRANS) { pn.specialValues = new double[6]; for (int i = 0; i < 6; i++) pn.specialValues[i] = ni.specialValues[i]; } pn.nodeSizeRule = ni.nodeSizeRule; t.nodes.add(pn); } addSpiceHeader(t, 1, gi.spiceLevel1Header); addSpiceHeader(t, 2, gi.spiceLevel2Header); addSpiceHeader(t, 3, gi.spiceLevel3Header); if (gi.menuPalette != null) { t.menuPalette = new Xml.MenuPalette(); int numColumns = gi.menuPalette[0].length; t.menuPalette.numColumns = numColumns; for (Object[] menuLine: gi.menuPalette) { for (int i = 0; i < numColumns; i++) t.menuPalette.menuBoxes.add(makeMenuBoxXml(t, menuLine[i])); } } Xml.Foundry foundry = new Xml.Foundry(); foundry.name = gi.defaultFoundry; for (LayerInfo li: lList) { if (li.gds != null && li.gds.length() > 0) foundry.layerGds.put(li.name, li.gds); } if (gi.conDist != null && gi.unConDist != null) { int layerTotal = lList.length; int ruleIndex = 0; for (int i1 = 0; i1 < layerTotal; i1++) { LayerInfo l1 = lList[i1]; for (int i2 = i1; i2 < layerTotal; i2++) { LayerInfo l2 = lList[i2]; double conSpa = gi.conDist[ruleIndex]; double uConSpa = gi.unConDist[ruleIndex]; if (conSpa > -1) foundry.rules.add(makeDesignRule("C" + ruleIndex, l1, l2, DRCTemplate.DRCRuleType.CONSPA, conSpa)); if (uConSpa > -1) foundry.rules.add(makeDesignRule("U" + ruleIndex, l1, l2, DRCTemplate.DRCRuleType.UCONSPA, uConSpa)); ruleIndex++; } } } t.foundries.add(foundry); return t; } private Xml.NodeLayer makeNodeLayerDetails(NodeInfo.LayerDetails nl, boolean isSerp, EPoint correction) { Xml.NodeLayer nld = new Xml.NodeLayer(); nld.layer = nl.layer.name; nld.style = nl.style; nld.portNum = nl.portIndex; nld.inLayers = nl.inLayers; nld.inElectricalLayers = nl.inElectricalLayers; nld.representation = nl.representation; Technology.TechPoint[] points = nl.values; if (nld.representation == Technology.NodeLayer.BOX || nld.representation == Technology.NodeLayer.MULTICUTBOX) { nld.lx.k = points[0].getX().getMultiplier()*2; nld.lx.value = DBMath.round(points[0].getX().getAdder() + correction.getLambdaX()*points[0].getX().getMultiplier()*2); nld.hx.k = points[1].getX().getMultiplier()*2; nld.hx.value = DBMath.round(points[1].getX().getAdder() + correction.getLambdaX()*points[1].getX().getMultiplier()*2); nld.ly.k = points[0].getY().getMultiplier()*2; nld.ly.value = DBMath.round(points[0].getY().getAdder() + correction.getLambdaY()*points[0].getY().getMultiplier()*2); nld.hy.k = points[1].getY().getMultiplier()*2; nld.hy.value = DBMath.round(points[1].getY().getAdder() + correction.getLambdaY()*points[1].getY().getMultiplier()*2); } else { for (Technology.TechPoint p: points) nld.techPoints.add(correction(p, correction)); } nld.sizex = DBMath.round(nl.multiXS); nld.sizey = DBMath.round(nl.multiYS); nld.sep1d = DBMath.round(nl.multiSep); nld.sep2d = DBMath.round(nl.multiSep2D); if (isSerp) { nld.lWidth = DBMath.round(nl.lWidth); nld.rWidth = DBMath.round(nl.rWidth); nld.tExtent = DBMath.round(nl.extendT); nld.bExtent = DBMath.round(nl.extendB); } return nld; } private Technology.TechPoint correction(Technology.TechPoint p, EPoint correction) { EdgeH h = p.getX(); EdgeV v = p.getY(); h = new EdgeH(h.getMultiplier(), h.getAdder() + correction.getLambdaX()*h.getMultiplier()*2); v = new EdgeV(v.getMultiplier(), v.getAdder() + correction.getLambdaY()*v.getMultiplier()*2); return new Technology.TechPoint(h, v); } private void addSpiceHeader(Xml.Technology t, int level, String[] spiceLines) { if (spiceLines == null) return; Xml.SpiceHeader spiceHeader = new Xml.SpiceHeader(); spiceHeader.level = level; for (String spiceLine: spiceLines) spiceHeader.spiceLines.add(spiceLine); t.spiceHeaders.add(spiceHeader); } private ArrayList<Object> makeMenuBoxXml(Xml.Technology t, Object o) { ArrayList<Object> menuBox = new ArrayList<Object>(); if (o != null) { if (o instanceof List) { for(Object subO : (List)o) menuBox.add(subO); } else menuBox.add(o); } return menuBox; } private DRCTemplate makeDesignRule(String ruleName, LayerInfo l1, LayerInfo l2, DRCTemplate.DRCRuleType type, double value) { return new DRCTemplate(ruleName, DRCTemplate.DRCMode.ALL.mode(), type, l1.name, l2.name, new double[] {value}, null, null); } }
true
true
private NodeInfo [] extractNodes(Library [] dependentLibs, LayerInfo [] lList, ArcInfo [] aList) { Cell [] nodeCells = Info.findCellSequence(dependentLibs, "node-", Info.NODESEQUENCE_KEY); if (nodeCells.length <= 0) { System.out.println("No nodes found"); return null; } NodeInfo [] nList = new NodeInfo[nodeCells.length]; // get the nodes int nodeIndex = 0; for(int pass=0; pass<3; pass++) for(int m=0; m<nodeCells.length; m++) { // make sure this is the right type of node for this pass of the nodes Cell np = nodeCells[m]; NodeInfo nIn = NodeInfo.parseCell(np); Netlist netList = np.acquireUserNetlist(); if (netList == null) { System.out.println("Sorry, a deadlock technology generation (network information unavailable). Please try again"); return null; } // only want pins on pass 0, pure-layer nodes on pass 2 if (pass == 0 && nIn.func != PrimitiveNode.Function.PIN) continue; if (pass == 1 && (nIn.func == PrimitiveNode.Function.PIN || nIn.func == PrimitiveNode.Function.NODE)) continue; if (pass == 2 && nIn.func != PrimitiveNode.Function.NODE) continue; if (nIn.func == PrimitiveNode.Function.NODE) { if (nIn.serp) { error.markError(null, np, "Pure layer " + nIn.name + " can not be serpentine"); return null; } nIn.specialType = PrimitiveNode.POLYGONAL; } nList[nodeIndex] = nIn; nIn.name = np.getName().substring(5); // build a list of examples found in this node List<Example> neList = Example.getExamples(np, true, error); if (neList == null || neList.size() == 0) { System.out.println("Cannot analyze " + np); return null; } Example firstEx = neList.get(0); nIn.xSize = firstEx.hx - firstEx.lx; nIn.ySize = firstEx.hy - firstEx.ly; // sort the layers in the main example Collections.sort(firstEx.samples, new SamplesByLayerOrder(lList)); // associate the samples in each example if (associateExamples(neList, np)) return null; // derive primitives from the examples nIn.nodeLayers = makePrimitiveNodeLayers(neList, np, lList); if (nIn.nodeLayers == null) return null; // count the number of ports on this node int portCount = 0; for(Sample ns : firstEx.samples) { if (ns.layer == Generic.tech.portNode) portCount++; } if (portCount == 0) { error.markError(null, np, "No ports found"); return null; } // fill the port structures List<NodeInfo.PortDetails> ports = new ArrayList<NodeInfo.PortDetails>(); Map<NodeInfo.PortDetails,Sample> portSamples = new HashMap<NodeInfo.PortDetails,Sample>(); for(Sample ns : firstEx.samples) { if (ns.layer != Generic.tech.portNode) continue; // port connections NodeInfo.PortDetails nipd = new NodeInfo.PortDetails(); portSamples.put(nipd, ns); // port name nipd.name = Info.getPortName(ns.node); if (nipd.name == null) { error.markError(ns.node, np, "Port does not have a name"); return null; } for(int c=0; c<nipd.name.length(); c++) { char str = nipd.name.charAt(c); if (str <= ' ' || str >= 0177) { error.markError(ns.node, np, "Invalid port name"); return null; } } // port angle and range nipd.angle = 0; Variable varAngle = ns.node.getVar(Info.PORTANGLE_KEY); if (varAngle != null) nipd.angle = ((Integer)varAngle.getObject()).intValue(); nipd.range = 180; Variable varRange = ns.node.getVar(Info.PORTRANGE_KEY); if (varRange != null) nipd.range = ((Integer)varRange.getObject()).intValue(); // port area rule nipd.values = ns.values; ports.add(nipd); } // sort the ports by name within angle Collections.sort(ports, new PortsByAngleAndName()); // now find the poly/active ports for transistor rearranging int pol1Port = -1, pol2Port = -1, dif1Port = -1, dif2Port = -1; for(int i=0; i<ports.size(); i++) { NodeInfo.PortDetails nipd = ports.get(i); Sample ns = portSamples.get(nipd); nipd.connections = new ArcInfo[0]; Variable var = ns.node.getVar(Info.CONNECTION_KEY); if (var != null) { // convert "arc-CELL" pointers to indices CellId [] arcCells = (CellId [])var.getObject(); List<ArcInfo> validArcCells = new ArrayList<ArcInfo>(); for(int j=0; j<arcCells.length; j++) { // find arc that connects if (arcCells[j] == null) continue; Cell arcCell = EDatabase.serverDatabase().getCell(arcCells[j]); if (arcCell == null) continue; String cellName = arcCell.getName().substring(4); for(int k=0; k<aList.length; k++) { if (aList[k].name.equalsIgnoreCase(cellName)) { validArcCells.add(aList[k]); break; } } } ArcInfo [] connections = new ArcInfo[validArcCells.size()]; nipd.connections = connections; for(int j=0; j<validArcCells.size(); j++) connections[j] = validArcCells.get(j); for(int j=0; j<connections.length; j++) { // find port characteristics for possible transistors Variable meaningVar = ns.node.getVar(Info.PORTMEANING_KEY); int meaning = 0; if (meaningVar != null) meaning = ((Integer)meaningVar.getObject()).intValue(); if (connections[j].func.isPoly() || meaning == 1) { if (pol1Port < 0) { pol1Port = i; break; } else if (pol2Port < 0) { pol2Port = i; break; } } else if (connections[j].func.isDiffusion() || meaning == 2) { if (dif1Port < 0) { dif1Port = i; break; } else if (dif2Port < 0) { dif2Port = i; break; } } } } } // save the ports in an array nIn.nodePortDetails = new NodeInfo.PortDetails[ports.size()]; for(int j=0; j<ports.size(); j++) nIn.nodePortDetails[j] = ports.get(j); // on MOS transistors, make sure the first 4 ports are poly/active/poly/active if (nIn.func == PrimitiveNode.Function.TRANMOS || nIn.func == PrimitiveNode.Function.TRADMOS || nIn.func == PrimitiveNode.Function.TRAPMOS || nIn.func == PrimitiveNode.Function.TRADMES || nIn.func == PrimitiveNode.Function.TRAEMES) { if (pol1Port < 0 || pol2Port < 0 || dif1Port < 0 || dif2Port < 0) { error.markError(null, np, "Need 2 gate (poly) and 2 gated (active) ports on field-effect transistor"); return null; } // also make sure that dif1Port is positive and dif2Port is negative double x1Pos = (nIn.nodePortDetails[dif1Port].values[0].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[dif1Port].values[0].getX().getAdder() + nIn.nodePortDetails[dif1Port].values[1].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[dif1Port].values[1].getX().getAdder()) / 2; double x2Pos = (nIn.nodePortDetails[dif2Port].values[0].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[dif2Port].values[0].getX().getAdder() + nIn.nodePortDetails[dif2Port].values[1].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[dif2Port].values[1].getX().getAdder()) / 2; double y1Pos = (nIn.nodePortDetails[dif1Port].values[0].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[dif1Port].values[0].getY().getAdder() + nIn.nodePortDetails[dif1Port].values[1].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[dif1Port].values[1].getY().getAdder()) / 2; double y2Pos = (nIn.nodePortDetails[dif2Port].values[0].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[dif2Port].values[0].getY().getAdder() + nIn.nodePortDetails[dif2Port].values[1].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[dif2Port].values[1].getY().getAdder()) / 2; if (Math.abs(x1Pos-x2Pos) > Math.abs(y1Pos-y2Pos)) { if (x1Pos < x2Pos) { int k = dif1Port; dif1Port = dif2Port; dif2Port = k; } } else { if (y1Pos < y2Pos) { int k = dif1Port; dif1Port = dif2Port; dif2Port = k; } } // also make sure that pol1Port is negative and pol2Port is positive x1Pos = (nIn.nodePortDetails[pol1Port].values[0].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[pol1Port].values[0].getX().getAdder() + nIn.nodePortDetails[pol1Port].values[1].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[pol1Port].values[1].getX().getAdder()) / 2; x2Pos = (nIn.nodePortDetails[pol2Port].values[0].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[pol2Port].values[0].getX().getAdder() + nIn.nodePortDetails[pol2Port].values[1].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[pol2Port].values[1].getX().getAdder()) / 2; y1Pos = (nIn.nodePortDetails[pol1Port].values[0].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[pol1Port].values[0].getY().getAdder() + nIn.nodePortDetails[pol1Port].values[1].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[pol1Port].values[1].getY().getAdder()) / 2; y2Pos = (nIn.nodePortDetails[pol2Port].values[0].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[pol2Port].values[0].getY().getAdder() + nIn.nodePortDetails[pol2Port].values[1].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[pol2Port].values[1].getY().getAdder()) / 2; if (Math.abs(x1Pos-x2Pos) > Math.abs(y1Pos-y2Pos)) { if (x1Pos > x2Pos) { int k = pol1Port; pol1Port = pol2Port; pol2Port = k; } } else { if (y1Pos > y2Pos) { int k = pol1Port; pol1Port = pol2Port; pol2Port = k; } } // gather extra ports that go at the end List<NodeInfo.PortDetails> extras = new ArrayList<NodeInfo.PortDetails>(); for(int j=0; j<ports.size(); j++) { if (j != pol1Port && j != dif1Port && j != pol2Port && j != dif2Port) extras.add(ports.get(j)); } // rearrange the ports NodeInfo.PortDetails port0 = nIn.nodePortDetails[pol1Port]; NodeInfo.PortDetails port1 = nIn.nodePortDetails[dif1Port]; NodeInfo.PortDetails port2 = nIn.nodePortDetails[pol2Port]; NodeInfo.PortDetails port3 = nIn.nodePortDetails[dif2Port]; nIn.nodePortDetails[pol1Port=0] = port0; nIn.nodePortDetails[dif1Port=1] = port1; nIn.nodePortDetails[pol2Port=2] = port2; nIn.nodePortDetails[dif2Port=3] = port3; for(int j=0; j<extras.size(); j++) nIn.nodePortDetails[j+4] = extras.get(j); // establish port connectivity for(int i=0; i<nIn.nodePortDetails.length; i++) { NodeInfo.PortDetails nipd = nIn.nodePortDetails[i]; Sample ns = portSamples.get(nipd); nipd.netIndex = i; if (ns.node.hasConnections()) { ArcInst ai1 = ns.node.getConnections().next().getArc(); Network net1 = netList.getNetwork(ai1, 0); for(int j=0; j<i; j++) { NodeInfo.PortDetails onipd = nIn.nodePortDetails[j]; Sample oNs = portSamples.get(onipd); if (oNs.node.hasConnections()) { ArcInst ai2 = oNs.node.getConnections().next().getArc(); Network net2 = netList.getNetwork(ai2, 0); if (net1 == net2) { nipd.netIndex = j; break; } } } } } // make sure implant layers are not connected to ports for(int k=0; k<nIn.nodeLayers.length; k++) { NodeInfo.LayerDetails nld = nIn.nodeLayers[k]; if (nld.layer.fun.isSubstrate()) nld.portIndex = -1; } } if (nIn.serp) { // finish up serpentine transistors nIn.specialType = PrimitiveNode.SERPTRANS; // determine port numbers for serpentine transistors int polIndex = -1, difIndex = -1; for(int k=0; k<nIn.nodeLayers.length; k++) { NodeInfo.LayerDetails nld = nIn.nodeLayers[k]; if (nld.layer.fun.isPoly()) { polIndex = k; } else if (nld.layer.fun.isDiff()) { if (difIndex >= 0) { // figure out which layer is the basic active layer int funExtraOld = nIn.nodeLayers[difIndex].layer.funExtra; int funExtraNew = nld.layer.funExtra; if (funExtraOld == funExtraNew) continue; if (funExtraOld == 0) // if ((funExtraOld & ~(Layer.Function.PTYPE|Layer.Function.NTYPE)) == 0) continue; } difIndex = k; } } if (difIndex < 0 || polIndex < 0) { error.markError(null, np, "No diffusion and polysilicon layers in serpentine transistor"); return null; } // find width and extension from comparison to poly layer Sample polNs = nIn.nodeLayers[polIndex].ns; Rectangle2D polNodeBounds = polNs.node.getBounds(); Sample difNs = nIn.nodeLayers[difIndex].ns; Rectangle2D difNodeBounds = difNs.node.getBounds(); for(int k=0; k<nIn.nodeLayers.length; k++) { NodeInfo.LayerDetails nld = nIn.nodeLayers[k]; Sample ns = nld.ns; Rectangle2D nodeBounds = ns.node.getBounds(); if (polNodeBounds.getWidth() > polNodeBounds.getHeight()) { // horizontal layer nld.lWidth = nodeBounds.getMaxY() - (ns.parent.ly + ns.parent.hy)/2; nld.rWidth = (ns.parent.ly + ns.parent.hy)/2 - nodeBounds.getMinY(); nld.extendT = difNodeBounds.getMinX() - nodeBounds.getMinX(); } else { // vertical layer nld.lWidth = nodeBounds.getMaxX() - (ns.parent.lx + ns.parent.hx)/2; nld.rWidth = (ns.parent.lx + ns.parent.hx)/2 - nodeBounds.getMinX(); nld.extendT = difNodeBounds.getMinY() - nodeBounds.getMinY(); } nld.extendB = nld.extendT; } // add in electrical layers for diffusion NodeInfo.LayerDetails [] addedLayers = new NodeInfo.LayerDetails[nIn.nodeLayers.length+2]; for(int k=0; k<nIn.nodeLayers.length; k++) addedLayers[k] = nIn.nodeLayers[k]; NodeInfo.LayerDetails diff1 = nIn.nodeLayers[difIndex].duplicate(); NodeInfo.LayerDetails diff2 = nIn.nodeLayers[difIndex].duplicate(); addedLayers[nIn.nodeLayers.length] = diff1; addedLayers[nIn.nodeLayers.length+1] = diff2; nIn.nodeLayers = addedLayers; diff1.inLayers = diff2.inLayers = false; nIn.nodeLayers[difIndex].inElectricalLayers = false; diff1.portIndex = dif2Port; diff2.portIndex = dif1Port; // compute port extension factors nIn.specialValues = new double[6]; int layerCount = 0; for(Sample ns : firstEx.samples) { if (ns.values != null && ns.layer != Generic.tech.portNode && ns.layer != Generic.tech.cellCenterNode && ns.layer != null) layerCount++; } nIn.specialValues[0] = layerCount+1; if (nIn.nodePortDetails[dif1Port].values[0].getX().getAdder() > nIn.nodePortDetails[dif1Port].values[0].getY().getAdder()) { // vertical diffusion layer: determine polysilicon width nIn.specialValues[3] = (nIn.ySize * nIn.nodeLayers[polIndex].values[1].getY().getMultiplier() + nIn.nodeLayers[polIndex].values[1].getY().getAdder()) - (nIn.ySize * nIn.nodeLayers[polIndex].values[0].getY().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getY().getAdder()); // determine diffusion port rule nIn.specialValues[1] = (nIn.xSize * nIn.nodePortDetails[dif1Port].values[0].getX().getMultiplier() + nIn.nodePortDetails[dif1Port].values[0].getX().getAdder()) - (nIn.xSize * nIn.nodeLayers[difIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[difIndex].values[0].getX().getAdder()); nIn.specialValues[2] = (nIn.ySize * nIn.nodePortDetails[dif1Port].values[0].getY().getMultiplier() + nIn.nodePortDetails[dif1Port].values[0].getY().getAdder()) - (nIn.ySize * nIn.nodeLayers[polIndex].values[1].getY().getMultiplier() + nIn.nodeLayers[polIndex].values[1].getY().getAdder()); // determine polysilicon port rule nIn.specialValues[4] = (nIn.ySize * nIn.nodePortDetails[pol1Port].values[0].getY().getMultiplier() + nIn.nodePortDetails[pol1Port].values[0].getY().getAdder()) - (nIn.ySize * nIn.nodeLayers[polIndex].values[0].getY().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getY().getAdder()); nIn.specialValues[5] = (nIn.xSize * nIn.nodeLayers[difIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[difIndex].values[0].getX().getAdder()) - (nIn.xSize * nIn.nodePortDetails[pol1Port].values[1].getX().getMultiplier() + nIn.nodePortDetails[pol1Port].values[1].getX().getAdder()); // setup electrical layers for diffusion diff1.values[0].getY().setMultiplier(0); diff1.values[0].getY().setAdder(0); diff1.rWidth = 0; diff2.values[1].getY().setMultiplier(0); diff2.values[1].getY().setAdder(0); diff2.lWidth = 0; } else { // horizontal diffusion layer: determine polysilicon width nIn.specialValues[3] = (nIn.xSize * nIn.nodeLayers[polIndex].values[1].getX().getMultiplier() + nIn.nodeLayers[polIndex].values[1].getX().getAdder()) - (nIn.xSize * nIn.nodeLayers[polIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getX().getAdder()); // determine diffusion port rule nIn.specialValues[1] = (nIn.ySize * nIn.nodePortDetails[dif1Port].values[0].getY().getMultiplier() + nIn.nodePortDetails[dif1Port].values[0].getY().getAdder()) - (nIn.ySize * nIn.nodeLayers[difIndex].values[0].getY().getMultiplier() + nIn.nodeLayers[difIndex].values[0].getY().getAdder()); nIn.specialValues[2] = (nIn.xSize * nIn.nodeLayers[polIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getX().getAdder()) - (nIn.xSize * nIn.nodePortDetails[dif1Port].values[1].getX().getMultiplier() + nIn.nodePortDetails[dif1Port].values[1].getX().getAdder()); // determine polysilicon port rule nIn.specialValues[4] = (nIn.xSize * nIn.nodePortDetails[pol1Port].values[0].getX().getMultiplier() + nIn.nodePortDetails[pol1Port].values[0].getX().getAdder()) - (nIn.xSize * nIn.nodeLayers[polIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getX().getAdder()); nIn.specialValues[5] = (nIn.ySize * nIn.nodeLayers[difIndex].values[0].getY().getMultiplier() + nIn.nodeLayers[difIndex].values[0].getY().getAdder()) - (nIn.ySize * nIn.nodePortDetails[pol1Port].values[1].getY().getMultiplier() + nIn.nodePortDetails[pol1Port].values[1].getY().getAdder()); // setup electrical layers for diffusion diff1.values[0].getX().setMultiplier(0); diff1.values[0].getX().setAdder(0); diff1.rWidth = 0; diff2.values[1].getX().setMultiplier(0); diff2.values[1].getX().setAdder(0); diff2.lWidth = 0; } } // extract width offset information from highlight box double lX = 0, hX = 0, lY = 0, hY = 0; boolean found = false; for(Sample ns : firstEx.samples) { if (ns.layer != null) continue; found = true; if (ns.values != null) { boolean err = false; if (ns.values[0].getX().getMultiplier() == -0.5) // left edge offset { lX = ns.values[0].getX().getAdder(); } else if (ns.values[0].getX().getMultiplier() == 0.5) { lX = nIn.xSize + ns.values[0].getX().getAdder(); } else err = true; if (ns.values[0].getY().getMultiplier() == -0.5) // bottom edge offset { lY = ns.values[0].getY().getAdder(); } else if (ns.values[0].getY().getMultiplier() == 0.5) { lY = nIn.ySize + ns.values[0].getY().getAdder();; } else err = true; if (ns.values[1].getX().getMultiplier() == 0.5) // right edge offset { hX = -ns.values[1].getX().getAdder(); } else if (ns.values[1].getX().getMultiplier() == -0.5) { hX = nIn.xSize - ns.values[1].getX().getAdder(); } else err = true; if (ns.values[1].getY().getMultiplier() == 0.5) // top edge offset { hY = -ns.values[1].getY().getAdder(); } else if (ns.values[1].getY().getMultiplier() == -0.5) { hY = nIn.ySize - ns.values[1].getY().getAdder(); } else err = true; if (err) { error.markError(ns.node, np, "Highlighting cannot scale from center"); return null; } } else { error.markError(ns.node, np, "No rule found for highlight"); return null; } } if (!found) { error.markError(null, np, "No highlight found"); return null; } if (lX != 0 || hX != 0 || lY != 0 || hY != 0) { nList[nodeIndex].so = new SizeOffset(lX, hX, lY, hY); } // // get grab point information // for(ns = neList.firstSample; ns != NOSAMPLE; ns = ns.nextSample) // if (ns.layer == Generic.tech.cellCenterNode) break; // if (ns != NOSAMPLE) // { // us_tecnode_grab[us_tecnode_grabcount++] = nodeindex+1; // us_tecnode_grab[us_tecnode_grabcount++] = (ns.node.geom.lowx + // ns.node.geom.highx - neList.lx - neList.hx)/2 * // el_curlib.lambda[tech.techindex] / lambda; // us_tecnode_grab[us_tecnode_grabcount++] = (ns.node.geom.lowy + // ns.node.geom.highy - neList.ly - neList.hy)/2 * // el_curlib.lambda[tech.techindex] / lambda; // us_tecflags |= HASGRAB; // } // advance the fill pointer nodeIndex++; } return nList; }
private NodeInfo [] extractNodes(Library [] dependentLibs, LayerInfo [] lList, ArcInfo [] aList) { Cell [] nodeCells = Info.findCellSequence(dependentLibs, "node-", Info.NODESEQUENCE_KEY); if (nodeCells.length <= 0) { System.out.println("No nodes found"); return null; } NodeInfo [] nList = new NodeInfo[nodeCells.length]; // get the nodes int nodeIndex = 0; for(int pass=0; pass<3; pass++) for(int m=0; m<nodeCells.length; m++) { // make sure this is the right type of node for this pass of the nodes Cell np = nodeCells[m]; NodeInfo nIn = NodeInfo.parseCell(np); Netlist netList = np.acquireUserNetlist(); if (netList == null) { System.out.println("Sorry, a deadlock technology generation (network information unavailable). Please try again"); return null; } // only want pins on pass 0, pure-layer nodes on pass 2 if (pass == 0 && nIn.func != PrimitiveNode.Function.PIN) continue; if (pass == 1 && (nIn.func == PrimitiveNode.Function.PIN || nIn.func == PrimitiveNode.Function.NODE)) continue; if (pass == 2 && nIn.func != PrimitiveNode.Function.NODE) continue; if (nIn.func == PrimitiveNode.Function.NODE) { if (nIn.serp) { error.markError(null, np, "Pure layer " + nIn.name + " can not be serpentine"); return null; } nIn.specialType = PrimitiveNode.POLYGONAL; } nList[nodeIndex] = nIn; nIn.name = np.getName().substring(5); // build a list of examples found in this node List<Example> neList = Example.getExamples(np, true, error); if (neList == null || neList.size() == 0) { System.out.println("Cannot analyze " + np); return null; } Example firstEx = neList.get(0); nIn.xSize = firstEx.hx - firstEx.lx; nIn.ySize = firstEx.hy - firstEx.ly; // sort the layers in the main example Collections.sort(firstEx.samples, new SamplesByLayerOrder(lList)); // associate the samples in each example if (associateExamples(neList, np)) return null; // derive primitives from the examples nIn.nodeLayers = makePrimitiveNodeLayers(neList, np, lList); if (nIn.nodeLayers == null) return null; // count the number of ports on this node int portCount = 0; for(Sample ns : firstEx.samples) { if (ns.layer == Generic.tech.portNode) portCount++; } if (portCount == 0) { error.markError(null, np, "No ports found"); return null; } // fill the port structures List<NodeInfo.PortDetails> ports = new ArrayList<NodeInfo.PortDetails>(); Map<NodeInfo.PortDetails,Sample> portSamples = new HashMap<NodeInfo.PortDetails,Sample>(); for(Sample ns : firstEx.samples) { if (ns.layer != Generic.tech.portNode) continue; // port connections NodeInfo.PortDetails nipd = new NodeInfo.PortDetails(); portSamples.put(nipd, ns); // port name nipd.name = Info.getPortName(ns.node); if (nipd.name == null) { error.markError(ns.node, np, "Port does not have a name"); return null; } for(int c=0; c<nipd.name.length(); c++) { char str = nipd.name.charAt(c); if (str <= ' ' || str >= 0177) { error.markError(ns.node, np, "Invalid port name"); return null; } } // port angle and range nipd.angle = 0; Variable varAngle = ns.node.getVar(Info.PORTANGLE_KEY); if (varAngle != null) nipd.angle = ((Integer)varAngle.getObject()).intValue(); nipd.range = 180; Variable varRange = ns.node.getVar(Info.PORTRANGE_KEY); if (varRange != null) nipd.range = ((Integer)varRange.getObject()).intValue(); // port area rule nipd.values = ns.values; ports.add(nipd); } // sort the ports by name within angle Collections.sort(ports, new PortsByAngleAndName()); // now find the poly/active ports for transistor rearranging int pol1Port = -1, pol2Port = -1, dif1Port = -1, dif2Port = -1; for(int i=0; i<ports.size(); i++) { NodeInfo.PortDetails nipd = ports.get(i); Sample ns = portSamples.get(nipd); nipd.connections = new ArcInfo[0]; Variable var = ns.node.getVar(Info.CONNECTION_KEY); if (var != null) { // convert "arc-CELL" pointers to indices CellId [] arcCells = (CellId [])var.getObject(); List<ArcInfo> validArcCells = new ArrayList<ArcInfo>(); for(int j=0; j<arcCells.length; j++) { // find arc that connects if (arcCells[j] == null) continue; Cell arcCell = EDatabase.serverDatabase().getCell(arcCells[j]); if (arcCell == null) continue; String cellName = arcCell.getName().substring(4); for(int k=0; k<aList.length; k++) { if (aList[k].name.equalsIgnoreCase(cellName)) { validArcCells.add(aList[k]); break; } } } ArcInfo [] connections = new ArcInfo[validArcCells.size()]; nipd.connections = connections; for(int j=0; j<validArcCells.size(); j++) connections[j] = validArcCells.get(j); for(int j=0; j<connections.length; j++) { // find port characteristics for possible transistors Variable meaningVar = ns.node.getVar(Info.PORTMEANING_KEY); int meaning = 0; if (meaningVar != null) meaning = ((Integer)meaningVar.getObject()).intValue(); if (connections[j].func.isPoly() || meaning == 1) { if (pol1Port < 0) { pol1Port = i; break; } else if (pol2Port < 0) { pol2Port = i; break; } } else if (connections[j].func.isDiffusion() || meaning == 2) { if (dif1Port < 0) { dif1Port = i; break; } else if (dif2Port < 0) { dif2Port = i; break; } } } } } // save the ports in an array nIn.nodePortDetails = new NodeInfo.PortDetails[ports.size()]; for(int j=0; j<ports.size(); j++) nIn.nodePortDetails[j] = ports.get(j); // on MOS transistors, make sure the first 4 ports are poly/active/poly/active if (nIn.func == PrimitiveNode.Function.TRANMOS || nIn.func == PrimitiveNode.Function.TRADMOS || nIn.func == PrimitiveNode.Function.TRAPMOS || nIn.func == PrimitiveNode.Function.TRADMES || nIn.func == PrimitiveNode.Function.TRAEMES) { if (pol1Port < 0 || pol2Port < 0 || dif1Port < 0 || dif2Port < 0) { error.markError(null, np, "Need 2 gate (poly) and 2 gated (active) ports on field-effect transistor"); return null; } // also make sure that dif1Port is positive and dif2Port is negative double x1Pos = (nIn.nodePortDetails[dif1Port].values[0].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[dif1Port].values[0].getX().getAdder() + nIn.nodePortDetails[dif1Port].values[1].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[dif1Port].values[1].getX().getAdder()) / 2; double x2Pos = (nIn.nodePortDetails[dif2Port].values[0].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[dif2Port].values[0].getX().getAdder() + nIn.nodePortDetails[dif2Port].values[1].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[dif2Port].values[1].getX().getAdder()) / 2; double y1Pos = (nIn.nodePortDetails[dif1Port].values[0].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[dif1Port].values[0].getY().getAdder() + nIn.nodePortDetails[dif1Port].values[1].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[dif1Port].values[1].getY().getAdder()) / 2; double y2Pos = (nIn.nodePortDetails[dif2Port].values[0].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[dif2Port].values[0].getY().getAdder() + nIn.nodePortDetails[dif2Port].values[1].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[dif2Port].values[1].getY().getAdder()) / 2; if (Math.abs(x1Pos-x2Pos) > Math.abs(y1Pos-y2Pos)) { if (x1Pos < x2Pos) { int k = dif1Port; dif1Port = dif2Port; dif2Port = k; } } else { if (y1Pos < y2Pos) { int k = dif1Port; dif1Port = dif2Port; dif2Port = k; } } // also make sure that pol1Port is negative and pol2Port is positive x1Pos = (nIn.nodePortDetails[pol1Port].values[0].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[pol1Port].values[0].getX().getAdder() + nIn.nodePortDetails[pol1Port].values[1].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[pol1Port].values[1].getX().getAdder()) / 2; x2Pos = (nIn.nodePortDetails[pol2Port].values[0].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[pol2Port].values[0].getX().getAdder() + nIn.nodePortDetails[pol2Port].values[1].getX().getMultiplier() * nIn.xSize + nIn.nodePortDetails[pol2Port].values[1].getX().getAdder()) / 2; y1Pos = (nIn.nodePortDetails[pol1Port].values[0].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[pol1Port].values[0].getY().getAdder() + nIn.nodePortDetails[pol1Port].values[1].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[pol1Port].values[1].getY().getAdder()) / 2; y2Pos = (nIn.nodePortDetails[pol2Port].values[0].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[pol2Port].values[0].getY().getAdder() + nIn.nodePortDetails[pol2Port].values[1].getY().getMultiplier() * nIn.ySize + nIn.nodePortDetails[pol2Port].values[1].getY().getAdder()) / 2; if (Math.abs(x1Pos-x2Pos) > Math.abs(y1Pos-y2Pos)) { if (x1Pos > x2Pos) { int k = pol1Port; pol1Port = pol2Port; pol2Port = k; } } else { if (y1Pos > y2Pos) { int k = pol1Port; pol1Port = pol2Port; pol2Port = k; } } // gather extra ports that go at the end List<NodeInfo.PortDetails> extras = new ArrayList<NodeInfo.PortDetails>(); for(int j=0; j<ports.size(); j++) { if (j != pol1Port && j != dif1Port && j != pol2Port && j != dif2Port) extras.add(ports.get(j)); } // rearrange the ports NodeInfo.PortDetails port0 = nIn.nodePortDetails[pol1Port]; NodeInfo.PortDetails port1 = nIn.nodePortDetails[dif1Port]; NodeInfo.PortDetails port2 = nIn.nodePortDetails[pol2Port]; NodeInfo.PortDetails port3 = nIn.nodePortDetails[dif2Port]; nIn.nodePortDetails[pol1Port=0] = port0; nIn.nodePortDetails[dif1Port=1] = port1; nIn.nodePortDetails[pol2Port=2] = port2; nIn.nodePortDetails[dif2Port=3] = port3; for(int j=0; j<extras.size(); j++) nIn.nodePortDetails[j+4] = extras.get(j); // establish port connectivity for(int i=0; i<nIn.nodePortDetails.length; i++) { NodeInfo.PortDetails nipd = nIn.nodePortDetails[i]; Sample ns = portSamples.get(nipd); nipd.netIndex = i; if (ns.node.hasConnections()) { ArcInst ai1 = ns.node.getConnections().next().getArc(); Network net1 = netList.getNetwork(ai1, 0); for(int j=0; j<i; j++) { NodeInfo.PortDetails onipd = nIn.nodePortDetails[j]; Sample oNs = portSamples.get(onipd); if (oNs.node.hasConnections()) { ArcInst ai2 = oNs.node.getConnections().next().getArc(); Network net2 = netList.getNetwork(ai2, 0); if (net1 == net2) { nipd.netIndex = j; break; } } } } } // make sure implant layers are not connected to ports for(int k=0; k<nIn.nodeLayers.length; k++) { NodeInfo.LayerDetails nld = nIn.nodeLayers[k]; if (nld.layer.fun.isSubstrate()) nld.portIndex = -1; } } if (nIn.serp) { // finish up serpentine transistors nIn.specialType = PrimitiveNode.SERPTRANS; // determine port numbers for serpentine transistors int polIndex = -1, difIndex = -1; for(int k=0; k<nIn.nodeLayers.length; k++) { NodeInfo.LayerDetails nld = nIn.nodeLayers[k]; if (nld.layer.fun.isPoly()) { polIndex = k; } else if (nld.layer.fun.isDiff()) { if (difIndex >= 0) { // figure out which layer is the basic active layer int funExtraOld = nIn.nodeLayers[difIndex].layer.funExtra; int funExtraNew = nld.layer.funExtra; if (funExtraOld == funExtraNew) continue; if (funExtraOld == 0) // if ((funExtraOld & ~(Layer.Function.PTYPE|Layer.Function.NTYPE)) == 0) continue; } difIndex = k; } } if (difIndex < 0 || polIndex < 0) { error.markError(null, np, "No diffusion and polysilicon layers in serpentine transistor"); return null; } // find width and extension from comparison to poly layer Sample polNs = nIn.nodeLayers[polIndex].ns; Rectangle2D polNodeBounds = polNs.node.getBounds(); Sample difNs = nIn.nodeLayers[difIndex].ns; Rectangle2D difNodeBounds = difNs.node.getBounds(); for(int k=0; k<nIn.nodeLayers.length; k++) { NodeInfo.LayerDetails nld = nIn.nodeLayers[k]; Sample ns = nld.ns; Rectangle2D nodeBounds = ns.node.getBounds(); if (polNodeBounds.getWidth() > polNodeBounds.getHeight()) { // horizontal layer nld.lWidth = nodeBounds.getMaxY() - (ns.parent.ly + ns.parent.hy)/2; nld.rWidth = (ns.parent.ly + ns.parent.hy)/2 - nodeBounds.getMinY(); nld.extendT = difNodeBounds.getMinX() - nodeBounds.getMinX(); } else { // vertical layer nld.lWidth = nodeBounds.getMaxX() - (ns.parent.lx + ns.parent.hx)/2; nld.rWidth = (ns.parent.lx + ns.parent.hx)/2 - nodeBounds.getMinX(); nld.extendT = difNodeBounds.getMinY() - nodeBounds.getMinY(); } nld.extendB = nld.extendT; } // add in electrical layers for diffusion NodeInfo.LayerDetails [] addedLayers = new NodeInfo.LayerDetails[nIn.nodeLayers.length+2]; for(int k=0; k<nIn.nodeLayers.length; k++) addedLayers[k] = nIn.nodeLayers[k]; NodeInfo.LayerDetails diff1 = nIn.nodeLayers[difIndex].duplicate(); NodeInfo.LayerDetails diff2 = nIn.nodeLayers[difIndex].duplicate(); addedLayers[nIn.nodeLayers.length] = diff1; addedLayers[nIn.nodeLayers.length+1] = diff2; nIn.nodeLayers = addedLayers; diff1.inLayers = diff2.inLayers = false; nIn.nodeLayers[difIndex].inElectricalLayers = false; diff1.portIndex = dif1Port; diff2.portIndex = dif2Port; // compute port extension factors nIn.specialValues = new double[6]; int layerCount = 0; for(Sample ns : firstEx.samples) { if (ns.values != null && ns.layer != Generic.tech.portNode && ns.layer != Generic.tech.cellCenterNode && ns.layer != null) layerCount++; } nIn.specialValues[0] = layerCount+1; if (nIn.nodePortDetails[dif1Port].values[0].getX().getAdder() > nIn.nodePortDetails[dif1Port].values[0].getY().getAdder()) { // vertical diffusion layer: determine polysilicon width nIn.specialValues[3] = (nIn.ySize * nIn.nodeLayers[polIndex].values[1].getY().getMultiplier() + nIn.nodeLayers[polIndex].values[1].getY().getAdder()) - (nIn.ySize * nIn.nodeLayers[polIndex].values[0].getY().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getY().getAdder()); // determine diffusion port rule nIn.specialValues[1] = (nIn.xSize * nIn.nodePortDetails[dif1Port].values[0].getX().getMultiplier() + nIn.nodePortDetails[dif1Port].values[0].getX().getAdder()) - (nIn.xSize * nIn.nodeLayers[difIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[difIndex].values[0].getX().getAdder()); nIn.specialValues[2] = (nIn.ySize * nIn.nodePortDetails[dif1Port].values[0].getY().getMultiplier() + nIn.nodePortDetails[dif1Port].values[0].getY().getAdder()) - (nIn.ySize * nIn.nodeLayers[polIndex].values[1].getY().getMultiplier() + nIn.nodeLayers[polIndex].values[1].getY().getAdder()); // determine polysilicon port rule nIn.specialValues[4] = (nIn.ySize * nIn.nodePortDetails[pol1Port].values[0].getY().getMultiplier() + nIn.nodePortDetails[pol1Port].values[0].getY().getAdder()) - (nIn.ySize * nIn.nodeLayers[polIndex].values[0].getY().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getY().getAdder()); nIn.specialValues[5] = (nIn.xSize * nIn.nodeLayers[difIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[difIndex].values[0].getX().getAdder()) - (nIn.xSize * nIn.nodePortDetails[pol1Port].values[1].getX().getMultiplier() + nIn.nodePortDetails[pol1Port].values[1].getX().getAdder()); // setup electrical layers for diffusion diff1.values[0].getY().setMultiplier(0); diff1.values[0].getY().setAdder(0); diff1.rWidth = 0; diff2.values[1].getY().setMultiplier(0); diff2.values[1].getY().setAdder(0); diff2.lWidth = 0; } else { // horizontal diffusion layer: determine polysilicon width nIn.specialValues[3] = (nIn.xSize * nIn.nodeLayers[polIndex].values[1].getX().getMultiplier() + nIn.nodeLayers[polIndex].values[1].getX().getAdder()) - (nIn.xSize * nIn.nodeLayers[polIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getX().getAdder()); // determine diffusion port rule nIn.specialValues[1] = (nIn.ySize * nIn.nodePortDetails[dif1Port].values[0].getY().getMultiplier() + nIn.nodePortDetails[dif1Port].values[0].getY().getAdder()) - (nIn.ySize * nIn.nodeLayers[difIndex].values[0].getY().getMultiplier() + nIn.nodeLayers[difIndex].values[0].getY().getAdder()); nIn.specialValues[2] = (nIn.xSize * nIn.nodeLayers[polIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getX().getAdder()) - (nIn.xSize * nIn.nodePortDetails[dif1Port].values[1].getX().getMultiplier() + nIn.nodePortDetails[dif1Port].values[1].getX().getAdder()); // determine polysilicon port rule nIn.specialValues[4] = (nIn.xSize * nIn.nodePortDetails[pol1Port].values[0].getX().getMultiplier() + nIn.nodePortDetails[pol1Port].values[0].getX().getAdder()) - (nIn.xSize * nIn.nodeLayers[polIndex].values[0].getX().getMultiplier() + nIn.nodeLayers[polIndex].values[0].getX().getAdder()); nIn.specialValues[5] = (nIn.ySize * nIn.nodeLayers[difIndex].values[0].getY().getMultiplier() + nIn.nodeLayers[difIndex].values[0].getY().getAdder()) - (nIn.ySize * nIn.nodePortDetails[pol1Port].values[1].getY().getMultiplier() + nIn.nodePortDetails[pol1Port].values[1].getY().getAdder()); // setup electrical layers for diffusion diff1.values[0].getX().setMultiplier(0); diff1.values[0].getX().setAdder(0); diff1.rWidth = 0; diff2.values[1].getX().setMultiplier(0); diff2.values[1].getX().setAdder(0); diff2.lWidth = 0; } } // extract width offset information from highlight box double lX = 0, hX = 0, lY = 0, hY = 0; boolean found = false; for(Sample ns : firstEx.samples) { if (ns.layer != null) continue; found = true; if (ns.values != null) { boolean err = false; if (ns.values[0].getX().getMultiplier() == -0.5) // left edge offset { lX = ns.values[0].getX().getAdder(); } else if (ns.values[0].getX().getMultiplier() == 0.5) { lX = nIn.xSize + ns.values[0].getX().getAdder(); } else err = true; if (ns.values[0].getY().getMultiplier() == -0.5) // bottom edge offset { lY = ns.values[0].getY().getAdder(); } else if (ns.values[0].getY().getMultiplier() == 0.5) { lY = nIn.ySize + ns.values[0].getY().getAdder();; } else err = true; if (ns.values[1].getX().getMultiplier() == 0.5) // right edge offset { hX = -ns.values[1].getX().getAdder(); } else if (ns.values[1].getX().getMultiplier() == -0.5) { hX = nIn.xSize - ns.values[1].getX().getAdder(); } else err = true; if (ns.values[1].getY().getMultiplier() == 0.5) // top edge offset { hY = -ns.values[1].getY().getAdder(); } else if (ns.values[1].getY().getMultiplier() == -0.5) { hY = nIn.ySize - ns.values[1].getY().getAdder(); } else err = true; if (err) { error.markError(ns.node, np, "Highlighting cannot scale from center"); return null; } } else { error.markError(ns.node, np, "No rule found for highlight"); return null; } } if (!found) { error.markError(null, np, "No highlight found"); return null; } if (lX != 0 || hX != 0 || lY != 0 || hY != 0) { nList[nodeIndex].so = new SizeOffset(lX, hX, lY, hY); } // // get grab point information // for(ns = neList.firstSample; ns != NOSAMPLE; ns = ns.nextSample) // if (ns.layer == Generic.tech.cellCenterNode) break; // if (ns != NOSAMPLE) // { // us_tecnode_grab[us_tecnode_grabcount++] = nodeindex+1; // us_tecnode_grab[us_tecnode_grabcount++] = (ns.node.geom.lowx + // ns.node.geom.highx - neList.lx - neList.hx)/2 * // el_curlib.lambda[tech.techindex] / lambda; // us_tecnode_grab[us_tecnode_grabcount++] = (ns.node.geom.lowy + // ns.node.geom.highy - neList.ly - neList.hy)/2 * // el_curlib.lambda[tech.techindex] / lambda; // us_tecflags |= HASGRAB; // } // advance the fill pointer nodeIndex++; } return nList; }
diff --git a/src/test/java/org/got5/tapestry5/jquery/test/services/AppModule.java b/src/test/java/org/got5/tapestry5/jquery/test/services/AppModule.java index 691653b3..9093855a 100644 --- a/src/test/java/org/got5/tapestry5/jquery/test/services/AppModule.java +++ b/src/test/java/org/got5/tapestry5/jquery/test/services/AppModule.java @@ -1,105 +1,105 @@ // // Copyright 2010 GOT5 (GO Tapestry 5) // // 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.got5.tapestry5.jquery.test.services; import org.apache.tapestry5.SymbolConstants; import org.apache.tapestry5.ioc.Configuration; import org.apache.tapestry5.ioc.MappedConfiguration; import org.apache.tapestry5.ioc.OrderedConfiguration; import org.apache.tapestry5.ioc.annotations.Contribute; import org.apache.tapestry5.ioc.annotations.SubModule; import org.apache.tapestry5.ioc.annotations.Symbol; import org.apache.tapestry5.ioc.services.ApplicationDefaults; import org.apache.tapestry5.ioc.services.SymbolProvider; import org.apache.tapestry5.json.JSONObject; import org.apache.tapestry5.services.ApplicationStateContribution; import org.apache.tapestry5.services.ApplicationStateCreator; import org.apache.tapestry5.services.MarkupRendererFilter; import org.got5.tapestry5.jquery.EffectsConstants; import org.got5.tapestry5.jquery.JQuerySymbolConstants; import org.got5.tapestry5.jquery.services.EffectsParam; import org.got5.tapestry5.jquery.services.JQueryModule; import org.got5.tapestry5.jquery.services.WidgetParams; import org.got5.tapestry5.jquery.test.data.IDataSource; import org.got5.tapestry5.jquery.test.data.MockDataSource; import org.got5.tapestry5.jquery.test.pages.GAnalyticsScriptsInjector; @SubModule(value = JQueryModule.class) public class AppModule { @Contribute(SymbolProvider.class) @ApplicationDefaults public static void contributeApplicationDefaults(MappedConfiguration<String, String> configuration) { configuration.add(SymbolConstants.SUPPORTED_LOCALES, "en,fr,de"); - configuration.add(SymbolConstants.PRODUCTION_MODE, "true"); + configuration.add(SymbolConstants.PRODUCTION_MODE, "false"); configuration.add(SymbolConstants.COMBINE_SCRIPTS, "false"); configuration.add(SymbolConstants.COMPRESS_WHITESPACE, "false"); configuration.add(SymbolConstants.GZIP_COMPRESSION_ENABLED, "false"); configuration.add(JQuerySymbolConstants.SUPPRESS_PROTOTYPE, "true"); configuration.add(JQuerySymbolConstants.JQUERY_ALIAS, "$"); configuration.add(JQuerySymbolConstants.JQUERY_UI_DEFAULT_THEME, "context:css/south-street/jquery-ui.css"); configuration.add("demo-src-dir",""); } @Contribute(WidgetParams.class) public void addWidgetParams(MappedConfiguration<String, JSONObject> configuration){ configuration.add("slider", new JSONObject().put("min", 5)); configuration.add("customdatepicker", new JSONObject("prevText","Previous Month")); } public static void contributeClasspathAssetAliasManager(MappedConfiguration<String, String> configuration) { configuration.add("demo-jquery", "static/css"); } public void contributeApplicationStateManager( MappedConfiguration<Class, ApplicationStateContribution> configuration) { ApplicationStateCreator<IDataSource> creator = new ApplicationStateCreator<IDataSource>() { public IDataSource create() { return new MockDataSource(); } }; configuration.add(IDataSource.class, new ApplicationStateContribution( "session", creator)); } @Contribute(EffectsParam.class) public void addEffectsFile(Configuration<String> configuration){ configuration.add(EffectsConstants.SHAKE); } public void contributeMarkupRenderer(OrderedConfiguration<MarkupRendererFilter> configuration, @Symbol("enableAnalytics") final boolean enableAnalytics) { if (enableAnalytics) { configuration.addInstance("GAnalyticsScript", GAnalyticsScriptsInjector.class, "after:DocumentLinker"); } } }
true
true
public static void contributeApplicationDefaults(MappedConfiguration<String, String> configuration) { configuration.add(SymbolConstants.SUPPORTED_LOCALES, "en,fr,de"); configuration.add(SymbolConstants.PRODUCTION_MODE, "true"); configuration.add(SymbolConstants.COMBINE_SCRIPTS, "false"); configuration.add(SymbolConstants.COMPRESS_WHITESPACE, "false"); configuration.add(SymbolConstants.GZIP_COMPRESSION_ENABLED, "false"); configuration.add(JQuerySymbolConstants.SUPPRESS_PROTOTYPE, "true"); configuration.add(JQuerySymbolConstants.JQUERY_ALIAS, "$"); configuration.add(JQuerySymbolConstants.JQUERY_UI_DEFAULT_THEME, "context:css/south-street/jquery-ui.css"); configuration.add("demo-src-dir",""); }
public static void contributeApplicationDefaults(MappedConfiguration<String, String> configuration) { configuration.add(SymbolConstants.SUPPORTED_LOCALES, "en,fr,de"); configuration.add(SymbolConstants.PRODUCTION_MODE, "false"); configuration.add(SymbolConstants.COMBINE_SCRIPTS, "false"); configuration.add(SymbolConstants.COMPRESS_WHITESPACE, "false"); configuration.add(SymbolConstants.GZIP_COMPRESSION_ENABLED, "false"); configuration.add(JQuerySymbolConstants.SUPPRESS_PROTOTYPE, "true"); configuration.add(JQuerySymbolConstants.JQUERY_ALIAS, "$"); configuration.add(JQuerySymbolConstants.JQUERY_UI_DEFAULT_THEME, "context:css/south-street/jquery-ui.css"); configuration.add("demo-src-dir",""); }
diff --git a/maven-scm-api/src/main/java/org/apache/maven/scm/ScmFileSet.java b/maven-scm-api/src/main/java/org/apache/maven/scm/ScmFileSet.java index 5668cffd..b3e70bf8 100644 --- a/maven-scm-api/src/main/java/org/apache/maven/scm/ScmFileSet.java +++ b/maven-scm-api/src/main/java/org/apache/maven/scm/ScmFileSet.java @@ -1,96 +1,96 @@ package org.apache.maven.scm; import org.codehaus.plexus.util.FileUtils; import java.io.File; import java.io.IOException; import java.util.Arrays; /* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <a href="mailto:[email protected]">Brett Porter</a> * @version $Id$ */ public class ScmFileSet { private static final String DEFAULT_EXCLUDES = "**/CVS/**,**/.svn/**"; private File basedir; /** List of files, all relative to the basedir. */ private File[] files; private static final File[] EMPTY_FILE_ARRAY = new File[0]; public ScmFileSet( File basedir ) { this( basedir, EMPTY_FILE_ARRAY ); } public ScmFileSet( File basedir, File file ) { this( basedir, new File[] { file } ); } public ScmFileSet( File basedir, String includes, String excludes ) throws IOException { this.basedir = basedir; if ( excludes != null && excludes.length() > 0 ) { - excludes += DEFAULT_EXCLUDES; + excludes += "," + DEFAULT_EXCLUDES; } else { excludes = DEFAULT_EXCLUDES; } // TODO: just use a list instead? files = (File[]) FileUtils.getFiles( basedir, includes, excludes, false ).toArray( EMPTY_FILE_ARRAY ); } public ScmFileSet( File basedir, File[] files ) { if ( basedir == null ) { throw new NullPointerException( "basedir must not be null" ); } if ( files == null ) { throw new NullPointerException( "files must not be null" ); } this.basedir = basedir; this.files = files; } public File getBasedir() { return basedir; } public File[] getFiles() { return this.files; } public String toString() { return "basedir = " + basedir + "; files = " + Arrays.asList(files); } }
true
true
public ScmFileSet( File basedir, String includes, String excludes ) throws IOException { this.basedir = basedir; if ( excludes != null && excludes.length() > 0 ) { excludes += DEFAULT_EXCLUDES; } else { excludes = DEFAULT_EXCLUDES; } // TODO: just use a list instead? files = (File[]) FileUtils.getFiles( basedir, includes, excludes, false ).toArray( EMPTY_FILE_ARRAY ); }
public ScmFileSet( File basedir, String includes, String excludes ) throws IOException { this.basedir = basedir; if ( excludes != null && excludes.length() > 0 ) { excludes += "," + DEFAULT_EXCLUDES; } else { excludes = DEFAULT_EXCLUDES; } // TODO: just use a list instead? files = (File[]) FileUtils.getFiles( basedir, includes, excludes, false ).toArray( EMPTY_FILE_ARRAY ); }
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/repository/RepositoriesViewContentProvider.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/repository/RepositoriesViewContentProvider.java index 672ab573..4c507321 100644 --- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/repository/RepositoriesViewContentProvider.java +++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/repository/RepositoriesViewContentProvider.java @@ -1,508 +1,508 @@ /******************************************************************************* * Copyright (c) 2010 SAP AG. * 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: * Mathias Kinzler (SAP AG) - initial implementation *******************************************************************************/ package org.eclipse.egit.ui.internal.repository; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Map.Entry; import org.eclipse.core.commands.IStateListener; import org.eclipse.core.commands.State; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.egit.core.RepositoryCache; import org.eclipse.egit.core.RepositoryUtil; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.internal.repository.tree.BranchHierarchyNode; import org.eclipse.egit.ui.internal.repository.tree.BranchesNode; import org.eclipse.egit.ui.internal.repository.tree.ErrorNode; import org.eclipse.egit.ui.internal.repository.tree.FetchNode; import org.eclipse.egit.ui.internal.repository.tree.FileNode; import org.eclipse.egit.ui.internal.repository.tree.FolderNode; import org.eclipse.egit.ui.internal.repository.tree.LocalNode; import org.eclipse.egit.ui.internal.repository.tree.AdditionalRefNode; import org.eclipse.egit.ui.internal.repository.tree.AdditionalRefsNode; import org.eclipse.egit.ui.internal.repository.tree.PushNode; import org.eclipse.egit.ui.internal.repository.tree.RefNode; import org.eclipse.egit.ui.internal.repository.tree.RemoteNode; import org.eclipse.egit.ui.internal.repository.tree.RemoteTrackingNode; import org.eclipse.egit.ui.internal.repository.tree.RemotesNode; import org.eclipse.egit.ui.internal.repository.tree.RepositoryNode; import org.eclipse.egit.ui.internal.repository.tree.RepositoryTreeNode; import org.eclipse.egit.ui.internal.repository.tree.SubmodulesNode; import org.eclipse.egit.ui.internal.repository.tree.TagNode; import org.eclipse.egit.ui.internal.repository.tree.TagsNode; import org.eclipse.egit.ui.internal.repository.tree.WorkingDirNode; import org.eclipse.egit.ui.internal.repository.tree.command.ToggleBranchHierarchyCommand; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.RefDatabase; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.submodule.SubmoduleWalk; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.commands.ICommandService; /** * Content Provider for the Git Repositories View */ public class RepositoriesViewContentProvider implements ITreeContentProvider, IStateListener { private final RepositoryCache repositoryCache = org.eclipse.egit.core.Activator .getDefault().getRepositoryCache(); private final State commandState; private boolean branchHierarchyMode = false; /** * Constructs this instance */ public RepositoriesViewContentProvider() { ICommandService srv = (ICommandService) PlatformUI.getWorkbench() .getService(ICommandService.class); commandState = srv.getCommand( ToggleBranchHierarchyCommand.ID) .getState(ToggleBranchHierarchyCommand.TOGGLE_STATE); commandState.addListener(this); try { this.branchHierarchyMode = ((Boolean) commandState.getValue()) .booleanValue(); } catch (Exception e) { Activator.handleError(e.getMessage(), e, false); } } @SuppressWarnings("unchecked") public Object[] getElements(Object inputElement) { List<RepositoryTreeNode> nodes = new ArrayList<RepositoryTreeNode>(); List<String> directories = new ArrayList<String>(); RepositoryUtil repositoryUtil = Activator.getDefault() .getRepositoryUtil(); if (inputElement instanceof Collection) { for (Iterator it = ((Collection) inputElement).iterator(); it .hasNext();) { Object next = it.next(); if (next instanceof RepositoryTreeNode) nodes.add((RepositoryTreeNode) next); else if (next instanceof String) directories.add((String) next); } } else if (inputElement instanceof IWorkspaceRoot) { directories.addAll(repositoryUtil.getConfiguredRepositories()); } for (String directory : directories) { try { File gitDir = new File(directory); if (gitDir.exists()) { RepositoryNode rNode = new RepositoryNode(null, repositoryCache.lookupRepository(gitDir)); nodes.add(rNode); } else repositoryUtil.removeDir(gitDir); } catch (IOException e) { // ignore for now } } Collections.sort(nodes); return nodes.toArray(); } public void dispose() { commandState.removeListener(this); } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // nothing } public Object[] getChildren(Object parentElement) { RepositoryTreeNode node = (RepositoryTreeNode) parentElement; Repository repo = node.getRepository(); switch (node.getType()) { case BRANCHES: { List<RepositoryTreeNode> nodes = new ArrayList<RepositoryTreeNode>(); nodes.add(new LocalNode(node, repo)); nodes.add(new RemoteTrackingNode(node, repo)); return nodes.toArray(); } case LOCAL: { if (branchHierarchyMode) { BranchHierarchyNode hierNode = new BranchHierarchyNode(node, repo, new Path(Constants.R_HEADS)); List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>(); try { for (IPath path : hierNode.getChildPaths()) { children.add(new BranchHierarchyNode(node, node .getRepository(), path)); } for (Ref ref : hierNode.getChildRefs()) { children.add(new RefNode(node, node.getRepository(), ref)); } - } catch (IOException e) { + } catch (Exception e) { return handleException(e, node); } return children.toArray(); } else { List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>(); try { for (Entry<String, Ref> refEntry : repo.getRefDatabase() .getRefs(Constants.R_HEADS).entrySet()) { if (!refEntry.getValue().isSymbolic()) refs.add(new RefNode(node, repo, refEntry .getValue())); } - } catch (IOException e) { + } catch (Exception e) { return handleException(e, node); } return refs.toArray(); } } case REMOTETRACKING: { if (branchHierarchyMode) { BranchHierarchyNode hierNode = new BranchHierarchyNode(node, repo, new Path(Constants.R_REMOTES)); List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>(); try { for (IPath path : hierNode.getChildPaths()) { children.add(new BranchHierarchyNode(node, node .getRepository(), path)); } for (Ref ref : hierNode.getChildRefs()) { children.add(new RefNode(node, node.getRepository(), ref)); } - } catch (IOException e) { + } catch (Exception e) { return handleException(e, node); } return children.toArray(); } else { List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>(); try { for (Entry<String, Ref> refEntry : repo.getRefDatabase() .getRefs(Constants.R_REMOTES).entrySet()) { if (!refEntry.getValue().isSymbolic()) refs.add(new RefNode(node, repo, refEntry .getValue())); } - } catch (IOException e) { + } catch (Exception e) { return handleException(e, node); } return refs.toArray(); } } case BRANCHHIERARCHY: { BranchHierarchyNode hierNode = (BranchHierarchyNode) node; List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>(); try { for (IPath path : hierNode.getChildPaths()) { children.add(new BranchHierarchyNode(node, node .getRepository(), path)); } for (Ref ref : hierNode.getChildRefs()) { children.add(new RefNode(node, node.getRepository(), ref)); } } catch (IOException e) { return handleException(e, node); } return children.toArray(); } case TAGS: { List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>(); try { for (Entry<String, Ref> refEntry : repo.getRefDatabase() .getRefs(Constants.R_TAGS).entrySet()) { refs.add(new TagNode(node, repo, refEntry.getValue())); } } catch (IOException e) { return handleException(e, node); } return refs.toArray(); } case ADDITIONALREFS: { List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>(); try { for (Entry<String, Ref> refEntry : repo.getRefDatabase() .getRefs(RefDatabase.ALL).entrySet()) { String name=refEntry.getKey(); if (!(name.startsWith(Constants.R_HEADS) || name.startsWith(Constants.R_TAGS)|| name.startsWith(Constants.R_REMOTES))) refs.add(new AdditionalRefNode(node, repo, refEntry .getValue())); } for (Ref r : repo.getRefDatabase().getAdditionalRefs()) refs.add(new AdditionalRefNode(node, repo, r)); - } catch (IOException e) { + } catch (Exception e) { return handleException(e, node); } return refs.toArray(); } case REMOTES: { List<RepositoryTreeNode<String>> remotes = new ArrayList<RepositoryTreeNode<String>>(); Repository rep = node.getRepository(); Set<String> configNames = rep.getConfig().getSubsections( RepositoriesView.REMOTE); for (String configName : configNames) { remotes.add(new RemoteNode(node, repo, configName)); } return remotes.toArray(); } case REPO: { List<RepositoryTreeNode<? extends Object>> nodeList = new ArrayList<RepositoryTreeNode<? extends Object>>(); nodeList.add(new BranchesNode(node, repo)); nodeList.add(new TagsNode(node, repo)); nodeList.add(new AdditionalRefsNode(node, repo)); nodeList.add(new WorkingDirNode(node, repo)); nodeList.add(new RemotesNode(node, repo)); if (!repo.isBare()) nodeList.add(new SubmodulesNode(node, repo)); return nodeList.toArray(); } case WORKINGDIR: { List<RepositoryTreeNode<File>> children = new ArrayList<RepositoryTreeNode<File>>(); if (node.getRepository().isBare()) return children.toArray(); File workingDir = repo.getWorkTree(); if (workingDir == null || !workingDir.exists()) return children.toArray(); File[] childFiles = workingDir.listFiles(); Arrays.sort(childFiles, new Comparator<File>() { public int compare(File o1, File o2) { if (o1.isDirectory()) { if (o2.isDirectory()) { return o1.compareTo(o2); } return -1; } else if (o2.isDirectory()) { return 1; } return o1.compareTo(o2); } }); for (File file : childFiles) { if (file.isDirectory()) { children.add(new FolderNode(node, repo, file)); } else { children.add(new FileNode(node, repo, file)); } } return children.toArray(); } case FOLDER: { List<RepositoryTreeNode<File>> children = new ArrayList<RepositoryTreeNode<File>>(); File parent = ((File) node.getObject()); File[] childFiles = parent.listFiles(); Arrays.sort(childFiles, new Comparator<File>() { public int compare(File o1, File o2) { if (o1.isDirectory()) { if (o2.isDirectory()) { return o1.compareTo(o2); } return -1; } else if (o2.isDirectory()) { return 1; } return o1.compareTo(o2); } }); for (File file : childFiles) { if (file.isDirectory()) { children.add(new FolderNode(node, repo, file)); } else { children.add(new FileNode(node, repo, file)); } } return children.toArray(); } case REMOTE: { List<RepositoryTreeNode<String>> children = new ArrayList<RepositoryTreeNode<String>>(); String remoteName = (String) node.getObject(); RemoteConfig rc; try { rc = new RemoteConfig(node.getRepository().getConfig(), remoteName); } catch (URISyntaxException e) { return handleException(e, node); } if (!rc.getURIs().isEmpty()) children.add(new FetchNode(node, node.getRepository(), rc .getURIs().get(0).toPrivateString())); int uriCount = rc.getPushURIs().size(); if (uriCount == 0 && !rc.getURIs().isEmpty()) uriCount++; // show push if either a fetch or push URI is specified and // at least one push specification if (uriCount > 0) { URIish firstUri; if (!rc.getPushURIs().isEmpty()) firstUri = rc.getPushURIs().get(0); else firstUri = rc.getURIs().get(0); if (uriCount == 1) children.add(new PushNode(node, node.getRepository(), firstUri.toPrivateString())); else children.add(new PushNode(node, node.getRepository(), firstUri.toPrivateString() + "...")); //$NON-NLS-1$ } return children.toArray(); } case SUBMODULES: List<RepositoryNode> children = new ArrayList<RepositoryNode>(); try { SubmoduleWalk walk = SubmoduleWalk.forIndex(node .getRepository()); while (walk.next()) { Repository subRepo = walk.getRepository(); if (subRepo != null) children.add(new RepositoryNode(node, subRepo)); } } catch (IOException e) { handleException(e, node); } return children.toArray(); case FILE: // fall through case REF: // fall through case PUSH: // fall through case TAG: // fall through case FETCH: // fall through case ERROR: // fall through case ADDITIONALREF: return null; } return null; } private Object[] handleException(Exception e, RepositoryTreeNode parentNode) { Activator.handleError(e.getMessage(), e, false); // add a node indicating that there was an Exception String message = e.getMessage(); if (message == null) return new Object[] { new ErrorNode(parentNode, parentNode .getRepository(), UIText.RepositoriesViewContentProvider_ExceptionNodeText) }; else return new Object[] { new ErrorNode(parentNode, parentNode .getRepository(), message) }; } public Object getParent(Object element) { if (element instanceof RepositoryTreeNode) return ((RepositoryTreeNode) element).getParent(); return null; } public boolean hasChildren(Object element) { // for some of the nodes we can optimize this call RepositoryTreeNode node = (RepositoryTreeNode) element; Repository repo = node.getRepository(); switch (node.getType()) { case BRANCHES: return true; case REPO: return true; case ADDITIONALREFS: return true; case SUBMODULES: return true; case TAGS: try { return !repo.getRefDatabase().getRefs(Constants.R_TAGS) .isEmpty(); } catch (IOException e) { return true; } case WORKINGDIR: if (node.getRepository().isBare()) return false; File workingDir = repo.getWorkTree(); if (workingDir == null || !workingDir.exists()) return false; return workingDir.listFiles().length > 0; default: Object[] children = getChildren(element); return children != null && children.length > 0; } } public void handleStateChange(State state, Object oldValue) { try { this.branchHierarchyMode = ((Boolean) state.getValue()) .booleanValue(); } catch (Exception e) { Activator.handleError(e.getMessage(), e, false); } } }
false
true
public Object[] getChildren(Object parentElement) { RepositoryTreeNode node = (RepositoryTreeNode) parentElement; Repository repo = node.getRepository(); switch (node.getType()) { case BRANCHES: { List<RepositoryTreeNode> nodes = new ArrayList<RepositoryTreeNode>(); nodes.add(new LocalNode(node, repo)); nodes.add(new RemoteTrackingNode(node, repo)); return nodes.toArray(); } case LOCAL: { if (branchHierarchyMode) { BranchHierarchyNode hierNode = new BranchHierarchyNode(node, repo, new Path(Constants.R_HEADS)); List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>(); try { for (IPath path : hierNode.getChildPaths()) { children.add(new BranchHierarchyNode(node, node .getRepository(), path)); } for (Ref ref : hierNode.getChildRefs()) { children.add(new RefNode(node, node.getRepository(), ref)); } } catch (IOException e) { return handleException(e, node); } return children.toArray(); } else { List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>(); try { for (Entry<String, Ref> refEntry : repo.getRefDatabase() .getRefs(Constants.R_HEADS).entrySet()) { if (!refEntry.getValue().isSymbolic()) refs.add(new RefNode(node, repo, refEntry .getValue())); } } catch (IOException e) { return handleException(e, node); } return refs.toArray(); } } case REMOTETRACKING: { if (branchHierarchyMode) { BranchHierarchyNode hierNode = new BranchHierarchyNode(node, repo, new Path(Constants.R_REMOTES)); List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>(); try { for (IPath path : hierNode.getChildPaths()) { children.add(new BranchHierarchyNode(node, node .getRepository(), path)); } for (Ref ref : hierNode.getChildRefs()) { children.add(new RefNode(node, node.getRepository(), ref)); } } catch (IOException e) { return handleException(e, node); } return children.toArray(); } else { List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>(); try { for (Entry<String, Ref> refEntry : repo.getRefDatabase() .getRefs(Constants.R_REMOTES).entrySet()) { if (!refEntry.getValue().isSymbolic()) refs.add(new RefNode(node, repo, refEntry .getValue())); } } catch (IOException e) { return handleException(e, node); } return refs.toArray(); } } case BRANCHHIERARCHY: { BranchHierarchyNode hierNode = (BranchHierarchyNode) node; List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>(); try { for (IPath path : hierNode.getChildPaths()) { children.add(new BranchHierarchyNode(node, node .getRepository(), path)); } for (Ref ref : hierNode.getChildRefs()) { children.add(new RefNode(node, node.getRepository(), ref)); } } catch (IOException e) { return handleException(e, node); } return children.toArray(); } case TAGS: { List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>(); try { for (Entry<String, Ref> refEntry : repo.getRefDatabase() .getRefs(Constants.R_TAGS).entrySet()) { refs.add(new TagNode(node, repo, refEntry.getValue())); } } catch (IOException e) { return handleException(e, node); } return refs.toArray(); } case ADDITIONALREFS: { List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>(); try { for (Entry<String, Ref> refEntry : repo.getRefDatabase() .getRefs(RefDatabase.ALL).entrySet()) { String name=refEntry.getKey(); if (!(name.startsWith(Constants.R_HEADS) || name.startsWith(Constants.R_TAGS)|| name.startsWith(Constants.R_REMOTES))) refs.add(new AdditionalRefNode(node, repo, refEntry .getValue())); } for (Ref r : repo.getRefDatabase().getAdditionalRefs()) refs.add(new AdditionalRefNode(node, repo, r)); } catch (IOException e) { return handleException(e, node); } return refs.toArray(); } case REMOTES: { List<RepositoryTreeNode<String>> remotes = new ArrayList<RepositoryTreeNode<String>>(); Repository rep = node.getRepository(); Set<String> configNames = rep.getConfig().getSubsections( RepositoriesView.REMOTE); for (String configName : configNames) { remotes.add(new RemoteNode(node, repo, configName)); } return remotes.toArray(); } case REPO: { List<RepositoryTreeNode<? extends Object>> nodeList = new ArrayList<RepositoryTreeNode<? extends Object>>(); nodeList.add(new BranchesNode(node, repo)); nodeList.add(new TagsNode(node, repo)); nodeList.add(new AdditionalRefsNode(node, repo)); nodeList.add(new WorkingDirNode(node, repo)); nodeList.add(new RemotesNode(node, repo)); if (!repo.isBare()) nodeList.add(new SubmodulesNode(node, repo)); return nodeList.toArray(); } case WORKINGDIR: { List<RepositoryTreeNode<File>> children = new ArrayList<RepositoryTreeNode<File>>(); if (node.getRepository().isBare()) return children.toArray(); File workingDir = repo.getWorkTree(); if (workingDir == null || !workingDir.exists()) return children.toArray(); File[] childFiles = workingDir.listFiles(); Arrays.sort(childFiles, new Comparator<File>() { public int compare(File o1, File o2) { if (o1.isDirectory()) { if (o2.isDirectory()) { return o1.compareTo(o2); } return -1; } else if (o2.isDirectory()) { return 1; } return o1.compareTo(o2); } }); for (File file : childFiles) { if (file.isDirectory()) { children.add(new FolderNode(node, repo, file)); } else { children.add(new FileNode(node, repo, file)); } } return children.toArray(); } case FOLDER: { List<RepositoryTreeNode<File>> children = new ArrayList<RepositoryTreeNode<File>>(); File parent = ((File) node.getObject()); File[] childFiles = parent.listFiles(); Arrays.sort(childFiles, new Comparator<File>() { public int compare(File o1, File o2) { if (o1.isDirectory()) { if (o2.isDirectory()) { return o1.compareTo(o2); } return -1; } else if (o2.isDirectory()) { return 1; } return o1.compareTo(o2); } }); for (File file : childFiles) { if (file.isDirectory()) { children.add(new FolderNode(node, repo, file)); } else { children.add(new FileNode(node, repo, file)); } } return children.toArray(); } case REMOTE: { List<RepositoryTreeNode<String>> children = new ArrayList<RepositoryTreeNode<String>>(); String remoteName = (String) node.getObject(); RemoteConfig rc; try { rc = new RemoteConfig(node.getRepository().getConfig(), remoteName); } catch (URISyntaxException e) { return handleException(e, node); } if (!rc.getURIs().isEmpty()) children.add(new FetchNode(node, node.getRepository(), rc .getURIs().get(0).toPrivateString())); int uriCount = rc.getPushURIs().size(); if (uriCount == 0 && !rc.getURIs().isEmpty()) uriCount++; // show push if either a fetch or push URI is specified and // at least one push specification if (uriCount > 0) { URIish firstUri; if (!rc.getPushURIs().isEmpty()) firstUri = rc.getPushURIs().get(0); else firstUri = rc.getURIs().get(0); if (uriCount == 1) children.add(new PushNode(node, node.getRepository(), firstUri.toPrivateString())); else children.add(new PushNode(node, node.getRepository(), firstUri.toPrivateString() + "...")); //$NON-NLS-1$ } return children.toArray(); } case SUBMODULES: List<RepositoryNode> children = new ArrayList<RepositoryNode>(); try { SubmoduleWalk walk = SubmoduleWalk.forIndex(node .getRepository()); while (walk.next()) { Repository subRepo = walk.getRepository(); if (subRepo != null) children.add(new RepositoryNode(node, subRepo)); } } catch (IOException e) { handleException(e, node); } return children.toArray(); case FILE: // fall through case REF: // fall through case PUSH: // fall through case TAG: // fall through case FETCH: // fall through case ERROR: // fall through case ADDITIONALREF: return null; } return null; }
public Object[] getChildren(Object parentElement) { RepositoryTreeNode node = (RepositoryTreeNode) parentElement; Repository repo = node.getRepository(); switch (node.getType()) { case BRANCHES: { List<RepositoryTreeNode> nodes = new ArrayList<RepositoryTreeNode>(); nodes.add(new LocalNode(node, repo)); nodes.add(new RemoteTrackingNode(node, repo)); return nodes.toArray(); } case LOCAL: { if (branchHierarchyMode) { BranchHierarchyNode hierNode = new BranchHierarchyNode(node, repo, new Path(Constants.R_HEADS)); List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>(); try { for (IPath path : hierNode.getChildPaths()) { children.add(new BranchHierarchyNode(node, node .getRepository(), path)); } for (Ref ref : hierNode.getChildRefs()) { children.add(new RefNode(node, node.getRepository(), ref)); } } catch (Exception e) { return handleException(e, node); } return children.toArray(); } else { List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>(); try { for (Entry<String, Ref> refEntry : repo.getRefDatabase() .getRefs(Constants.R_HEADS).entrySet()) { if (!refEntry.getValue().isSymbolic()) refs.add(new RefNode(node, repo, refEntry .getValue())); } } catch (Exception e) { return handleException(e, node); } return refs.toArray(); } } case REMOTETRACKING: { if (branchHierarchyMode) { BranchHierarchyNode hierNode = new BranchHierarchyNode(node, repo, new Path(Constants.R_REMOTES)); List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>(); try { for (IPath path : hierNode.getChildPaths()) { children.add(new BranchHierarchyNode(node, node .getRepository(), path)); } for (Ref ref : hierNode.getChildRefs()) { children.add(new RefNode(node, node.getRepository(), ref)); } } catch (Exception e) { return handleException(e, node); } return children.toArray(); } else { List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>(); try { for (Entry<String, Ref> refEntry : repo.getRefDatabase() .getRefs(Constants.R_REMOTES).entrySet()) { if (!refEntry.getValue().isSymbolic()) refs.add(new RefNode(node, repo, refEntry .getValue())); } } catch (Exception e) { return handleException(e, node); } return refs.toArray(); } } case BRANCHHIERARCHY: { BranchHierarchyNode hierNode = (BranchHierarchyNode) node; List<RepositoryTreeNode> children = new ArrayList<RepositoryTreeNode>(); try { for (IPath path : hierNode.getChildPaths()) { children.add(new BranchHierarchyNode(node, node .getRepository(), path)); } for (Ref ref : hierNode.getChildRefs()) { children.add(new RefNode(node, node.getRepository(), ref)); } } catch (IOException e) { return handleException(e, node); } return children.toArray(); } case TAGS: { List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>(); try { for (Entry<String, Ref> refEntry : repo.getRefDatabase() .getRefs(Constants.R_TAGS).entrySet()) { refs.add(new TagNode(node, repo, refEntry.getValue())); } } catch (IOException e) { return handleException(e, node); } return refs.toArray(); } case ADDITIONALREFS: { List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>(); try { for (Entry<String, Ref> refEntry : repo.getRefDatabase() .getRefs(RefDatabase.ALL).entrySet()) { String name=refEntry.getKey(); if (!(name.startsWith(Constants.R_HEADS) || name.startsWith(Constants.R_TAGS)|| name.startsWith(Constants.R_REMOTES))) refs.add(new AdditionalRefNode(node, repo, refEntry .getValue())); } for (Ref r : repo.getRefDatabase().getAdditionalRefs()) refs.add(new AdditionalRefNode(node, repo, r)); } catch (Exception e) { return handleException(e, node); } return refs.toArray(); } case REMOTES: { List<RepositoryTreeNode<String>> remotes = new ArrayList<RepositoryTreeNode<String>>(); Repository rep = node.getRepository(); Set<String> configNames = rep.getConfig().getSubsections( RepositoriesView.REMOTE); for (String configName : configNames) { remotes.add(new RemoteNode(node, repo, configName)); } return remotes.toArray(); } case REPO: { List<RepositoryTreeNode<? extends Object>> nodeList = new ArrayList<RepositoryTreeNode<? extends Object>>(); nodeList.add(new BranchesNode(node, repo)); nodeList.add(new TagsNode(node, repo)); nodeList.add(new AdditionalRefsNode(node, repo)); nodeList.add(new WorkingDirNode(node, repo)); nodeList.add(new RemotesNode(node, repo)); if (!repo.isBare()) nodeList.add(new SubmodulesNode(node, repo)); return nodeList.toArray(); } case WORKINGDIR: { List<RepositoryTreeNode<File>> children = new ArrayList<RepositoryTreeNode<File>>(); if (node.getRepository().isBare()) return children.toArray(); File workingDir = repo.getWorkTree(); if (workingDir == null || !workingDir.exists()) return children.toArray(); File[] childFiles = workingDir.listFiles(); Arrays.sort(childFiles, new Comparator<File>() { public int compare(File o1, File o2) { if (o1.isDirectory()) { if (o2.isDirectory()) { return o1.compareTo(o2); } return -1; } else if (o2.isDirectory()) { return 1; } return o1.compareTo(o2); } }); for (File file : childFiles) { if (file.isDirectory()) { children.add(new FolderNode(node, repo, file)); } else { children.add(new FileNode(node, repo, file)); } } return children.toArray(); } case FOLDER: { List<RepositoryTreeNode<File>> children = new ArrayList<RepositoryTreeNode<File>>(); File parent = ((File) node.getObject()); File[] childFiles = parent.listFiles(); Arrays.sort(childFiles, new Comparator<File>() { public int compare(File o1, File o2) { if (o1.isDirectory()) { if (o2.isDirectory()) { return o1.compareTo(o2); } return -1; } else if (o2.isDirectory()) { return 1; } return o1.compareTo(o2); } }); for (File file : childFiles) { if (file.isDirectory()) { children.add(new FolderNode(node, repo, file)); } else { children.add(new FileNode(node, repo, file)); } } return children.toArray(); } case REMOTE: { List<RepositoryTreeNode<String>> children = new ArrayList<RepositoryTreeNode<String>>(); String remoteName = (String) node.getObject(); RemoteConfig rc; try { rc = new RemoteConfig(node.getRepository().getConfig(), remoteName); } catch (URISyntaxException e) { return handleException(e, node); } if (!rc.getURIs().isEmpty()) children.add(new FetchNode(node, node.getRepository(), rc .getURIs().get(0).toPrivateString())); int uriCount = rc.getPushURIs().size(); if (uriCount == 0 && !rc.getURIs().isEmpty()) uriCount++; // show push if either a fetch or push URI is specified and // at least one push specification if (uriCount > 0) { URIish firstUri; if (!rc.getPushURIs().isEmpty()) firstUri = rc.getPushURIs().get(0); else firstUri = rc.getURIs().get(0); if (uriCount == 1) children.add(new PushNode(node, node.getRepository(), firstUri.toPrivateString())); else children.add(new PushNode(node, node.getRepository(), firstUri.toPrivateString() + "...")); //$NON-NLS-1$ } return children.toArray(); } case SUBMODULES: List<RepositoryNode> children = new ArrayList<RepositoryNode>(); try { SubmoduleWalk walk = SubmoduleWalk.forIndex(node .getRepository()); while (walk.next()) { Repository subRepo = walk.getRepository(); if (subRepo != null) children.add(new RepositoryNode(node, subRepo)); } } catch (IOException e) { handleException(e, node); } return children.toArray(); case FILE: // fall through case REF: // fall through case PUSH: // fall through case TAG: // fall through case FETCH: // fall through case ERROR: // fall through case ADDITIONALREF: return null; } return null; }
diff --git a/webapps/cockpit-webapp-fox/src/main/java/com/camunda/fox/cockpit/demo/deployer/FoxPlatformDemoDataDeployer.java b/webapps/cockpit-webapp-fox/src/main/java/com/camunda/fox/cockpit/demo/deployer/FoxPlatformDemoDataDeployer.java index d57986e52..482dec9a8 100644 --- a/webapps/cockpit-webapp-fox/src/main/java/com/camunda/fox/cockpit/demo/deployer/FoxPlatformDemoDataDeployer.java +++ b/webapps/cockpit-webapp-fox/src/main/java/com/camunda/fox/cockpit/demo/deployer/FoxPlatformDemoDataDeployer.java @@ -1,37 +1,37 @@ package com.camunda.fox.cockpit.demo.deployer; import javax.ejb.EJB; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Alternative; import com.camunda.fox.cockpit.demo.DemoDataDeployer; import com.camunda.fox.platform.api.ProcessArchiveService; @ApplicationScoped @Alternative public class FoxPlatformDemoDataDeployer implements DemoDataDeployer { // lookup the process archive service using the portable global jndi name @EJB(lookup= "java:global/" + "camunda-fox-platform/" + "process-engine/" + "PlatformService!com.camunda.fox.platform.api.ProcessArchiveService") protected ProcessArchiveService processEngineService; // lookup the process archive context executor @EJB protected ProcessArchiveContextExecutor processArchiveContextExecutorBean; private DemoDataProcessArchiveImpl demoDataProcessArchiveImpl; - public void deployDemoData() { + public String deployDemoData() { demoDataProcessArchiveImpl = new DemoDataProcessArchiveImpl(processArchiveContextExecutorBean); - processEngineService.installProcessArchive(demoDataProcessArchiveImpl); + return processEngineService.installProcessArchive(demoDataProcessArchiveImpl).getProcessEngineDeploymentId(); } public void undeployDemoData() { processEngineService.unInstallProcessArchive(demoDataProcessArchiveImpl); } }
false
true
public void deployDemoData() { demoDataProcessArchiveImpl = new DemoDataProcessArchiveImpl(processArchiveContextExecutorBean); processEngineService.installProcessArchive(demoDataProcessArchiveImpl); }
public String deployDemoData() { demoDataProcessArchiveImpl = new DemoDataProcessArchiveImpl(processArchiveContextExecutorBean); return processEngineService.installProcessArchive(demoDataProcessArchiveImpl).getProcessEngineDeploymentId(); }
diff --git a/modules/foundation/xremwin/src/classes/org/jdesktop/wonderland/modules/xremwin/client/cell/AppCellXrw.java b/modules/foundation/xremwin/src/classes/org/jdesktop/wonderland/modules/xremwin/client/cell/AppCellXrw.java index 52549e9fc..408fd09e4 100644 --- a/modules/foundation/xremwin/src/classes/org/jdesktop/wonderland/modules/xremwin/client/cell/AppCellXrw.java +++ b/modules/foundation/xremwin/src/classes/org/jdesktop/wonderland/modules/xremwin/client/cell/AppCellXrw.java @@ -1,90 +1,89 @@ /** * 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.modules.xremwin.client.cell; import org.jdesktop.wonderland.client.cell.CellCache; import org.jdesktop.wonderland.client.comms.WonderlandSession; import org.jdesktop.wonderland.common.ExperimentalAPI; import org.jdesktop.wonderland.common.cell.CellID; import org.jdesktop.wonderland.modules.appbase.client.AppConventional; import org.jdesktop.wonderland.modules.appbase.client.ProcessReporterFactory; import org.jdesktop.wonderland.modules.appbase.client.cell.AppConventionalCell; import org.jdesktop.wonderland.modules.xremwin.client.AppXrw; import org.jdesktop.wonderland.modules.xremwin.client.AppXrwMaster; import org.jdesktop.wonderland.modules.xremwin.client.AppXrwSlave; import org.jdesktop.wonderland.modules.xremwin.client.AppXrwConnectionInfo; /** * An Xremwin client-side app cell. * * @author deronj */ @ExperimentalAPI public class AppCellXrw extends AppConventionalCell { /** The session used by the cell cache of this cell to connect to the server */ private WonderlandSession session; /** * Create an instance of AppCellXrw. * * @param cellID The ID of the cell. * @param cellCache the cell cache which instantiated, and owns, this cell. */ public AppCellXrw(CellID cellID, CellCache cellCache) { super(cellID, cellCache); session = cellCache.getSession(); } /** * {@inheritDoc} */ protected String startMaster(String appName, String command, boolean initInBestView) { try { app = new AppXrwMaster(appName, command, pixelScale, ProcessReporterFactory.getFactory().create(appName), session); } catch (InstantiationException ex) { return null; } - ((AppConventional) app).setInitInBestView(initInBestView); ((AppConventional) app).addDisplayer(this); // Now it is safe to enable the master client loop ((AppXrw)app).getClient().enable(); return ((AppXrwMaster)app).getConnectionInfo().toString(); } /** * {@inheritDoc} */ protected boolean startSlave(String connectionInfo) { try { app = new AppXrwSlave(appName, pixelScale, ProcessReporterFactory.getFactory().create(appName), new AppXrwConnectionInfo(connectionInfo), session, this); } catch (InstantiationException ex) { ex.printStackTrace(); return false; } return true; } }
true
true
protected String startMaster(String appName, String command, boolean initInBestView) { try { app = new AppXrwMaster(appName, command, pixelScale, ProcessReporterFactory.getFactory().create(appName), session); } catch (InstantiationException ex) { return null; } ((AppConventional) app).setInitInBestView(initInBestView); ((AppConventional) app).addDisplayer(this); // Now it is safe to enable the master client loop ((AppXrw)app).getClient().enable(); return ((AppXrwMaster)app).getConnectionInfo().toString(); }
protected String startMaster(String appName, String command, boolean initInBestView) { try { app = new AppXrwMaster(appName, command, pixelScale, ProcessReporterFactory.getFactory().create(appName), session); } catch (InstantiationException ex) { return null; } ((AppConventional) app).addDisplayer(this); // Now it is safe to enable the master client loop ((AppXrw)app).getClient().enable(); return ((AppXrwMaster)app).getConnectionInfo().toString(); }
diff --git a/java/kouchat/src/net/usikkert/kouchat/net/MessageParser.java b/java/kouchat/src/net/usikkert/kouchat/net/MessageParser.java index 56bc1ccd..ba5a6528 100644 --- a/java/kouchat/src/net/usikkert/kouchat/net/MessageParser.java +++ b/java/kouchat/src/net/usikkert/kouchat/net/MessageParser.java @@ -1,287 +1,287 @@ /*************************************************************************** * Copyright 2006-2007 by Christian Ihle * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ package net.usikkert.kouchat.net; import java.util.logging.Level; import java.util.logging.Logger; import net.usikkert.kouchat.event.ReceiverListener; import net.usikkert.kouchat.misc.NickDTO; import net.usikkert.kouchat.misc.Settings; public class MessageParser implements ReceiverListener { private static Logger log = Logger.getLogger( MessageParser.class.getName() ); private MessageReceiver receiver; private MessageResponder responder; private Settings settings; private boolean loggedOn; public MessageParser( MessageResponder responder ) { this.responder = responder; settings = Settings.getSettings(); receiver = new MessageReceiver(); receiver.registerReceiverListener( this ); } public void start() { receiver.startReceiver(); } public void stop() { receiver.stopReceiver(); } public boolean restart() { return receiver.restartReceiver(); } @Override public void messageArrived( String message, String ipAddress ) { if ( settings.isDebug() ) System.out.println( message ); try { int exclamation = message.indexOf( "!" ); int hash = message.indexOf( "#" ); int colon = message.indexOf( ":" ); int msgCode = Integer.parseInt( message.substring( 0, exclamation ) ); String type = message.substring( exclamation +1, hash ); String msgNick = message.substring( hash +1, colon ); String msg = message.substring( colon +1, message.length() ); NickDTO tempme = settings.getMe(); if ( msgCode != tempme.getCode() && loggedOn ) { if ( type.equals( "MSG" ) ) { int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); int rgb = Integer.parseInt( msg.substring( leftBracket +1, rightBracket ) ); responder.messageArrived( msgCode, msg.substring( rightBracket +1, msg.length() ), rgb ); } else if ( type.equals( "LOGON" ) ) { NickDTO newUser = new NickDTO( msgNick, msgCode ); newUser.setIpAddress( ipAddress ); newUser.setLastIdle( System.currentTimeMillis() ); responder.userLogOn( newUser ); } else if ( type.equals( "EXPOSING" ) ) { NickDTO user = new NickDTO( msgNick, msgCode ); user.setIpAddress( ipAddress ); user.setAwayMsg( msg ); if ( msg.length() > 0 ) user.setAway( true ); user.setLastIdle( System.currentTimeMillis() ); responder.userExposing( user ); } else if ( type.equals( "LOGOFF" ) ) { responder.userLogOff( msgCode ); } else if ( type.equals( "AWAY" ) ) { responder.awayChanged( msgCode, true, msg ); } else if ( type.equals( "BACK" ) ) { responder.awayChanged( msgCode, false, "" ); } else if ( type.equals( "EXPOSE" ) ) { responder.exposeRequested(); } else if ( type.equals( "NICKCRASH" ) ) { if ( tempme.getNick().equals( msg ) ) { responder.nickCrash(); } } else if ( type.equals( "WRITING" ) ) { responder.writingChanged( msgCode, true ); } else if ( type.equals( "STOPPEDWRITING" ) ) { responder.writingChanged( msgCode, false ); } else if ( type.equals( "GETTOPIC" ) ) { responder.topicRequested(); } else if ( type.equals( "TOPIC" ) ) { int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); if ( rightBracket != -1 && leftBracket != -1 ) { String theNick = msg.substring( leftPara +1, rightPara ); long theTime = Long.parseLong( msg.substring( leftBracket +1, rightBracket ) ); String theTopic = null; if ( msg.length() > rightBracket + 1 ) { theTopic = msg.substring( rightBracket +1, msg.length() ); } responder.topicChanged( msgCode, theTopic, theNick, theTime ); } } else if ( type.equals( "NICK" ) ) { responder.nickChanged( msgCode, msgNick ); } else if ( type.equals( "IDLE" ) ) { responder.userIdle( msgCode, ipAddress ); } else if ( type.equals( "SENDFILEACCEPT" ) ) { int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); int fileCode = Integer.parseInt( msg.substring( leftPara +1, rightPara ) ); if ( fileCode == tempme.getCode() ) { int leftCurly = msg.indexOf( "{" ); int rightCurly = msg.indexOf( "}" ); int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); int port = Integer.parseInt( msg.substring( leftBracket +1, rightBracket ) ); int fileHash = Integer.parseInt( msg.substring( leftCurly +1, rightCurly ) ); String fileName = msg.substring( rightCurly +1, msg.length() ); responder.fileSendAccepted( msgCode, fileName, fileHash, port ); } } else if ( type.equals( "SENDFILEABORT" ) ) { int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); int fileCode = Integer.parseInt( msg.substring( leftPara +1, rightPara ) ); if ( fileCode == tempme.getCode() ) { int leftCurly = msg.indexOf( "{" ); int rightCurly = msg.indexOf( "}" ); String fileName = msg.substring( rightCurly +1, msg.length() ); int fileHash = Integer.parseInt( msg.substring( leftCurly +1, rightCurly ) ); responder.fileSendAborted( msgCode, fileName, fileHash ); } } else if ( type.equals( "SENDFILE" ) ) { int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); int fileCode = Integer.parseInt( msg.substring( leftPara +1, rightPara ) ); if ( fileCode == tempme.getCode() ) { int leftCurly = msg.indexOf( "{" ); int rightCurly = msg.indexOf( "}" ); int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); long byteSize = Long.parseLong( msg.substring( leftBracket +1, rightBracket ) ); String fileName = msg.substring( rightCurly +1, msg.length() ); int fileHash = Integer.parseInt( msg.substring( leftCurly +1, rightCurly ) ); responder.fileSend( msgCode, byteSize, fileName, msgNick, fileHash, fileCode ); } } else if ( type.equals( "CLIENT" ) ) { int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); int leftCurly = msg.indexOf( "{" ); int rightCurly = msg.indexOf( "}" ); String client = msg.substring( leftPara +1, rightPara ); long timeSinceLogon = Long.parseLong( msg.substring( leftBracket +1, rightBracket ) ); String operatingSystem = msg.substring( leftCurly +1, rightCurly ); responder.clientInfo( msgCode, client, timeSinceLogon, operatingSystem ); } } - else if ( type.equals( "LOGON" ) ) + else if ( msgCode == tempme.getCode() && type.equals( "LOGON" ) ) { responder.meLogOn( ipAddress ); loggedOn = true; } - else if ( type.equals( "IDLE" ) ) + else if ( msgCode == tempme.getCode() && type.equals( "IDLE" ) && loggedOn ) { responder.meIdle( ipAddress ); } } catch ( StringIndexOutOfBoundsException e ) { log.log( Level.SEVERE, e.getMessage(), e ); } catch ( NumberFormatException e ) { log.log( Level.SEVERE, e.getMessage(), e ); } } }
false
true
public void messageArrived( String message, String ipAddress ) { if ( settings.isDebug() ) System.out.println( message ); try { int exclamation = message.indexOf( "!" ); int hash = message.indexOf( "#" ); int colon = message.indexOf( ":" ); int msgCode = Integer.parseInt( message.substring( 0, exclamation ) ); String type = message.substring( exclamation +1, hash ); String msgNick = message.substring( hash +1, colon ); String msg = message.substring( colon +1, message.length() ); NickDTO tempme = settings.getMe(); if ( msgCode != tempme.getCode() && loggedOn ) { if ( type.equals( "MSG" ) ) { int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); int rgb = Integer.parseInt( msg.substring( leftBracket +1, rightBracket ) ); responder.messageArrived( msgCode, msg.substring( rightBracket +1, msg.length() ), rgb ); } else if ( type.equals( "LOGON" ) ) { NickDTO newUser = new NickDTO( msgNick, msgCode ); newUser.setIpAddress( ipAddress ); newUser.setLastIdle( System.currentTimeMillis() ); responder.userLogOn( newUser ); } else if ( type.equals( "EXPOSING" ) ) { NickDTO user = new NickDTO( msgNick, msgCode ); user.setIpAddress( ipAddress ); user.setAwayMsg( msg ); if ( msg.length() > 0 ) user.setAway( true ); user.setLastIdle( System.currentTimeMillis() ); responder.userExposing( user ); } else if ( type.equals( "LOGOFF" ) ) { responder.userLogOff( msgCode ); } else if ( type.equals( "AWAY" ) ) { responder.awayChanged( msgCode, true, msg ); } else if ( type.equals( "BACK" ) ) { responder.awayChanged( msgCode, false, "" ); } else if ( type.equals( "EXPOSE" ) ) { responder.exposeRequested(); } else if ( type.equals( "NICKCRASH" ) ) { if ( tempme.getNick().equals( msg ) ) { responder.nickCrash(); } } else if ( type.equals( "WRITING" ) ) { responder.writingChanged( msgCode, true ); } else if ( type.equals( "STOPPEDWRITING" ) ) { responder.writingChanged( msgCode, false ); } else if ( type.equals( "GETTOPIC" ) ) { responder.topicRequested(); } else if ( type.equals( "TOPIC" ) ) { int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); if ( rightBracket != -1 && leftBracket != -1 ) { String theNick = msg.substring( leftPara +1, rightPara ); long theTime = Long.parseLong( msg.substring( leftBracket +1, rightBracket ) ); String theTopic = null; if ( msg.length() > rightBracket + 1 ) { theTopic = msg.substring( rightBracket +1, msg.length() ); } responder.topicChanged( msgCode, theTopic, theNick, theTime ); } } else if ( type.equals( "NICK" ) ) { responder.nickChanged( msgCode, msgNick ); } else if ( type.equals( "IDLE" ) ) { responder.userIdle( msgCode, ipAddress ); } else if ( type.equals( "SENDFILEACCEPT" ) ) { int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); int fileCode = Integer.parseInt( msg.substring( leftPara +1, rightPara ) ); if ( fileCode == tempme.getCode() ) { int leftCurly = msg.indexOf( "{" ); int rightCurly = msg.indexOf( "}" ); int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); int port = Integer.parseInt( msg.substring( leftBracket +1, rightBracket ) ); int fileHash = Integer.parseInt( msg.substring( leftCurly +1, rightCurly ) ); String fileName = msg.substring( rightCurly +1, msg.length() ); responder.fileSendAccepted( msgCode, fileName, fileHash, port ); } } else if ( type.equals( "SENDFILEABORT" ) ) { int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); int fileCode = Integer.parseInt( msg.substring( leftPara +1, rightPara ) ); if ( fileCode == tempme.getCode() ) { int leftCurly = msg.indexOf( "{" ); int rightCurly = msg.indexOf( "}" ); String fileName = msg.substring( rightCurly +1, msg.length() ); int fileHash = Integer.parseInt( msg.substring( leftCurly +1, rightCurly ) ); responder.fileSendAborted( msgCode, fileName, fileHash ); } } else if ( type.equals( "SENDFILE" ) ) { int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); int fileCode = Integer.parseInt( msg.substring( leftPara +1, rightPara ) ); if ( fileCode == tempme.getCode() ) { int leftCurly = msg.indexOf( "{" ); int rightCurly = msg.indexOf( "}" ); int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); long byteSize = Long.parseLong( msg.substring( leftBracket +1, rightBracket ) ); String fileName = msg.substring( rightCurly +1, msg.length() ); int fileHash = Integer.parseInt( msg.substring( leftCurly +1, rightCurly ) ); responder.fileSend( msgCode, byteSize, fileName, msgNick, fileHash, fileCode ); } } else if ( type.equals( "CLIENT" ) ) { int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); int leftCurly = msg.indexOf( "{" ); int rightCurly = msg.indexOf( "}" ); String client = msg.substring( leftPara +1, rightPara ); long timeSinceLogon = Long.parseLong( msg.substring( leftBracket +1, rightBracket ) ); String operatingSystem = msg.substring( leftCurly +1, rightCurly ); responder.clientInfo( msgCode, client, timeSinceLogon, operatingSystem ); } } else if ( type.equals( "LOGON" ) ) { responder.meLogOn( ipAddress ); loggedOn = true; } else if ( type.equals( "IDLE" ) ) { responder.meIdle( ipAddress ); } } catch ( StringIndexOutOfBoundsException e ) { log.log( Level.SEVERE, e.getMessage(), e ); } catch ( NumberFormatException e ) { log.log( Level.SEVERE, e.getMessage(), e ); } }
public void messageArrived( String message, String ipAddress ) { if ( settings.isDebug() ) System.out.println( message ); try { int exclamation = message.indexOf( "!" ); int hash = message.indexOf( "#" ); int colon = message.indexOf( ":" ); int msgCode = Integer.parseInt( message.substring( 0, exclamation ) ); String type = message.substring( exclamation +1, hash ); String msgNick = message.substring( hash +1, colon ); String msg = message.substring( colon +1, message.length() ); NickDTO tempme = settings.getMe(); if ( msgCode != tempme.getCode() && loggedOn ) { if ( type.equals( "MSG" ) ) { int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); int rgb = Integer.parseInt( msg.substring( leftBracket +1, rightBracket ) ); responder.messageArrived( msgCode, msg.substring( rightBracket +1, msg.length() ), rgb ); } else if ( type.equals( "LOGON" ) ) { NickDTO newUser = new NickDTO( msgNick, msgCode ); newUser.setIpAddress( ipAddress ); newUser.setLastIdle( System.currentTimeMillis() ); responder.userLogOn( newUser ); } else if ( type.equals( "EXPOSING" ) ) { NickDTO user = new NickDTO( msgNick, msgCode ); user.setIpAddress( ipAddress ); user.setAwayMsg( msg ); if ( msg.length() > 0 ) user.setAway( true ); user.setLastIdle( System.currentTimeMillis() ); responder.userExposing( user ); } else if ( type.equals( "LOGOFF" ) ) { responder.userLogOff( msgCode ); } else if ( type.equals( "AWAY" ) ) { responder.awayChanged( msgCode, true, msg ); } else if ( type.equals( "BACK" ) ) { responder.awayChanged( msgCode, false, "" ); } else if ( type.equals( "EXPOSE" ) ) { responder.exposeRequested(); } else if ( type.equals( "NICKCRASH" ) ) { if ( tempme.getNick().equals( msg ) ) { responder.nickCrash(); } } else if ( type.equals( "WRITING" ) ) { responder.writingChanged( msgCode, true ); } else if ( type.equals( "STOPPEDWRITING" ) ) { responder.writingChanged( msgCode, false ); } else if ( type.equals( "GETTOPIC" ) ) { responder.topicRequested(); } else if ( type.equals( "TOPIC" ) ) { int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); if ( rightBracket != -1 && leftBracket != -1 ) { String theNick = msg.substring( leftPara +1, rightPara ); long theTime = Long.parseLong( msg.substring( leftBracket +1, rightBracket ) ); String theTopic = null; if ( msg.length() > rightBracket + 1 ) { theTopic = msg.substring( rightBracket +1, msg.length() ); } responder.topicChanged( msgCode, theTopic, theNick, theTime ); } } else if ( type.equals( "NICK" ) ) { responder.nickChanged( msgCode, msgNick ); } else if ( type.equals( "IDLE" ) ) { responder.userIdle( msgCode, ipAddress ); } else if ( type.equals( "SENDFILEACCEPT" ) ) { int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); int fileCode = Integer.parseInt( msg.substring( leftPara +1, rightPara ) ); if ( fileCode == tempme.getCode() ) { int leftCurly = msg.indexOf( "{" ); int rightCurly = msg.indexOf( "}" ); int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); int port = Integer.parseInt( msg.substring( leftBracket +1, rightBracket ) ); int fileHash = Integer.parseInt( msg.substring( leftCurly +1, rightCurly ) ); String fileName = msg.substring( rightCurly +1, msg.length() ); responder.fileSendAccepted( msgCode, fileName, fileHash, port ); } } else if ( type.equals( "SENDFILEABORT" ) ) { int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); int fileCode = Integer.parseInt( msg.substring( leftPara +1, rightPara ) ); if ( fileCode == tempme.getCode() ) { int leftCurly = msg.indexOf( "{" ); int rightCurly = msg.indexOf( "}" ); String fileName = msg.substring( rightCurly +1, msg.length() ); int fileHash = Integer.parseInt( msg.substring( leftCurly +1, rightCurly ) ); responder.fileSendAborted( msgCode, fileName, fileHash ); } } else if ( type.equals( "SENDFILE" ) ) { int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); int fileCode = Integer.parseInt( msg.substring( leftPara +1, rightPara ) ); if ( fileCode == tempme.getCode() ) { int leftCurly = msg.indexOf( "{" ); int rightCurly = msg.indexOf( "}" ); int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); long byteSize = Long.parseLong( msg.substring( leftBracket +1, rightBracket ) ); String fileName = msg.substring( rightCurly +1, msg.length() ); int fileHash = Integer.parseInt( msg.substring( leftCurly +1, rightCurly ) ); responder.fileSend( msgCode, byteSize, fileName, msgNick, fileHash, fileCode ); } } else if ( type.equals( "CLIENT" ) ) { int leftPara = msg.indexOf( "(" ); int rightPara = msg.indexOf( ")" ); int leftBracket = msg.indexOf( "[" ); int rightBracket = msg.indexOf( "]" ); int leftCurly = msg.indexOf( "{" ); int rightCurly = msg.indexOf( "}" ); String client = msg.substring( leftPara +1, rightPara ); long timeSinceLogon = Long.parseLong( msg.substring( leftBracket +1, rightBracket ) ); String operatingSystem = msg.substring( leftCurly +1, rightCurly ); responder.clientInfo( msgCode, client, timeSinceLogon, operatingSystem ); } } else if ( msgCode == tempme.getCode() && type.equals( "LOGON" ) ) { responder.meLogOn( ipAddress ); loggedOn = true; } else if ( msgCode == tempme.getCode() && type.equals( "IDLE" ) && loggedOn ) { responder.meIdle( ipAddress ); } } catch ( StringIndexOutOfBoundsException e ) { log.log( Level.SEVERE, e.getMessage(), e ); } catch ( NumberFormatException e ) { log.log( Level.SEVERE, e.getMessage(), e ); } }
diff --git a/x10.compiler/src/x10/ast/AssignPropertyCall_c.java b/x10.compiler/src/x10/ast/AssignPropertyCall_c.java index 2368c97e1..18db8b4aa 100644 --- a/x10.compiler/src/x10/ast/AssignPropertyCall_c.java +++ b/x10.compiler/src/x10/ast/AssignPropertyCall_c.java @@ -1,381 +1,382 @@ /* * This file is part of the X10 project (http://x10-lang.org). * * This file is licensed to You under the Eclipse Public License (EPL); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.opensource.org/licenses/eclipse-1.0.php * * (C) Copyright IBM Corporation 2006-2010. */ package x10.ast; import java.util.ArrayList; import java.util.List; import polyglot.ast.Assign; import polyglot.ast.Expr; import polyglot.ast.FieldAssign; import polyglot.ast.Node; import polyglot.ast.NodeFactory; import polyglot.ast.Stmt; import polyglot.ast.Stmt_c; import polyglot.ast.Term; import polyglot.ast.TypeNode; import polyglot.frontend.Job; import polyglot.types.ClassType; import polyglot.types.Context; import polyglot.types.FieldInstance; import polyglot.types.LocalInstance; import polyglot.types.Ref; import polyglot.types.SemanticException; import polyglot.types.Type; import polyglot.types.TypeSystem; import polyglot.types.Types; import polyglot.types.UnknownType; import polyglot.util.Position; import polyglot.util.TypedList; import polyglot.visit.CFGBuilder; import polyglot.visit.ContextVisitor; import polyglot.visit.NodeVisitor; import polyglot.visit.TypeBuilder; import x10.Configuration; import x10.constraint.XFailure; import x10.constraint.XTerms; import x10.constraint.XVar; import x10.constraint.XTerm; import x10.constraint.XVar; import x10.errors.Errors; import x10.errors.Errors.IllegalConstraint; import x10.types.X10ConstructorDef; import polyglot.types.Context; import x10.types.X10ClassType; import x10.types.X10FieldInstance; import x10.types.X10ParsedClassType; import polyglot.types.TypeSystem; import x10.types.XTypeTranslator; import x10.types.X10ClassDef; import x10.types.X10TypeEnv; import x10.types.X10TypeEnv_c; import x10.types.checker.ThisChecker; import x10.types.constraints.CConstraint; import x10.types.constraints.CConstraint; import x10.types.constraints.CTerms; import x10.types.constraints.ConstraintMaker; import x10.types.matcher.Matcher; /** * @author vj * @author igor */ public class AssignPropertyCall_c extends Stmt_c implements AssignPropertyCall { List<Expr> arguments; List<X10FieldInstance> properties; /** * @param pos * @param arguments * @param target * @param name */ public AssignPropertyCall_c(Position pos, List<Expr> arguments) { super(pos); this.arguments = TypedList.copyAndCheck(arguments, Expr.class, true); } public Term firstChild() { return listChild(arguments, null); } /* (non-Javadoc) * @see polyglot.ast.Term#acceptCFG(polyglot.visit.CFGBuilder, java.util.List) */ public <S> List<S> acceptCFG(CFGBuilder v, List<S> succs) { v.visitCFGList(arguments, this, EXIT); return succs; } public AssignPropertyCall arguments(List<Expr> args) { if (args == arguments) return this; AssignPropertyCall_c n = (AssignPropertyCall_c) copy(); n.arguments = TypedList.copyAndCheck(args, Expr.class, true); return n; } public List<Expr> arguments() { return arguments; } public AssignPropertyCall properties(List<X10FieldInstance> properties) { if (properties == this.properties) return this; AssignPropertyCall_c n = (AssignPropertyCall_c) copy(); n.properties = TypedList.copyAndCheck(properties, FieldInstance.class, true); return n; } public List<X10FieldInstance> properties() { return properties; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("property"); sb.append("("); boolean first = true; for (Expr e : arguments) { if (first) { first = false; } else { sb.append(", "); } sb.append(e); } sb.append(");"); return sb.toString(); } public static X10ConstructorDef getConstructorDef(TypeBuilder tb) { for (; tb != null && tb.inCode(); tb = tb.pop()) if (tb.def() instanceof X10ConstructorDef) return (X10ConstructorDef) tb.def(); return null; } @Override public Node buildTypes(TypeBuilder tb) { X10ConstructorDef cd = getConstructorDef(tb); if (cd != null) { cd.derivedReturnType(true); } return this; } @Override public Node typeCheck(ContextVisitor tc) { TypeSystem ts = tc.typeSystem(); Context ctx = tc.context(); NodeFactory nf = (NodeFactory) tc.nodeFactory(); Position pos = position(); Job job = tc.job(); X10ConstructorDef thisConstructor = ctx.getCtorIgnoringAsync(); X10ParsedClassType container = (X10ParsedClassType) ctx.currentClass(); if (thisConstructor==null) { Errors.issue(job, new Errors.PropertyStatementMayOnlyOccurInBodyOfConstuctor(position())); } else { container = (X10ParsedClassType) thisConstructor.asInstance().container(); } // Now check that the types of each actual argument are subtypes of the corresponding // property for the class reachable through the constructor. List<FieldInstance> definedProperties = container.definedProperties(); int pSize = definedProperties.size(); int aSize = arguments.size(); if (aSize != pSize) { Errors.issue(job, new Errors.PropertyInitializerMustHaveSameNumberOfArgumentsAsPropertyForClass(position())); } checkAssignments(tc, pos, definedProperties, arguments); if (thisConstructor != null) { checkReturnType(tc, pos, thisConstructor, definedProperties, arguments); } /* We check that "this" is not allowed in CheckEscapingThis.CheckCtor ThisChecker thisC = (ThisChecker) new ThisChecker(tc.job()).context(tc.context()); for (int i=0; i < aSize; i++) { Expr arg = arguments.get(i); thisC.clearError(); visitChild(arg, thisC); if (thisC.error()) { Errors.issue(job, new Errors.ThisNotPermittedInPropertyInitializer(arg, position())); } } */ List<X10FieldInstance> properties = new ArrayList<X10FieldInstance>(); for (FieldInstance fi : definedProperties) { properties.add((X10FieldInstance) fi); } return this.properties(properties); } protected static void checkAssignments(ContextVisitor tc, Position pos, List<FieldInstance> props, List<Expr> args) { TypeSystem xts = tc.typeSystem(); Context cxt = tc.context(); XVar thisVar = tc.context().thisVar(); Type thisType=null; // Accumulate in curr constraint the bindings {arg1==this.prop1,..argi==this.propi}. // If argi does not have a name, make up a name, and add the constraint from typei // into curr, with argi/self. CConstraint curr = new CConstraint(); for (int i=0; i < args.size() && i < props.size(); ++i) { Type yType = args.get(i).type(); yType = Types.addConstraint(yType, curr); Type xType = props.get(i).type(); if (!xts.isSubtype(yType, xType)) { Errors.issue(tc.job(), new Errors.TypeOfPropertyIsNotSubtypeOfPropertyType(args.get(i).type(), props, i, pos)); } XVar symbol = Types.selfVarBinding(yType); if (symbol==null) { symbol = XTerms.makeUQV(); CConstraint c = Types.xclause(yType); curr.addIn(symbol, c); } curr.addBinding(CTerms.makeField(thisVar, props.get(i).def()), symbol); if (! curr.consistent()) { Errors.issue(tc.job(), new SemanticException("Inconsistent environment for property assignment call.", pos)); } } if (! curr.valid()) { curr.addIn(cxt.currentConstraint()); cxt.setCurrentConstraint(curr); } } protected void checkReturnType(ContextVisitor tc, Position pos, X10ConstructorDef thisConstructor, List<FieldInstance> definedProperties, List<Expr> args) { TypeSystem ts = tc.typeSystem(); final Context ctx = tc.context(); if (ts.hasUnknown(Types.getCached(thisConstructor.returnType()))) { return; } Type returnType = Types.getCached(thisConstructor.returnType()); CConstraint result = Types.xclause(returnType); if (result != null && result.valid()) result = null; // FIXME: the code below that infers the return type of a ctor is buggy, // since it infers "this". see XTENLANG-1770 { Type supType = thisConstructor.supType(); CConstraint known = Types.realX(supType); known = (known==null ? new CConstraint() : known.copy()); try { known.addIn(Types.get(thisConstructor.guard())); XVar thisVar = thisConstructor.thisVar(); for (int i = 0; i < args.size() && i < definedProperties.size(); i++) { Expr initializer = args.get(i); Type initType = initializer.type(); final FieldInstance fii = definedProperties.get(i); XVar prop = (XVar) ts.xtypeTranslator().translate(known.self(), fii); // Add in the real clause of the initializer with [self.prop/self] CConstraint c = Types.realX(initType); if (! c.consistent()) { Errors.issue(tc.job(), new Errors.InconsistentContext(initType, pos)); } if (c != null) known.addIn(c.instantiateSelf(prop)); try { XTerm initVar = ts.xtypeTranslator().translate(known, initializer, ctx, false); // it cannot be top-level, because the constraint will be "prop==initVar" if (initVar != null) known.addBinding(prop, initVar); } catch (IllegalConstraint z) { Errors.issue(tc.job(), z); } } X10ConstructorCall_c.checkSuperType(tc,supType, position); // Set the return type of the enclosing constructor to be this inferred type. Type inferredResultType = Types.addConstraint(Types.baseType(returnType), known); inferredResultType = Types.removeLocals( tc.context(), inferredResultType); if (! Types.consistent(inferredResultType)) { Errors.issue(tc.job(), new Errors.InconsistentType(inferredResultType, pos)); } Ref <? extends Type> r = thisConstructor.returnType(); - ((Ref<Type>) r).update(inferredResultType); + if (! r.known()) // update only if the return type not specified in the source program. + ((Ref<Type>) r).update(inferredResultType); // bind this==self; sup clause may constrain this. if (thisVar != null) { known = known.instantiateSelf(thisVar); // known.addSelfBinding(thisVar); // known.setThisVar(thisVar); } final CConstraint k = known; if (result != null) { final CConstraint rr = result.instantiateSelf(thisVar); if (!k.entails(rr, new ConstraintMaker() { public CConstraint make() throws XFailure { return ctx.constraintProjection(k, rr); }})) Errors.issue(tc.job(), new Errors.ConstructorReturnTypeNotEntailed(known, result, pos)); } // Check that the class invariant is satisfied. X10ClassType ctype = (X10ClassType) Types.getClassType(Types.get(thisConstructor.container()),ts,ctx); CConstraint _inv = Types.get(ctype.x10Def().classInvariant()).copy(); X10TypeEnv env = ts.env(tc.context()); boolean isThis = true; // because in the class invariant we use this (and not self) X10TypeEnv_c env_c = (X10TypeEnv_c) env; _inv = X10TypeEnv_c.ifNull(env_c.expandProperty(isThis,ctype,_inv),_inv); final CConstraint inv = _inv; if (!k.entails(inv, new ConstraintMaker() { public CConstraint make() throws XFailure { return ctx.constraintProjection(k, inv); }})) Errors.issue(tc.job(), new Errors.InvariantNotEntailed(known, inv, pos)); // Check that every super interface is entailed. for (Type intfc : ctype.interfaces()) { CConstraint cc = Types.realX(intfc); cc = cc.instantiateSelf(thisVar); // for some reason, the invariant has "self" instead of this, so I fix it here. if (thisVar != null) { XVar intfcThisVar = ((X10ClassType) intfc.toClass()).x10Def().thisVar(); cc = cc.substitute(thisVar, intfcThisVar); } cc = X10TypeEnv_c.ifNull(env_c.expandProperty(true,ctype,cc),cc); final CConstraint ccc=cc; if (!k.entails(cc, new ConstraintMaker() { public CConstraint make() throws XFailure { return ctx.constraintProjection(k, ccc); }})) Errors.issue(tc.job(), new Errors.InterfaceInvariantNotEntailed(known, intfc, cc, pos)); } // Install the known constraint in the context. CConstraint c = ctx.currentConstraint(); known.addIn(c); ctx.setCurrentConstraint(known); } catch (XFailure e) { Errors.issue(tc.job(), new Errors.GeneralError(e.getMessage(), position), this); } } } /** Visit the children of the statement. */ public Node visitChildren(NodeVisitor v) { List<Expr> args = visitList(this.arguments, v); return arguments(args); } }
true
true
protected void checkReturnType(ContextVisitor tc, Position pos, X10ConstructorDef thisConstructor, List<FieldInstance> definedProperties, List<Expr> args) { TypeSystem ts = tc.typeSystem(); final Context ctx = tc.context(); if (ts.hasUnknown(Types.getCached(thisConstructor.returnType()))) { return; } Type returnType = Types.getCached(thisConstructor.returnType()); CConstraint result = Types.xclause(returnType); if (result != null && result.valid()) result = null; // FIXME: the code below that infers the return type of a ctor is buggy, // since it infers "this". see XTENLANG-1770 { Type supType = thisConstructor.supType(); CConstraint known = Types.realX(supType); known = (known==null ? new CConstraint() : known.copy()); try { known.addIn(Types.get(thisConstructor.guard())); XVar thisVar = thisConstructor.thisVar(); for (int i = 0; i < args.size() && i < definedProperties.size(); i++) { Expr initializer = args.get(i); Type initType = initializer.type(); final FieldInstance fii = definedProperties.get(i); XVar prop = (XVar) ts.xtypeTranslator().translate(known.self(), fii); // Add in the real clause of the initializer with [self.prop/self] CConstraint c = Types.realX(initType); if (! c.consistent()) { Errors.issue(tc.job(), new Errors.InconsistentContext(initType, pos)); } if (c != null) known.addIn(c.instantiateSelf(prop)); try { XTerm initVar = ts.xtypeTranslator().translate(known, initializer, ctx, false); // it cannot be top-level, because the constraint will be "prop==initVar" if (initVar != null) known.addBinding(prop, initVar); } catch (IllegalConstraint z) { Errors.issue(tc.job(), z); } } X10ConstructorCall_c.checkSuperType(tc,supType, position); // Set the return type of the enclosing constructor to be this inferred type. Type inferredResultType = Types.addConstraint(Types.baseType(returnType), known); inferredResultType = Types.removeLocals( tc.context(), inferredResultType); if (! Types.consistent(inferredResultType)) { Errors.issue(tc.job(), new Errors.InconsistentType(inferredResultType, pos)); } Ref <? extends Type> r = thisConstructor.returnType(); ((Ref<Type>) r).update(inferredResultType); // bind this==self; sup clause may constrain this. if (thisVar != null) { known = known.instantiateSelf(thisVar); // known.addSelfBinding(thisVar); // known.setThisVar(thisVar); } final CConstraint k = known; if (result != null) { final CConstraint rr = result.instantiateSelf(thisVar); if (!k.entails(rr, new ConstraintMaker() { public CConstraint make() throws XFailure { return ctx.constraintProjection(k, rr); }})) Errors.issue(tc.job(), new Errors.ConstructorReturnTypeNotEntailed(known, result, pos)); } // Check that the class invariant is satisfied. X10ClassType ctype = (X10ClassType) Types.getClassType(Types.get(thisConstructor.container()),ts,ctx); CConstraint _inv = Types.get(ctype.x10Def().classInvariant()).copy(); X10TypeEnv env = ts.env(tc.context()); boolean isThis = true; // because in the class invariant we use this (and not self) X10TypeEnv_c env_c = (X10TypeEnv_c) env; _inv = X10TypeEnv_c.ifNull(env_c.expandProperty(isThis,ctype,_inv),_inv); final CConstraint inv = _inv; if (!k.entails(inv, new ConstraintMaker() { public CConstraint make() throws XFailure { return ctx.constraintProjection(k, inv); }})) Errors.issue(tc.job(), new Errors.InvariantNotEntailed(known, inv, pos)); // Check that every super interface is entailed. for (Type intfc : ctype.interfaces()) { CConstraint cc = Types.realX(intfc); cc = cc.instantiateSelf(thisVar); // for some reason, the invariant has "self" instead of this, so I fix it here. if (thisVar != null) { XVar intfcThisVar = ((X10ClassType) intfc.toClass()).x10Def().thisVar(); cc = cc.substitute(thisVar, intfcThisVar); } cc = X10TypeEnv_c.ifNull(env_c.expandProperty(true,ctype,cc),cc); final CConstraint ccc=cc; if (!k.entails(cc, new ConstraintMaker() { public CConstraint make() throws XFailure { return ctx.constraintProjection(k, ccc); }})) Errors.issue(tc.job(), new Errors.InterfaceInvariantNotEntailed(known, intfc, cc, pos)); } // Install the known constraint in the context. CConstraint c = ctx.currentConstraint(); known.addIn(c); ctx.setCurrentConstraint(known); } catch (XFailure e) { Errors.issue(tc.job(), new Errors.GeneralError(e.getMessage(), position), this); } } }
protected void checkReturnType(ContextVisitor tc, Position pos, X10ConstructorDef thisConstructor, List<FieldInstance> definedProperties, List<Expr> args) { TypeSystem ts = tc.typeSystem(); final Context ctx = tc.context(); if (ts.hasUnknown(Types.getCached(thisConstructor.returnType()))) { return; } Type returnType = Types.getCached(thisConstructor.returnType()); CConstraint result = Types.xclause(returnType); if (result != null && result.valid()) result = null; // FIXME: the code below that infers the return type of a ctor is buggy, // since it infers "this". see XTENLANG-1770 { Type supType = thisConstructor.supType(); CConstraint known = Types.realX(supType); known = (known==null ? new CConstraint() : known.copy()); try { known.addIn(Types.get(thisConstructor.guard())); XVar thisVar = thisConstructor.thisVar(); for (int i = 0; i < args.size() && i < definedProperties.size(); i++) { Expr initializer = args.get(i); Type initType = initializer.type(); final FieldInstance fii = definedProperties.get(i); XVar prop = (XVar) ts.xtypeTranslator().translate(known.self(), fii); // Add in the real clause of the initializer with [self.prop/self] CConstraint c = Types.realX(initType); if (! c.consistent()) { Errors.issue(tc.job(), new Errors.InconsistentContext(initType, pos)); } if (c != null) known.addIn(c.instantiateSelf(prop)); try { XTerm initVar = ts.xtypeTranslator().translate(known, initializer, ctx, false); // it cannot be top-level, because the constraint will be "prop==initVar" if (initVar != null) known.addBinding(prop, initVar); } catch (IllegalConstraint z) { Errors.issue(tc.job(), z); } } X10ConstructorCall_c.checkSuperType(tc,supType, position); // Set the return type of the enclosing constructor to be this inferred type. Type inferredResultType = Types.addConstraint(Types.baseType(returnType), known); inferredResultType = Types.removeLocals( tc.context(), inferredResultType); if (! Types.consistent(inferredResultType)) { Errors.issue(tc.job(), new Errors.InconsistentType(inferredResultType, pos)); } Ref <? extends Type> r = thisConstructor.returnType(); if (! r.known()) // update only if the return type not specified in the source program. ((Ref<Type>) r).update(inferredResultType); // bind this==self; sup clause may constrain this. if (thisVar != null) { known = known.instantiateSelf(thisVar); // known.addSelfBinding(thisVar); // known.setThisVar(thisVar); } final CConstraint k = known; if (result != null) { final CConstraint rr = result.instantiateSelf(thisVar); if (!k.entails(rr, new ConstraintMaker() { public CConstraint make() throws XFailure { return ctx.constraintProjection(k, rr); }})) Errors.issue(tc.job(), new Errors.ConstructorReturnTypeNotEntailed(known, result, pos)); } // Check that the class invariant is satisfied. X10ClassType ctype = (X10ClassType) Types.getClassType(Types.get(thisConstructor.container()),ts,ctx); CConstraint _inv = Types.get(ctype.x10Def().classInvariant()).copy(); X10TypeEnv env = ts.env(tc.context()); boolean isThis = true; // because in the class invariant we use this (and not self) X10TypeEnv_c env_c = (X10TypeEnv_c) env; _inv = X10TypeEnv_c.ifNull(env_c.expandProperty(isThis,ctype,_inv),_inv); final CConstraint inv = _inv; if (!k.entails(inv, new ConstraintMaker() { public CConstraint make() throws XFailure { return ctx.constraintProjection(k, inv); }})) Errors.issue(tc.job(), new Errors.InvariantNotEntailed(known, inv, pos)); // Check that every super interface is entailed. for (Type intfc : ctype.interfaces()) { CConstraint cc = Types.realX(intfc); cc = cc.instantiateSelf(thisVar); // for some reason, the invariant has "self" instead of this, so I fix it here. if (thisVar != null) { XVar intfcThisVar = ((X10ClassType) intfc.toClass()).x10Def().thisVar(); cc = cc.substitute(thisVar, intfcThisVar); } cc = X10TypeEnv_c.ifNull(env_c.expandProperty(true,ctype,cc),cc); final CConstraint ccc=cc; if (!k.entails(cc, new ConstraintMaker() { public CConstraint make() throws XFailure { return ctx.constraintProjection(k, ccc); }})) Errors.issue(tc.job(), new Errors.InterfaceInvariantNotEntailed(known, intfc, cc, pos)); } // Install the known constraint in the context. CConstraint c = ctx.currentConstraint(); known.addIn(c); ctx.setCurrentConstraint(known); } catch (XFailure e) { Errors.issue(tc.job(), new Errors.GeneralError(e.getMessage(), position), this); } } }
diff --git a/bndtools.diff/src/bndtools/diff/JarDiff.java b/bndtools.diff/src/bndtools/diff/JarDiff.java index 4683bb26..3c38da0f 100644 --- a/bndtools.diff/src/bndtools/diff/JarDiff.java +++ b/bndtools.diff/src/bndtools/diff/JarDiff.java @@ -1,1043 +1,1044 @@ /******************************************************************************* * Copyright (c) 2010 Per Kr. Soreide. * 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: * Per Kr. Soreide - initial API and implementation *******************************************************************************/ package bndtools.diff; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.io.PrintStream; import java.security.MessageDigest; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import org.osgi.framework.Constants; import org.osgi.framework.Version; import aQute.bnd.build.Project; import aQute.bnd.service.RepositoryPlugin; import aQute.lib.osgi.Builder; import aQute.lib.osgi.Jar; import aQute.lib.osgi.Resource; import aQute.libg.header.Attrs; import aQute.libg.header.Parameters; import aQute.libg.version.VersionRange; public class JarDiff { public static final int PKG_SEVERITY_NONE = 0; public static final int PKG_SEVERITY_MICRO = 10; // Version missing on exported package, or bytecode modification public static final int PKG_SEVERITY_MINOR = 20; // Method or class added public static final int PKG_SEVERITY_MAJOR = 30; // Class deleted, method changed or deleted private static final String VERSION = "version"; protected Map<String, PackageInfo> packages = new TreeMap<String, PackageInfo>(); protected String bundleSymbolicName; private TreeSet<String> suggestedVersions; private String selectedVersion; private String currentVersion; private final Jar projectJar; private final Jar previousJar; private RepositoryPlugin baselineRepository; private RepositoryPlugin releaseRepository; public JarDiff(Jar projectJar, Jar previousJar) { suggestedVersions = new TreeSet<String>(); this.projectJar = projectJar; this.previousJar = previousJar; } public void compare() throws Exception { Manifest projectManifest = projectJar.getManifest(); Parameters projectExportedPackages = new Parameters(getAttribute(projectManifest, Constants.EXPORT_PACKAGE)); Parameters projectImportedPackages = new Parameters(getAttribute(projectManifest, Constants.IMPORT_PACKAGE)); bundleSymbolicName = stripInstructions(getAttribute(projectManifest, Constants.BUNDLE_SYMBOLICNAME)); currentVersion = removeVersionQualifier(getAttribute(projectManifest, Constants.BUNDLE_VERSION)); // This is the version from the .bnd file Parameters previousExportedPackages; Parameters previousImportedPackages; Manifest previousManifest = null; if (previousJar != null) { previousManifest = previousJar.getManifest(); previousExportedPackages = new Parameters(getAttribute(previousManifest, Constants.EXPORT_PACKAGE)); previousImportedPackages = new Parameters(getAttribute(previousManifest, Constants.IMPORT_PACKAGE)); // If no version in projectJar use previous version if (currentVersion == null) { currentVersion = removeVersionQualifier(getAttribute(previousManifest, Constants.BUNDLE_VERSION)); } } else { previousExportedPackages = new Parameters(); // empty previousImportedPackages = new Parameters(); // empty } String prevName = stripInstructions(getAttribute(previousManifest, Constants.BUNDLE_SYMBOLICNAME)); if (bundleSymbolicName != null && prevName != null && !bundleSymbolicName.equals(prevName)) { throw new IllegalArgumentException(Constants.BUNDLE_SYMBOLICNAME + " must be equal"); } // Private packages if (previousJar != null) { for (String packageName : projectJar.getPackages()) { if (!projectExportedPackages.containsKey(packageName)) { PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); } Set<ClassInfo> projectClasses = getClassesFromPackage(pi, projectJar, packageName, null); if (projectClasses.size() == 0) { continue; } if (!packages.containsKey(packageName)) { packages.put(packageName, pi); } Set<ClassInfo> previousClasses = getClassesFromPackage(pi, previousJar, packageName, null); Set<ClassInfo> cis = pi.getClasses(); for (ClassInfo ci : projectClasses) { ClassInfo prevCi = null; if (previousClasses != null) { for (ClassInfo c : previousClasses) { if (c.equals(ci)) { prevCi = c; break; } } } cis.add(ci); if (prevCi != null && !Arrays.equals(ci.getSHA1(), prevCi.getSHA1())) { ci.setChangeCode(ClassInfo.CHANGE_CODE_MODIFIED); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); continue; } if (prevCi == null) { ci.setChangeCode(ClassInfo.CHANGE_CODE_NEW); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); continue; } } if (previousClasses != null) { for (ClassInfo prevCi : previousClasses) { if (!projectClasses.contains(prevCi)) { cis.add(prevCi); prevCi.setChangeCode(ClassInfo.CHANGE_CODE_REMOVED); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); } } } } } } for (Entry<String, Attrs> entry : projectImportedPackages.entrySet()) { String packageName = entry.getKey(); // New or modified packages PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setImported(true); Map<String, String> packageMap = entry.getValue(); String version = packageMap.get(VERSION); VersionRange projectVersion = null; if (version != null) { projectVersion = new VersionRange(version); pi.setSuggestedVersionRange(projectVersion.toString()); } if (previousImportedPackages.containsKey(packageName)) { Map<String, String> prevPackageMap = previousImportedPackages.get(packageName); version = prevPackageMap.get(VERSION); VersionRange previousVersion = null; if (version != null) { previousVersion = new VersionRange(version); } // No change, no versions if (projectVersion == null && previousVersion == null) { continue; } // No change if (projectVersion != null && previousVersion != null) { if (projectVersion.getHigh().equals(previousVersion.getHigh()) && projectVersion.getLow().equals(previousVersion.getLow())) { pi.setVersionRange(previousVersion.toString()); continue; } pi.setSeverity(PKG_SEVERITY_MINOR); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setVersionRange(previousVersion.toString()); pi.setSuggestedVersionRange(projectVersion.toString()); continue; } if (projectVersion != null) { pi.setSeverity(PKG_SEVERITY_MAJOR); pi.setChangeCode(PackageInfo.CHANGE_CODE_NEW); pi.setSuggestedVersionRange(projectVersion.toString()); continue; } if (previousVersion != null) { pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setVersionRange(previousVersion.toString()); } } } for (Entry<String, Attrs> entry : previousImportedPackages.entrySet()) { String packageName = entry.getKey(); if (!projectImportedPackages.containsKey(packageName)) { // Removed Packages Map<String, String> prevPackageMap = entry.getValue(); String previousVersion = prevPackageMap.get(VERSION); PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setImported(true); pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_REMOVED); pi.setVersionRange(previousVersion); } } for (Entry<String, Attrs> entry : projectExportedPackages.entrySet()) { String packageName = entry.getKey(); // New or modified packages PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setExported(true); Map<String, String> packageMap = entry.getValue(); String packageVersion = removeVersionQualifier(packageMap.get(VERSION)); /* can't be null */ Set<ClassInfo> projectClasses = getClassesFromPackage(pi, projectJar, packageName, packageVersion); Set<ClassInfo> cis = pi.getClasses(); String previousVersion = null; Set<ClassInfo> previousClasses = null; if (previousExportedPackages.containsKey(packageName)) { Map<String, String> prevPackageMap = previousExportedPackages.get(packageName); previousVersion = prevPackageMap.get(VERSION); previousClasses = getClassesFromPackage(pi, previousJar, packageName, previousVersion); } for (ClassInfo ci : projectClasses) { ClassInfo prevCi = null; if (previousClasses != null) { for (ClassInfo c : previousClasses) { if (c.equals(ci)) { prevCi = c; break; } } } int severity = getModificationSeverity(ci, prevCi); cis.add(ci); if (severity > PKG_SEVERITY_NONE) { // New or modified class if (severity > pi.getSeverity()) { pi.setSeverity(severity); } } } if (pi.getSeverity() > PKG_SEVERITY_NONE) { if (previousClasses == null) { // New package pi.setChangeCode(PackageInfo.CHANGE_CODE_NEW); pi.addSuggestedVersion(packageVersion); } else { // Modified package pi.setCurrentVersion(previousVersion); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); } } if (pi.getSeverity() == PKG_SEVERITY_NONE) { if (previousClasses != null && previousVersion == null) { // No change, but version missing on package pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_VERSION_MISSING); pi.addSuggestedVersion(getCurrentVersion()); } } if (previousClasses != null) { pi.setCurrentVersion(previousVersion); for (ClassInfo prevCi : previousClasses) { if (!projectClasses.contains(prevCi)) { int severity = getModificationSeverity(null, prevCi); cis.add(prevCi); if (severity > PKG_SEVERITY_NONE) { // Removed class if (severity > pi.getSeverity()) { pi.setSeverity(severity); } pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); } } } } } - for (String packageName : previousExportedPackages.keySet()) { + for (Entry<String, Attrs> entry : previousExportedPackages.entrySet()) { + String packageName = entry.getKey(); if (!projectExportedPackages.containsKey(packageName)) { // Removed Packages - Map<String, String> prevPackageMap = previousExportedPackages.get(packageName); + Attrs prevPackageMap = entry.getValue(); String previousVersion = prevPackageMap.get(VERSION); PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setExported(true); pi.setChangeCode(PackageInfo.CHANGE_CODE_REMOVED); Set<ClassInfo> previousClasses = getClassesFromPackage(pi, previousJar, packageName, previousVersion); pi.setClasses(previousClasses); pi.setSeverity(PKG_SEVERITY_MAJOR); for (ClassInfo prevCi : previousClasses) { // Removed class getModificationSeverity(null, prevCi); } pi.setCurrentVersion(previousVersion); } } } private static int getModificationSeverity(ClassInfo clazz, ClassInfo previousClass) { int severity = PKG_SEVERITY_NONE; if (clazz != null) { for (MethodInfo method : clazz.getMethods()) { MethodInfo prevMethod = findMethod(previousClass, method); if (prevMethod == null) { severity = PKG_SEVERITY_MINOR; method.setChangeCode(MethodInfo.CHANGE_NEW); } } for (FieldInfo field : clazz.getFields()) { FieldInfo prevField = findField(previousClass, field); if (prevField == null) { severity = PKG_SEVERITY_MINOR; field.setChangeCode(FieldInfo.CHANGE_NEW); } } } if (previousClass != null) { for (MethodInfo prevMethod : previousClass.getMethods()) { MethodInfo method = findMethod(clazz, prevMethod); if (method == null) { severity = PKG_SEVERITY_MAJOR; prevMethod.setChangeCode(MethodInfo.CHANGE_REMOVED); if (clazz != null) { clazz.addPublicMethod(prevMethod); } } } for (FieldInfo prevField : previousClass.getFields()) { FieldInfo method = findField(clazz, prevField); if (method == null) { severity = PKG_SEVERITY_MAJOR; prevField.setChangeCode(FieldInfo.CHANGE_REMOVED); if (clazz != null) { clazz.addPublicField(prevField); } } } } if (clazz != null && previousClass != null) { if (severity > PKG_SEVERITY_NONE) { clazz.setChangeCode(ClassInfo.CHANGE_CODE_MODIFIED); } else { if (!Arrays.equals(clazz.getSHA1(), previousClass.getSHA1())) { clazz.setChangeCode(ClassInfo.CHANGE_CODE_MODIFIED); severity = PKG_SEVERITY_MICRO; } else { clazz.setChangeCode(ClassInfo.CHANGE_CODE_NONE); } } } else if (clazz != null && previousClass == null) { clazz.setChangeCode(ClassInfo.CHANGE_CODE_NEW); if (severity == PKG_SEVERITY_NONE) { severity = PKG_SEVERITY_MINOR; } } else if (clazz == null && previousClass != null) { previousClass.setChangeCode(ClassInfo.CHANGE_CODE_REMOVED); if (severity == PKG_SEVERITY_NONE) { severity = PKG_SEVERITY_MAJOR; } } return severity; } private static MethodInfo findMethod(ClassInfo info, MethodInfo methodToFind) { if (info == null) { return null; } for (MethodInfo method : info.getMethods()) { if (!method.getName().equals(methodToFind.getName())) { continue; } if (method.getDesc() != null && !method.getDesc().equals(methodToFind.getDesc())) { continue; } return method; } return null; } private static FieldInfo findField(ClassInfo info, FieldInfo fieldToFind) { if (info == null) { return null; } for (FieldInfo field : info.getFields()) { if (!field.getName().equals(fieldToFind.getName())) { continue; } if (field.getDesc() != null && !field.getDesc().equals(fieldToFind.getDesc())) { continue; } return field; } return null; } private static Set<ClassInfo> getClassesFromPackage(PackageInfo pi, Jar jar, String packageName, String version) { packageName = packageName.replace('.', '/'); Map<String, Map<String, Resource>> dirs = jar.getDirectories(); if (dirs == null) { return Collections.emptySet(); } Map<String, Resource> res = dirs.get(packageName); if (res == null) { return Collections.emptySet(); } Set<ClassInfo> ret = new TreeSet<ClassInfo>(); for (Map.Entry<String, Resource> me : res.entrySet()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (me.getKey().endsWith(".class")) { InputStream is = null; try { is = me.getValue().openInputStream(); byte[] bytes = new byte[8092]; int bytesRead = 0; while ((bytesRead = is.read(bytes, 0, 8092)) != -1) { baos.write(bytes, 0, bytesRead); } byte[] classBytes = baos.toByteArray(); MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(classBytes); byte[] digest = md.digest(); ClassReader cr = new ClassReader(classBytes); ClassInfo ca = new ClassInfo(pi, digest); cr.accept(ca, 0); for (int i = 0; i < ca.methods.size(); i++) { MethodNode mn = (MethodNode) ca.methods.get(i); // Ignore anything but public and protected methods if ((mn.access & Opcodes.ACC_PUBLIC) == Opcodes.ACC_PUBLIC || (mn.access & Opcodes.ACC_PROTECTED) == Opcodes.ACC_PROTECTED) { MethodInfo mi = new MethodInfo(mn, ca); ca.addPublicMethod(mi); } } for (int i = 0; i < ca.fields.size(); i++) { FieldNode mn = (FieldNode) ca.fields.get(i); // Ignore anything but public fields if ((mn.access & Opcodes.ACC_PUBLIC) == Opcodes.ACC_PUBLIC || (mn.access & Opcodes.ACC_PROTECTED) == Opcodes.ACC_PROTECTED) { FieldInfo mi = new FieldInfo(mn, ca); ca.addPublicField(mi); } } ret.add(ca); } catch (Exception e) { throw new RuntimeException(e); } } } return ret; } public Set<PackageInfo> getExportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : packages.values()) { if (!pi.isExported()) { continue; } ret.add(pi); } return ret; } public Set<PackageInfo> getPrivatePackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : packages.values()) { if (pi.isExported() || pi.isImported()) { continue; } ret.add(pi); } return ret; } public Set<PackageInfo> getNewExportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getExportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_NEW) { continue; } ret.add(pi); } return ret; } public Collection<PackageInfo> getModifiedExportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getExportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_MODIFIED) { continue; } ret.add(pi); } return ret; } public Collection<PackageInfo> getRemovedExportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getExportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_REMOVED) { continue; } ret.add(pi); } return ret; } public Set<PackageInfo> getChangedExportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getExportedPackages()) { if (pi.getChangeCode() == PackageInfo.CHANGE_CODE_NONE) { continue; } ret.add(pi); } return ret; } public Set<PackageInfo> getChangedPrivatePackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getPrivatePackages()) { if (pi.getChangeCode() == PackageInfo.CHANGE_CODE_NONE) { continue; } ret.add(pi); } return ret; } public Collection<PackageInfo> getImportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : packages.values()) { if (!pi.isImported()) { continue; } ret.add(pi); } return ret; } public Set<PackageInfo> getNewImportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getImportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_NEW) { continue; } ret.add(pi); } return ret; } public Collection<PackageInfo> getModifiedImportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getImportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_MODIFIED) { continue; } ret.add(pi); } return ret; } public Collection<PackageInfo> getRemovedImportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getImportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_REMOVED) { continue; } ret.add(pi); } return ret; } public Set<PackageInfo> getChangedImportedPackages() { Set<PackageInfo> ret = new TreeSet<PackageInfo>(); for (PackageInfo pi : getImportedPackages()) { if (pi.getChangeCode() == PackageInfo.CHANGE_CODE_NONE) { continue; } ret.add(pi); } return ret; } public static JarDiff createJarDiff(Project project, RepositoryPlugin baselineRepository, String bsn) { try { List<Builder> builders = project.getBuilder(null).getSubBuilders(); Builder builder = null; for (Builder b : builders) { if (bsn.equals(b.getBsn())) { builder = b; break; } } if (builder != null) { Jar jar = builder.build(); String bundleVersion = builder.getProperty(Constants.BUNDLE_VERSION); if (bundleVersion == null) { builder.setProperty(Constants.BUNDLE_VERSION, "0.0.0"); bundleVersion = "0.0.0"; } String unqualifiedVersion = removeVersionQualifier(bundleVersion); Version projectVersion = Version.parseVersion(unqualifiedVersion); String symbolicName = jar.getManifest().getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); if (symbolicName == null) { symbolicName = jar.getName().substring(0, jar.getName().lastIndexOf('-')); } Jar currentJar = null; VersionRange range = new VersionRange("[" + projectVersion.toString() + "," + projectVersion.toString() + "]"); try { if (baselineRepository != null) { File[] files = baselineRepository.get(symbolicName, range.toString()); if (files != null && files.length > 0) { currentJar = new Jar(files[0]); } } } catch (Exception e) { e.printStackTrace(); } JarDiff diff = new JarDiff(jar, currentJar); diff.setBaselineRepository(baselineRepository); diff.compare(); diff.calculatePackageVersions(); return diff; } } catch (Exception e1) { e1.printStackTrace(); } return null; } public void calculatePackageVersions() { int highestSeverity = PKG_SEVERITY_NONE; for (PackageInfo pi : getExportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_MODIFIED) { continue; } String version = getVersionString(projectJar, pi.getPackageName()); if (version == null) { version = pi.getCurrentVersion(); } String mask; if (pi.getSeverity() > highestSeverity) { highestSeverity = pi.getSeverity(); } switch(pi.getSeverity()) { case PKG_SEVERITY_MINOR : mask = "=+0"; break; case PKG_SEVERITY_MAJOR : mask = "+00"; break; default: mask = null; } if (mask != null) { String suggestedVersion = _version(new String[] { "", mask, version}); pi.addSuggestedVersion(suggestedVersion); } else { pi.addSuggestedVersion(version); } } for (PackageInfo pi : getImportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_REMOVED) { continue; } String mask; if (pi.getSeverity() > highestSeverity) { highestSeverity = pi.getSeverity(); } switch(pi.getSeverity()) { case PKG_SEVERITY_MINOR : mask = "=+0"; break; case PKG_SEVERITY_MAJOR : mask = "+00"; break; default: mask = null; } if (mask != null) { String suggestedVersion = "[" + _version(new String[] { "", mask, currentVersion}) + "]"; pi.addSuggestedVersion(suggestedVersion); } else { pi.addSuggestedVersion(currentVersion); } } String mask; switch(highestSeverity) { case PKG_SEVERITY_MINOR : mask = "=+0"; break; case PKG_SEVERITY_MAJOR : mask = "+00"; break; default: mask = "==+"; } String bundleVersion = currentVersion == null ? "0.0.0" : currentVersion; String unqualifiedVersion = removeVersionQualifier(bundleVersion); String suggestedVersion = _version(new String[] { "", mask, unqualifiedVersion}); suggestedVersions.add(suggestedVersion); if (suggestVersionOne(suggestedVersion)) { suggestedVersions.add("1.0.0"); } for (PackageInfo pi : getExportedPackages()) { if (pi.getChangeCode() != PackageInfo.CHANGE_CODE_NEW) { continue; } // Obey packageinfo if it exist String version = getVersionString(projectJar, pi.getPackageName()); if (version != null) { pi.addSuggestedVersion(version); if (suggestVersionOne(version)) { pi.addSuggestedVersion("1.0.0"); } } else { if (pi.getSuggestedVersion() == null || pi.getSuggestedVersion().length() == 0 || "0.0.0".equals(pi.getSuggestedVersion())) { pi.addSuggestedVersion(suggestedVersion); } if (suggestVersionOne(suggestedVersion)) { pi.addSuggestedVersion("1.0.0"); } } } } private static boolean suggestVersionOne(String version) { aQute.libg.version.Version aQuteVersion = new aQute.libg.version.Version(version); if (aQuteVersion.compareTo(new aQute.libg.version.Version("1.0.0")) < 0) { return true; } return false; } // From aQute.libg.version.Macro _version. Without dependencies on project and properties private static String _version(String[] args) { String mask = args[1]; aQute.libg.version.Version version = new aQute.libg.version.Version(args[2]); StringBuilder sb = new StringBuilder(); String del = ""; for (int i = 0; i < mask.length(); i++) { char c = mask.charAt(i); String result = null; if (c != '~') { if (i == 3) { result = version.getQualifier(); } else if (Character.isDigit(c)) { // Handle masks like +00, =+0 result = String.valueOf(c); } else { int x = version.get(i); switch (c) { case '+': x++; break; case '-': x--; break; case '=': break; } result = Integer.toString(x); } if (result != null) { sb.append(del); del = "."; sb.append(result); } } } return sb.toString(); } private static String getVersionString(Jar jar, String packageName) { Resource resource = jar.getResource(getResourcePath(packageName, "packageinfo")); if (resource == null) { return null; } Properties packageInfo = new Properties(); InputStream is = null; try { is = resource.openInputStream(); packageInfo.load(is); } catch (Exception e) { throw new RuntimeException(e); } finally { if (is != null) { try {is.close();} catch (Exception e) {} } } String version = packageInfo.getProperty(VERSION); return version; } private static String getResourcePath(String packageName, String resourceName) { String s = packageName.replace('.', '/'); s += "/" + resourceName; return s; } public static String getSeverityText(int severity) { switch (severity) { case PKG_SEVERITY_MINOR : { return "Minor (Method or class added)"; } case PKG_SEVERITY_MAJOR : { return "Major (Class deleted, method changed or deleted)"; } default: { return ""; } } } public static void printDiff(JarDiff diff, PrintStream out) { out.println(); out.println("============================================"); out.println("Bundle " + diff.getSymbolicName() + ":"); out.println("============================================"); out.println("Version: " + diff.getCurrentVersion() + (diff.getSuggestedVersion() != null ? " -> Suggested Version: " + diff.getSuggestedVersion() : "")); if (diff.getModifiedExportedPackages().size() > 0) { out.println(); out.println("Modified Exported Packages:"); out.println("---------------------------"); for (PackageInfo pi : diff.getModifiedExportedPackages()) { out.println(pi.getPackageName() + " " + pi.getCurrentVersion() + " : " + getSeverityText(pi.getSeverity()) + (pi.getSuggestedVersion() != null ? " -> Suggested version: " + pi.getSuggestedVersion() : "")); for (ClassInfo ci :pi.getChangedClasses()) { out.println(" " + ci.toString()); } } } if (diff.getModifiedImportedPackages().size() > 0) { out.println(); out.println("Modified Imported Packages:"); out.println("---------------------------"); for (PackageInfo pi : diff.getModifiedImportedPackages()) { out.println(pi.getPackageName() + " " + pi.getVersionRange() + " : " + getSeverityText(pi.getSeverity()) + (pi.getSuggestedVersionRange() != null ? " -> Suggested version range: " + pi.getSuggestedVersionRange() : "")); for (ClassInfo ci :pi.getChangedClasses()) { out.println(" " + ci.toString()); } } } if (diff.getNewExportedPackages().size() > 0) { out.println(); out.println("Added Exported Packages:"); out.println("------------------------"); for (PackageInfo pi : diff.getNewExportedPackages()) { out.println(pi.getPackageName() + (pi.getSuggestedVersion() != null ? " -> Suggested version: " + pi.getSuggestedVersion() : "")); for (ClassInfo ci :pi.getChangedClasses()) { out.println(" " + ci.toString()); } } } if (diff.getNewImportedPackages().size() > 0) { out.println(); out.println("Added Imported Packages:"); out.println("------------------------"); for (PackageInfo pi : diff.getNewImportedPackages()) { out.println(pi.getPackageName() + (pi.getSuggestedVersionRange() != null ? " -> Suggested version range: " + pi.getSuggestedVersionRange() : "")); for (ClassInfo ci :pi.getChangedClasses()) { out.println(" " + ci.toString()); } } } if (diff.getRemovedExportedPackages().size() > 0) { out.println(); out.println("Deleted Exported Packages:"); out.println("--------------------------"); for (PackageInfo pi : diff.getRemovedExportedPackages()) { out.println(pi.getPackageName() + " " + pi.getCurrentVersion()); } } if (diff.getRemovedImportedPackages().size() > 0) { out.println(); out.println("Deleted Imported Packages:"); out.println("--------------------------"); for (PackageInfo pi : diff.getRemovedImportedPackages()) { out.println(pi.getPackageName() + " " + pi.getVersionRange()); } } } public String getSymbolicName() { return bundleSymbolicName; } public static String stripInstructions(String header) { if (header == null) { return null; } int idx = header.indexOf(';'); if (idx > -1) { return header.substring(0, idx); } return header; } public static String getAttribute(Manifest manifest, String attributeName) { if (manifest != null && attributeName != null) { return (String) manifest.getMainAttributes().get(new Attributes.Name(attributeName)); } return null; } public static String removeVersionQualifier(String version) { if (version == null) { return null; } // Remove qualifier String[] parts = version.split("\\."); StringBuilder sb = new StringBuilder(); String sep = ""; for (int i = 0; i < parts.length; i++) { if (i == 3) { break; } sb.append(sep); sb.append(parts[i]); sep = "."; } return sb.toString(); } public String getCurrentVersion() { return currentVersion; } public String getSuggestedVersion() { if (suggestedVersions.size() > 0) { return suggestedVersions.last(); } return null; } public TreeSet<String> getSuggestedVersions() { return suggestedVersions; } public String getSelectedVersion() { if (selectedVersion == null) { return getSuggestedVersion(); } return selectedVersion; } public void setSelectedVersion(String selectedVersion) { this.selectedVersion = selectedVersion; } public RepositoryPlugin getBaselineRepository() { return baselineRepository; } public void setBaselineRepository(RepositoryPlugin baselineRepository) { this.baselineRepository = baselineRepository; } public RepositoryPlugin getReleaseRepository() { return releaseRepository; } public void setReleaseRepository(RepositoryPlugin releaseRepository) { this.releaseRepository = releaseRepository; } }
false
true
public void compare() throws Exception { Manifest projectManifest = projectJar.getManifest(); Parameters projectExportedPackages = new Parameters(getAttribute(projectManifest, Constants.EXPORT_PACKAGE)); Parameters projectImportedPackages = new Parameters(getAttribute(projectManifest, Constants.IMPORT_PACKAGE)); bundleSymbolicName = stripInstructions(getAttribute(projectManifest, Constants.BUNDLE_SYMBOLICNAME)); currentVersion = removeVersionQualifier(getAttribute(projectManifest, Constants.BUNDLE_VERSION)); // This is the version from the .bnd file Parameters previousExportedPackages; Parameters previousImportedPackages; Manifest previousManifest = null; if (previousJar != null) { previousManifest = previousJar.getManifest(); previousExportedPackages = new Parameters(getAttribute(previousManifest, Constants.EXPORT_PACKAGE)); previousImportedPackages = new Parameters(getAttribute(previousManifest, Constants.IMPORT_PACKAGE)); // If no version in projectJar use previous version if (currentVersion == null) { currentVersion = removeVersionQualifier(getAttribute(previousManifest, Constants.BUNDLE_VERSION)); } } else { previousExportedPackages = new Parameters(); // empty previousImportedPackages = new Parameters(); // empty } String prevName = stripInstructions(getAttribute(previousManifest, Constants.BUNDLE_SYMBOLICNAME)); if (bundleSymbolicName != null && prevName != null && !bundleSymbolicName.equals(prevName)) { throw new IllegalArgumentException(Constants.BUNDLE_SYMBOLICNAME + " must be equal"); } // Private packages if (previousJar != null) { for (String packageName : projectJar.getPackages()) { if (!projectExportedPackages.containsKey(packageName)) { PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); } Set<ClassInfo> projectClasses = getClassesFromPackage(pi, projectJar, packageName, null); if (projectClasses.size() == 0) { continue; } if (!packages.containsKey(packageName)) { packages.put(packageName, pi); } Set<ClassInfo> previousClasses = getClassesFromPackage(pi, previousJar, packageName, null); Set<ClassInfo> cis = pi.getClasses(); for (ClassInfo ci : projectClasses) { ClassInfo prevCi = null; if (previousClasses != null) { for (ClassInfo c : previousClasses) { if (c.equals(ci)) { prevCi = c; break; } } } cis.add(ci); if (prevCi != null && !Arrays.equals(ci.getSHA1(), prevCi.getSHA1())) { ci.setChangeCode(ClassInfo.CHANGE_CODE_MODIFIED); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); continue; } if (prevCi == null) { ci.setChangeCode(ClassInfo.CHANGE_CODE_NEW); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); continue; } } if (previousClasses != null) { for (ClassInfo prevCi : previousClasses) { if (!projectClasses.contains(prevCi)) { cis.add(prevCi); prevCi.setChangeCode(ClassInfo.CHANGE_CODE_REMOVED); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); } } } } } } for (Entry<String, Attrs> entry : projectImportedPackages.entrySet()) { String packageName = entry.getKey(); // New or modified packages PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setImported(true); Map<String, String> packageMap = entry.getValue(); String version = packageMap.get(VERSION); VersionRange projectVersion = null; if (version != null) { projectVersion = new VersionRange(version); pi.setSuggestedVersionRange(projectVersion.toString()); } if (previousImportedPackages.containsKey(packageName)) { Map<String, String> prevPackageMap = previousImportedPackages.get(packageName); version = prevPackageMap.get(VERSION); VersionRange previousVersion = null; if (version != null) { previousVersion = new VersionRange(version); } // No change, no versions if (projectVersion == null && previousVersion == null) { continue; } // No change if (projectVersion != null && previousVersion != null) { if (projectVersion.getHigh().equals(previousVersion.getHigh()) && projectVersion.getLow().equals(previousVersion.getLow())) { pi.setVersionRange(previousVersion.toString()); continue; } pi.setSeverity(PKG_SEVERITY_MINOR); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setVersionRange(previousVersion.toString()); pi.setSuggestedVersionRange(projectVersion.toString()); continue; } if (projectVersion != null) { pi.setSeverity(PKG_SEVERITY_MAJOR); pi.setChangeCode(PackageInfo.CHANGE_CODE_NEW); pi.setSuggestedVersionRange(projectVersion.toString()); continue; } if (previousVersion != null) { pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setVersionRange(previousVersion.toString()); } } } for (Entry<String, Attrs> entry : previousImportedPackages.entrySet()) { String packageName = entry.getKey(); if (!projectImportedPackages.containsKey(packageName)) { // Removed Packages Map<String, String> prevPackageMap = entry.getValue(); String previousVersion = prevPackageMap.get(VERSION); PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setImported(true); pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_REMOVED); pi.setVersionRange(previousVersion); } } for (Entry<String, Attrs> entry : projectExportedPackages.entrySet()) { String packageName = entry.getKey(); // New or modified packages PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setExported(true); Map<String, String> packageMap = entry.getValue(); String packageVersion = removeVersionQualifier(packageMap.get(VERSION)); /* can't be null */ Set<ClassInfo> projectClasses = getClassesFromPackage(pi, projectJar, packageName, packageVersion); Set<ClassInfo> cis = pi.getClasses(); String previousVersion = null; Set<ClassInfo> previousClasses = null; if (previousExportedPackages.containsKey(packageName)) { Map<String, String> prevPackageMap = previousExportedPackages.get(packageName); previousVersion = prevPackageMap.get(VERSION); previousClasses = getClassesFromPackage(pi, previousJar, packageName, previousVersion); } for (ClassInfo ci : projectClasses) { ClassInfo prevCi = null; if (previousClasses != null) { for (ClassInfo c : previousClasses) { if (c.equals(ci)) { prevCi = c; break; } } } int severity = getModificationSeverity(ci, prevCi); cis.add(ci); if (severity > PKG_SEVERITY_NONE) { // New or modified class if (severity > pi.getSeverity()) { pi.setSeverity(severity); } } } if (pi.getSeverity() > PKG_SEVERITY_NONE) { if (previousClasses == null) { // New package pi.setChangeCode(PackageInfo.CHANGE_CODE_NEW); pi.addSuggestedVersion(packageVersion); } else { // Modified package pi.setCurrentVersion(previousVersion); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); } } if (pi.getSeverity() == PKG_SEVERITY_NONE) { if (previousClasses != null && previousVersion == null) { // No change, but version missing on package pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_VERSION_MISSING); pi.addSuggestedVersion(getCurrentVersion()); } } if (previousClasses != null) { pi.setCurrentVersion(previousVersion); for (ClassInfo prevCi : previousClasses) { if (!projectClasses.contains(prevCi)) { int severity = getModificationSeverity(null, prevCi); cis.add(prevCi); if (severity > PKG_SEVERITY_NONE) { // Removed class if (severity > pi.getSeverity()) { pi.setSeverity(severity); } pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); } } } } } for (String packageName : previousExportedPackages.keySet()) { if (!projectExportedPackages.containsKey(packageName)) { // Removed Packages Map<String, String> prevPackageMap = previousExportedPackages.get(packageName); String previousVersion = prevPackageMap.get(VERSION); PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setExported(true); pi.setChangeCode(PackageInfo.CHANGE_CODE_REMOVED); Set<ClassInfo> previousClasses = getClassesFromPackage(pi, previousJar, packageName, previousVersion); pi.setClasses(previousClasses); pi.setSeverity(PKG_SEVERITY_MAJOR); for (ClassInfo prevCi : previousClasses) { // Removed class getModificationSeverity(null, prevCi); } pi.setCurrentVersion(previousVersion); } } }
public void compare() throws Exception { Manifest projectManifest = projectJar.getManifest(); Parameters projectExportedPackages = new Parameters(getAttribute(projectManifest, Constants.EXPORT_PACKAGE)); Parameters projectImportedPackages = new Parameters(getAttribute(projectManifest, Constants.IMPORT_PACKAGE)); bundleSymbolicName = stripInstructions(getAttribute(projectManifest, Constants.BUNDLE_SYMBOLICNAME)); currentVersion = removeVersionQualifier(getAttribute(projectManifest, Constants.BUNDLE_VERSION)); // This is the version from the .bnd file Parameters previousExportedPackages; Parameters previousImportedPackages; Manifest previousManifest = null; if (previousJar != null) { previousManifest = previousJar.getManifest(); previousExportedPackages = new Parameters(getAttribute(previousManifest, Constants.EXPORT_PACKAGE)); previousImportedPackages = new Parameters(getAttribute(previousManifest, Constants.IMPORT_PACKAGE)); // If no version in projectJar use previous version if (currentVersion == null) { currentVersion = removeVersionQualifier(getAttribute(previousManifest, Constants.BUNDLE_VERSION)); } } else { previousExportedPackages = new Parameters(); // empty previousImportedPackages = new Parameters(); // empty } String prevName = stripInstructions(getAttribute(previousManifest, Constants.BUNDLE_SYMBOLICNAME)); if (bundleSymbolicName != null && prevName != null && !bundleSymbolicName.equals(prevName)) { throw new IllegalArgumentException(Constants.BUNDLE_SYMBOLICNAME + " must be equal"); } // Private packages if (previousJar != null) { for (String packageName : projectJar.getPackages()) { if (!projectExportedPackages.containsKey(packageName)) { PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); } Set<ClassInfo> projectClasses = getClassesFromPackage(pi, projectJar, packageName, null); if (projectClasses.size() == 0) { continue; } if (!packages.containsKey(packageName)) { packages.put(packageName, pi); } Set<ClassInfo> previousClasses = getClassesFromPackage(pi, previousJar, packageName, null); Set<ClassInfo> cis = pi.getClasses(); for (ClassInfo ci : projectClasses) { ClassInfo prevCi = null; if (previousClasses != null) { for (ClassInfo c : previousClasses) { if (c.equals(ci)) { prevCi = c; break; } } } cis.add(ci); if (prevCi != null && !Arrays.equals(ci.getSHA1(), prevCi.getSHA1())) { ci.setChangeCode(ClassInfo.CHANGE_CODE_MODIFIED); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); continue; } if (prevCi == null) { ci.setChangeCode(ClassInfo.CHANGE_CODE_NEW); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); continue; } } if (previousClasses != null) { for (ClassInfo prevCi : previousClasses) { if (!projectClasses.contains(prevCi)) { cis.add(prevCi); prevCi.setChangeCode(ClassInfo.CHANGE_CODE_REMOVED); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setSeverity(PKG_SEVERITY_MICRO); } } } } } } for (Entry<String, Attrs> entry : projectImportedPackages.entrySet()) { String packageName = entry.getKey(); // New or modified packages PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setImported(true); Map<String, String> packageMap = entry.getValue(); String version = packageMap.get(VERSION); VersionRange projectVersion = null; if (version != null) { projectVersion = new VersionRange(version); pi.setSuggestedVersionRange(projectVersion.toString()); } if (previousImportedPackages.containsKey(packageName)) { Map<String, String> prevPackageMap = previousImportedPackages.get(packageName); version = prevPackageMap.get(VERSION); VersionRange previousVersion = null; if (version != null) { previousVersion = new VersionRange(version); } // No change, no versions if (projectVersion == null && previousVersion == null) { continue; } // No change if (projectVersion != null && previousVersion != null) { if (projectVersion.getHigh().equals(previousVersion.getHigh()) && projectVersion.getLow().equals(previousVersion.getLow())) { pi.setVersionRange(previousVersion.toString()); continue; } pi.setSeverity(PKG_SEVERITY_MINOR); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setVersionRange(previousVersion.toString()); pi.setSuggestedVersionRange(projectVersion.toString()); continue; } if (projectVersion != null) { pi.setSeverity(PKG_SEVERITY_MAJOR); pi.setChangeCode(PackageInfo.CHANGE_CODE_NEW); pi.setSuggestedVersionRange(projectVersion.toString()); continue; } if (previousVersion != null) { pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); pi.setVersionRange(previousVersion.toString()); } } } for (Entry<String, Attrs> entry : previousImportedPackages.entrySet()) { String packageName = entry.getKey(); if (!projectImportedPackages.containsKey(packageName)) { // Removed Packages Map<String, String> prevPackageMap = entry.getValue(); String previousVersion = prevPackageMap.get(VERSION); PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setImported(true); pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_REMOVED); pi.setVersionRange(previousVersion); } } for (Entry<String, Attrs> entry : projectExportedPackages.entrySet()) { String packageName = entry.getKey(); // New or modified packages PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setExported(true); Map<String, String> packageMap = entry.getValue(); String packageVersion = removeVersionQualifier(packageMap.get(VERSION)); /* can't be null */ Set<ClassInfo> projectClasses = getClassesFromPackage(pi, projectJar, packageName, packageVersion); Set<ClassInfo> cis = pi.getClasses(); String previousVersion = null; Set<ClassInfo> previousClasses = null; if (previousExportedPackages.containsKey(packageName)) { Map<String, String> prevPackageMap = previousExportedPackages.get(packageName); previousVersion = prevPackageMap.get(VERSION); previousClasses = getClassesFromPackage(pi, previousJar, packageName, previousVersion); } for (ClassInfo ci : projectClasses) { ClassInfo prevCi = null; if (previousClasses != null) { for (ClassInfo c : previousClasses) { if (c.equals(ci)) { prevCi = c; break; } } } int severity = getModificationSeverity(ci, prevCi); cis.add(ci); if (severity > PKG_SEVERITY_NONE) { // New or modified class if (severity > pi.getSeverity()) { pi.setSeverity(severity); } } } if (pi.getSeverity() > PKG_SEVERITY_NONE) { if (previousClasses == null) { // New package pi.setChangeCode(PackageInfo.CHANGE_CODE_NEW); pi.addSuggestedVersion(packageVersion); } else { // Modified package pi.setCurrentVersion(previousVersion); pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); } } if (pi.getSeverity() == PKG_SEVERITY_NONE) { if (previousClasses != null && previousVersion == null) { // No change, but version missing on package pi.setSeverity(PKG_SEVERITY_MICRO); pi.setChangeCode(PackageInfo.CHANGE_CODE_VERSION_MISSING); pi.addSuggestedVersion(getCurrentVersion()); } } if (previousClasses != null) { pi.setCurrentVersion(previousVersion); for (ClassInfo prevCi : previousClasses) { if (!projectClasses.contains(prevCi)) { int severity = getModificationSeverity(null, prevCi); cis.add(prevCi); if (severity > PKG_SEVERITY_NONE) { // Removed class if (severity > pi.getSeverity()) { pi.setSeverity(severity); } pi.setChangeCode(PackageInfo.CHANGE_CODE_MODIFIED); } } } } } for (Entry<String, Attrs> entry : previousExportedPackages.entrySet()) { String packageName = entry.getKey(); if (!projectExportedPackages.containsKey(packageName)) { // Removed Packages Attrs prevPackageMap = entry.getValue(); String previousVersion = prevPackageMap.get(VERSION); PackageInfo pi = packages.get(packageName); if (pi == null) { pi = new PackageInfo(this, packageName); packages.put(packageName, pi); } pi.setExported(true); pi.setChangeCode(PackageInfo.CHANGE_CODE_REMOVED); Set<ClassInfo> previousClasses = getClassesFromPackage(pi, previousJar, packageName, previousVersion); pi.setClasses(previousClasses); pi.setSeverity(PKG_SEVERITY_MAJOR); for (ClassInfo prevCi : previousClasses) { // Removed class getModificationSeverity(null, prevCi); } pi.setCurrentVersion(previousVersion); } } }
diff --git a/Asteroids/src/GameObjects/ParticleEffects.java b/Asteroids/src/GameObjects/ParticleEffects.java index 2a3c32a..43f9f15 100644 --- a/Asteroids/src/GameObjects/ParticleEffects.java +++ b/Asteroids/src/GameObjects/ParticleEffects.java @@ -1,82 +1,82 @@ package GameObjects; import java.util.Random; import Game.MainGame; import GameComponents.ObjectRenderer.Shape; import GameComponents.RigidBody.ForceMode; import GameComponents.Transform; import Maths.Vector2; public class ParticleEffects extends GameObject { public boolean isTurnedOn = false; public Transform transform; private Particles[] particleArray; public ParticleEffects(Transform transform,int maxParticles) { this.transform = transform; particleArray = new Particles[maxParticles]; } public void Update() { Random ran = new Random(); - Vector2 back = transform.LocalPositionToWorld(new Vector2(0,-1)).Normalized(); + Vector2 back = transform.LocalDirectionToWorld(new Vector2(0,-1)).Normalized(); int shipLength = 15; Vector2 particlePos = transform.LocalPositionToWorld(new Vector2(0,-shipLength)); for(int i = 0; i < particleArray.length; i++) { if( particleArray[i] == null ) { if(ran.nextInt(1000) % 217 == 0 ) { if( isTurnedOn ) { particleArray[i] = new Particles(ran.nextInt(1500)+3000, particlePos); particleArray[i].objectRenderer.shape= Shape.Square; particleArray[i].objectRenderer.SetTexture("smoke"); particleArray[i].rigidBody.frictionCoefficient = 0.01f; particleArray[i].rigidBody.PushForce(new Vector2((ran.nextInt(20))*15*back.x,(ran.nextInt(20))*50*back.y),ForceMode.Impulse); particleArray[i].transform.size = new Vector2((1+ran.nextInt(2)) - 0.075f*ran.nextInt(50)); particleArray[i].rigidBody.PushTorque((ran.nextInt(20) -10) * 10, ForceMode.Impulse); particleArray[i].objectRenderer.opacity = 0.8f; } } } else { if( particleArray[i].TimeToDie() ) { particleArray[i].Delete(); particleArray[i] = null; } else { particleArray[i].Update(); } } } } public void TurnOn() { if( !isTurnedOn ) { isTurnedOn = true; } } public void TurnOff() { if( isTurnedOn ) { isTurnedOn = false; } } }
true
true
public void Update() { Random ran = new Random(); Vector2 back = transform.LocalPositionToWorld(new Vector2(0,-1)).Normalized(); int shipLength = 15; Vector2 particlePos = transform.LocalPositionToWorld(new Vector2(0,-shipLength)); for(int i = 0; i < particleArray.length; i++) { if( particleArray[i] == null ) { if(ran.nextInt(1000) % 217 == 0 ) { if( isTurnedOn ) { particleArray[i] = new Particles(ran.nextInt(1500)+3000, particlePos); particleArray[i].objectRenderer.shape= Shape.Square; particleArray[i].objectRenderer.SetTexture("smoke"); particleArray[i].rigidBody.frictionCoefficient = 0.01f; particleArray[i].rigidBody.PushForce(new Vector2((ran.nextInt(20))*15*back.x,(ran.nextInt(20))*50*back.y),ForceMode.Impulse); particleArray[i].transform.size = new Vector2((1+ran.nextInt(2)) - 0.075f*ran.nextInt(50)); particleArray[i].rigidBody.PushTorque((ran.nextInt(20) -10) * 10, ForceMode.Impulse); particleArray[i].objectRenderer.opacity = 0.8f; } } } else { if( particleArray[i].TimeToDie() ) { particleArray[i].Delete(); particleArray[i] = null; } else { particleArray[i].Update(); } } } }
public void Update() { Random ran = new Random(); Vector2 back = transform.LocalDirectionToWorld(new Vector2(0,-1)).Normalized(); int shipLength = 15; Vector2 particlePos = transform.LocalPositionToWorld(new Vector2(0,-shipLength)); for(int i = 0; i < particleArray.length; i++) { if( particleArray[i] == null ) { if(ran.nextInt(1000) % 217 == 0 ) { if( isTurnedOn ) { particleArray[i] = new Particles(ran.nextInt(1500)+3000, particlePos); particleArray[i].objectRenderer.shape= Shape.Square; particleArray[i].objectRenderer.SetTexture("smoke"); particleArray[i].rigidBody.frictionCoefficient = 0.01f; particleArray[i].rigidBody.PushForce(new Vector2((ran.nextInt(20))*15*back.x,(ran.nextInt(20))*50*back.y),ForceMode.Impulse); particleArray[i].transform.size = new Vector2((1+ran.nextInt(2)) - 0.075f*ran.nextInt(50)); particleArray[i].rigidBody.PushTorque((ran.nextInt(20) -10) * 10, ForceMode.Impulse); particleArray[i].objectRenderer.opacity = 0.8f; } } } else { if( particleArray[i].TimeToDie() ) { particleArray[i].Delete(); particleArray[i] = null; } else { particleArray[i].Update(); } } } }
diff --git a/raisavis/src/main/java/raisa/simulator/SonarDistanceScanner.java b/raisavis/src/main/java/raisa/simulator/SonarDistanceScanner.java index a75a952..406e222 100644 --- a/raisavis/src/main/java/raisa/simulator/SonarDistanceScanner.java +++ b/raisavis/src/main/java/raisa/simulator/SonarDistanceScanner.java @@ -1,29 +1,29 @@ package raisa.simulator; import java.util.Arrays; import java.util.List; import raisa.domain.WorldModel; /** * Makes scans to several directions around central heading and returns the * shortest value. * */ public class SonarDistanceScanner extends IRDistanceScanner { // simulate wide beam by doing several scans and taking the minimum distance private static final List<Float> beamHeadings = Arrays.asList(-5f, -2.5f, 0f, 2.5f, 5f); @Override public float scanDistance(WorldModel worldModel, SimulatorState roverState, float heading) { float min = -1; - for(float beamHeading: beamHeadings) { - float distance = super.scanDistance(worldModel, roverState, heading +180 + beamHeading); + for (float beamHeading : beamHeadings) { + float distance = super.scanDistance(worldModel, roverState, heading + beamHeading); if(min < 0 || (distance > 0 && distance < min)) { min = distance; } } return min; } }
true
true
public float scanDistance(WorldModel worldModel, SimulatorState roverState, float heading) { float min = -1; for(float beamHeading: beamHeadings) { float distance = super.scanDistance(worldModel, roverState, heading +180 + beamHeading); if(min < 0 || (distance > 0 && distance < min)) { min = distance; } } return min; }
public float scanDistance(WorldModel worldModel, SimulatorState roverState, float heading) { float min = -1; for (float beamHeading : beamHeadings) { float distance = super.scanDistance(worldModel, roverState, heading + beamHeading); if(min < 0 || (distance > 0 && distance < min)) { min = distance; } } return min; }
diff --git a/src/simpleserver/stream/StreamTunnel.java b/src/simpleserver/stream/StreamTunnel.java index 828a76c..383bd9b 100644 --- a/src/simpleserver/stream/StreamTunnel.java +++ b/src/simpleserver/stream/StreamTunnel.java @@ -1,1422 +1,1422 @@ /* * Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package simpleserver.stream; import static simpleserver.lang.Translations.t; import static simpleserver.util.Util.print; import static simpleserver.util.Util.println; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import simpleserver.Authenticator.AuthRequest; import simpleserver.Color; import simpleserver.Coordinate; import simpleserver.Coordinate.Dimension; import simpleserver.Main; import simpleserver.Player; import simpleserver.Server; import simpleserver.command.PlayerListCommand; import simpleserver.config.data.Chests.Chest; import simpleserver.config.xml.Config.BlockPermission; public class StreamTunnel { private static final boolean EXPENSIVE_DEBUG_LOGGING = Boolean.getBoolean("EXPENSIVE_DEBUG_LOGGING"); private static final int IDLE_TIME = 30000; private static final int BUFFER_SIZE = 1024; private static final byte BLOCK_DESTROYED_STATUS = 2; private static final Pattern MESSAGE_PATTERN = Pattern.compile("^<([^>]+)> (.*)$"); private static final Pattern COLOR_PATTERN = Pattern.compile("\u00a7[0-9a-z]"); private static final Pattern JOIN_PATTERN = Pattern.compile("\u00a7.((\\d|\\w)*) (joined|left) the game."); private static final String CONSOLE_CHAT_PATTERN = "\\[Server:.*\\]"; private static final int MESSAGE_SIZE = 60; private static final int MAXIMUM_MESSAGE_SIZE = 119; private final boolean isServerTunnel; private final String streamType; private final Player player; private final Server server; private final byte[] buffer; private final Tunneler tunneler; private DataInput in; private DataOutput out; private InputStream inputStream; private OutputStream outputStream; private StreamDumper inputDumper; private StreamDumper outputDumper; private boolean inGame = false; private volatile long lastRead; private volatile boolean run = true; private Byte lastPacket; private char commandPrefix; public StreamTunnel(InputStream in, OutputStream out, boolean isServerTunnel, Player player) { this.isServerTunnel = isServerTunnel; if (isServerTunnel) { streamType = "ServerStream"; } else { streamType = "PlayerStream"; } this.player = player; server = player.getServer(); commandPrefix = server.options.getBoolean("useSlashes") ? '/' : '!'; inputStream = in; outputStream = out; DataInputStream dIn = new DataInputStream(in); DataOutputStream dOut = new DataOutputStream(out); if (EXPENSIVE_DEBUG_LOGGING) { try { OutputStream dump = new FileOutputStream(streamType + "Input.debug"); InputStreamDumper dumper = new InputStreamDumper(dIn, dump); inputDumper = dumper; this.in = dumper; } catch (FileNotFoundException e) { System.out.println("Unable to open input debug dump!"); throw new RuntimeException(e); } try { OutputStream dump = new FileOutputStream(streamType + "Output.debug"); OutputStreamDumper dumper = new OutputStreamDumper(dOut, dump); outputDumper = dumper; this.out = dumper; } catch (FileNotFoundException e) { System.out.println("Unable to open output debug dump!"); throw new RuntimeException(e); } } else { this.in = dIn; this.out = dOut; } buffer = new byte[BUFFER_SIZE]; tunneler = new Tunneler(); tunneler.start(); lastRead = System.currentTimeMillis(); } public void stop() { run = false; } public boolean isAlive() { return tunneler.isAlive(); } public boolean isActive() { return System.currentTimeMillis() - lastRead < IDLE_TIME || player.isRobot(); } private void handlePacket() throws IOException { Byte packetId = in.readByte(); // System.out.println((isServerTunnel ? "server " : "client ") + // String.format("%02x", packetId)); int x; byte y; int z; byte dimension; Coordinate coordinate; switch (packetId) { case 0x00: // Keep Alive write(packetId); write(in.readInt()); // random number that is returned from server break; case 0x01: // Login Request/Response write(packetId); if (!isServerTunnel) { write(in.readInt()); write(readUTF16()); copyNBytes(5); break; } player.setEntityId(write(in.readInt())); write(readUTF16()); write(in.readByte()); dimension = in.readByte(); if (isServerTunnel) { player.setDimension(Dimension.get(dimension)); } write(dimension); write(in.readByte()); write(in.readByte()); if (isServerTunnel) { in.readByte(); write((byte) server.config.properties.getInt("maxPlayers")); } else { write(in.readByte()); } break; case 0x02: // Handshake byte version = in.readByte(); String name = readUTF16(); boolean nameSet = false; if (name.contains(";")) { name = name.substring(0, name.indexOf(";")); } if (name.equals("Player") || !server.authenticator.isMinecraftUp) { AuthRequest req = server.authenticator.getAuthRequest(player.getIPAddress()); if (req != null) { name = req.playerName; nameSet = server.authenticator.completeLogin(req, player); } if (req == null || !nameSet) { if (!name.equals("Player")) { player.addTMessage(Color.RED, "Login verification failed."); player.addTMessage(Color.RED, "You were logged in as guest."); } name = server.authenticator.getFreeGuestName(); player.setGuest(true); nameSet = player.setName(name); } } else { nameSet = player.setName(name); if (nameSet) { player.updateRealName(name); } } if (player.isGuest() && !server.authenticator.allowGuestJoin()) { player.kick(t("Failed to login: User not authenticated")); nameSet = false; } tunneler.setName(streamType + "-" + player.getName()); write(packetId); write(version); write(player.getName()); write(readUTF16()); write(in.readInt()); break; case 0x03: // Chat Message String message = readUTF16(); Matcher joinMatcher = JOIN_PATTERN.matcher(message); if (isServerTunnel && joinMatcher.find()) { if (server.bots.ninja(joinMatcher.group(1))) { break; } if (message.contains("join")) { player.addTMessage(Color.YELLOW, "%s joined the game.", joinMatcher.group(1)); } else { player.addTMessage(Color.YELLOW, "%s left the game.", joinMatcher.group(1)); } break; } if (isServerTunnel && server.config.properties.getBoolean("useMsgFormats")) { if (server.config.properties.getBoolean("forwardChat") && server.getMessager().wasForwarded(message)) { break; } Matcher colorMatcher = COLOR_PATTERN.matcher(message); String cleanMessage = colorMatcher.replaceAll(""); Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage); if (messageMatcher.find()) { } else if (cleanMessage.matches(CONSOLE_CHAT_PATTERN) && !server.config.properties.getBoolean("chatConsoleToOps")) { break; } if (server.config.properties.getBoolean("msgWrap")) { sendMessage(message); } else { if (message.length() > MAXIMUM_MESSAGE_SIZE) { message = message.substring(0, MAXIMUM_MESSAGE_SIZE); } write(packetId); write(message); } } else if (!isServerTunnel) { if (player.isMuted() && !message.startsWith("/") && !message.startsWith("!")) { player.addTMessage(Color.RED, "You are muted! You may not send messages to all players."); break; } if (message.charAt(0) == commandPrefix) { message = player.parseCommand(message, false); if (message == null) { break; } write(packetId); write(message); return; } player.sendMessage(message); } break; case 0x04: // Time Update write(packetId); write(in.readLong()); long time = in.readLong(); server.setTime(time); write(time); break; case 0x05: // Player Inventory write(packetId); write(in.readInt()); write(in.readShort()); copyItem(); break; case 0x06: // Spawn Position write(packetId); copyNBytes(12); if (server.options.getBoolean("enableEvents")) { server.eventhost.execute(server.eventhost.findEvent("onPlayerConnect"), player, true, null); } break; case 0x07: // Use Entity int user = in.readInt(); int target = in.readInt(); Player targetPlayer = server.playerList.findPlayer(target); if (targetPlayer != null) { if (targetPlayer.godModeEnabled()) { in.readBoolean(); break; } } write(packetId); write(user); write(target); copyNBytes(1); break; case 0x08: // Update Health write(packetId); player.updateHealth(write(in.readShort())); player.getHealth(); write(in.readShort()); write(in.readFloat()); break; case 0x09: // Respawn write(packetId); if (!isServerTunnel) { break; } player.setDimension(Dimension.get(write(in.readInt()))); write(in.readByte()); write(in.readByte()); write(in.readShort()); write(readUTF16()); // Added in 1.1 (level type) if (server.options.getBoolean("enableEvents") && isServerTunnel) { server.eventhost.execute(server.eventhost.findEvent("onPlayerRespawn"), player, true, null); } break; case 0x0a: // Player write(packetId); copyNBytes(1); if (!inGame && !isServerTunnel) { player.sendMOTD(); if (server.config.properties.getBoolean("showListOnConnect")) { // display player list if enabled in config player.execute(PlayerListCommand.class); } inGame = true; } break; case 0x0b: // Player Position write(packetId); copyPlayerLocation(); copyNBytes(1); break; case 0x0c: // Player Look write(packetId); copyPlayerLook(); copyNBytes(1); break; case 0x0d: // Player Position & Look write(packetId); copyPlayerLocation(); copyPlayerLook(); copyNBytes(1); break; case 0x0e: // Player Digging if (!isServerTunnel) { byte status = in.readByte(); x = in.readInt(); y = in.readByte(); z = in.readInt(); byte face = in.readByte(); coordinate = new Coordinate(x, y, z, player); if (!player.getGroup().ignoreAreas) { BlockPermission perm = server.config.blockPermission(player, coordinate); if (!perm.use && status == 0) { player.addTMessage(Color.RED, "You can not use this block here!"); break; } if (!perm.destroy && status == BLOCK_DESTROYED_STATUS) { player.addTMessage(Color.RED, "You can not destroy this block!"); break; } } boolean locked = server.data.chests.isLocked(coordinate); if (!locked || player.ignoresChestLocks() || server.data.chests.canOpen(player, coordinate)) { if (locked && status == BLOCK_DESTROYED_STATUS) { server.data.chests.releaseLock(coordinate); server.data.save(); } write(packetId); write(status); write(x); write(y); write(z); write(face); if (player.instantDestroyEnabled()) { packetFinished(); write(packetId); write(BLOCK_DESTROYED_STATUS); write(x); write(y); write(z); write(face); } if (status == BLOCK_DESTROYED_STATUS) { player.destroyedBlock(); } } } else { write(packetId); copyNBytes(11); } break; case 0x0f: // Player Block Placement x = in.readInt(); y = in.readByte(); z = in.readInt(); coordinate = new Coordinate(x, y, z, player); final byte direction = in.readByte(); final short dropItem = in.readShort(); byte itemCount = 0; short uses = 0; byte[] data = null; if (dropItem != -1) { itemCount = in.readByte(); uses = in.readShort(); short dataLength = in.readShort(); if (dataLength != -1) { data = new byte[dataLength]; in.readFully(data); } } byte blockX = in.readByte(); byte blockY = in.readByte(); byte blockZ = in.readByte(); boolean writePacket = true; boolean drop = false; BlockPermission perm = server.config.blockPermission(player, coordinate, dropItem); if (server.options.getBoolean("enableEvents")) { player.checkButtonEvents(new Coordinate(x + (x < 0 ? 1 : 0), y + 1, z + (z < 0 ? 1 : 0))); } if (isServerTunnel || server.data.chests.isChest(coordinate)) { // continue } else if (!player.getGroup().ignoreAreas && ((dropItem != -1 && !perm.place) || !perm.use)) { if (!perm.use) { player.addTMessage(Color.RED, "You can not use this block here!"); } else { player.addTMessage(Color.RED, "You can not place this block here!"); } writePacket = false; drop = true; } else if (dropItem == 54) { int xPosition = x; byte yPosition = y; int zPosition = z; switch (direction) { case 0: --yPosition; break; case 1: ++yPosition; break; case 2: --zPosition; break; case 3: ++zPosition; break; case 4: --xPosition; break; case 5: ++xPosition; break; } Coordinate targetBlock = new Coordinate(xPosition, yPosition, zPosition, player); Chest adjacentChest = server.data.chests.adjacentChest(targetBlock); if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) { player.addTMessage(Color.RED, "The adjacent chest is locked!"); writePacket = false; drop = true; } else { player.placingChest(targetBlock); } } if (writePacket) { write(packetId); write(x); write(y); write(z); write(direction); write(dropItem); if (dropItem != -1) { write(itemCount); write(uses); if (data != null) { write((short) data.length); out.write(data); } else { write((short) -1); } if (dropItem <= 94 && direction >= 0) { player.placedBlock(); } } write(blockX); write(blockY); write(blockZ); player.openingChest(coordinate); } else if (drop) { // Drop the item in hand. This keeps the client state in-sync with the // server. This generally prevents empty-hand clicks by the client // from placing blocks the server thinks the client has in hand. write((byte) 0x0e); write((byte) 0x04); write(x); write(y); write(z); write(direction); } break; case 0x10: // Holding Change write(packetId); copyNBytes(2); break; case 0x11: // Use Bed write(packetId); copyNBytes(14); break; case 0x12: // Animation write(packetId); copyNBytes(5); break; case 0x13: // Entity Action write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x14: // Named Entity Spawn int eid = in.readInt(); name = readUTF16(); if (!server.bots.ninja(name)) { write(packetId); write(eid); write(name); copyNBytes(16); copyUnknownBlob(); } else { skipNBytes(16); skipUnknownBlob(); } break; case 0x15: // Pickup Spawn write(packetId); copyNBytes(4); copyItem(); copyNBytes(15); break; case 0x16: // Collect Item write(packetId); copyNBytes(8); break; case 0x17: // Add Object/Vehicle write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readInt()); int flag = in.readInt(); write(flag); if (flag > 0) { write(in.readShort()); write(in.readShort()); write(in.readShort()); } break; case 0x18: // Mob Spawn write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readByte()); write(in.readByte()); write(in.readShort()); write(in.readShort()); write(in.readShort()); copyUnknownBlob(); break; case 0x19: // Entity: Painting write(packetId); write(in.readInt()); write(readUTF16()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); break; case 0x1a: // Experience Orb write(packetId); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readShort()); break; case 0x1c: // Entity Velocity write(packetId); copyNBytes(10); break; case 0x1d: // Destroy Entity write(packetId); byte destoryCount = write(in.readByte()); if (destoryCount > 0) { copyNBytes(destoryCount * 4); } break; case 0x1e: // Entity write(packetId); copyNBytes(4); break; case 0x1f: // Entity Relative Move write(packetId); copyNBytes(7); break; case 0x20: // Entity Look write(packetId); copyNBytes(6); break; case 0x21: // Entity Look and Relative Move write(packetId); copyNBytes(9); break; case 0x22: // Entity Teleport write(packetId); copyNBytes(18); break; case 0x23: // Entitiy Look write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x26: // Entity Status write(packetId); copyNBytes(5); break; case 0x27: // Attach Entity write(packetId); copyNBytes(8); break; case 0x28: // Entity Metadata write(packetId); write(in.readInt()); copyUnknownBlob(); break; case 0x29: // Entity Effect write(packetId); write(in.readInt()); write(in.readByte()); write(in.readByte()); write(in.readShort()); break; case 0x2a: // Remove Entity Effect write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x2b: // Experience write(packetId); player.updateExperience(write(in.readFloat()), write(in.readShort()), write(in.readShort())); break; case 0x33: // Map Chunk write(packetId); write(in.readInt()); write(in.readInt()); write(in.readBoolean()); write(in.readShort()); write(in.readShort()); copyNBytes(write(in.readInt())); break; case 0x34: // Multi Block Change write(packetId); write(in.readInt()); write(in.readInt()); write(in.readShort()); copyNBytes(write(in.readInt())); break; case 0x35: // Block Change write(packetId); x = in.readInt(); y = in.readByte(); z = in.readInt(); short blockType = in.readShort(); byte metadata = in.readByte(); coordinate = new Coordinate(x, y, z, player); if (blockType == 54 && player.placedChest(coordinate)) { lockChest(coordinate); player.placingChest(null); } write(x); write(y); write(z); write(blockType); write(metadata); break; case 0x36: // Block Action write(packetId); copyNBytes(14); break; case 0x37: // Mining progress write(packetId); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); break; case 0x38: // Chunk Bulk write(packetId); copyNBytes(write(in.readShort()) * 12 + write(in.readInt())); break; case 0x3c: // Explosion write(packetId); copyNBytes(28); int recordCount = in.readInt(); write(recordCount); copyNBytes(recordCount * 3); write(in.readFloat()); write(in.readFloat()); write(in.readFloat()); break; case 0x3d: // Sound/Particle Effect write(packetId); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readByte()); break; case 0x3e: // Named Sound/Particle Effect write(packetId); write(readUTF16()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readFloat()); write(in.readByte()); break; case 0x46: // New/Invalid State write(packetId); write(in.readByte()); write(in.readByte()); break; case 0x47: // Thunderbolt write(packetId); copyNBytes(17); break; case 0x64: // Open Window boolean allow = true; byte id = in.readByte(); byte invtype = in.readByte(); String typeString = readUTF16(); byte unknownByte = in.readByte(); if (invtype == 0) { Chest adjacent = server.data.chests.adjacentChest(player.openedChest()); if (!server.data.chests.isChest(player.openedChest())) { if (adjacent == null) { server.data.chests.addOpenChest(player.openedChest()); } else { server.data.chests.giveLock(adjacent.owner, player.openedChest(), adjacent.name); } server.data.save(); } if (!player.getGroup().ignoreAreas && (!server.config.blockPermission(player, player.openedChest()).chest || (adjacent != null && !server.config.blockPermission(player, adjacent.coordinate).chest))) { player.addTMessage(Color.RED, "You can't use chests here"); allow = false; } else if (server.data.chests.canOpen(player, player.openedChest()) || player.ignoresChestLocks()) { if (server.data.chests.isLocked(player.openedChest())) { if (player.isAttemptingUnlock()) { server.data.chests.unlock(player.openedChest()); server.data.save(); player.setAttemptedAction(null); player.addTMessage(Color.RED, "This chest is no longer locked!"); typeString = t("Open Chest"); } else { typeString = server.data.chests.chestName(player.openedChest()); } } else { typeString = t("Open Chest"); if (player.isAttemptLock()) { lockChest(player.openedChest()); typeString = (player.nextChestName() == null) ? t("Locked Chest") : player.nextChestName(); } } } else { player.addTMessage(Color.RED, "This chest is locked!"); allow = false; } } if (!allow) { write((byte) 0x65); write(id); } else { write(packetId); write(id); write(invtype); write(typeString); write(unknownByte); } break; case 0x65: // Close Window write(packetId); write(in.readByte()); break; case 0x66: // Window Click write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); write(in.readShort()); write(in.readByte()); copyItem(); break; case 0x67: // Set Slot write(packetId); write(in.readByte()); write(in.readShort()); copyItem(); break; case 0x68: // Window Items write(packetId); write(in.readByte()); short count = write(in.readShort()); for (int c = 0; c < count; ++c) { copyItem(); } break; case 0x69: // Update Window Property write(packetId); write(in.readByte()); write(in.readShort()); write(in.readShort()); break; case 0x6a: // Transaction write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); break; case 0x6b: // Creative Inventory Action write(packetId); write(in.readShort()); copyItem(); break; case 0x6c: // Enchant Item write(packetId); write(in.readByte()); write(in.readByte()); break; case (byte) 0x82: // Update Sign write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(readUTF16()); write(readUTF16()); write(readUTF16()); write(readUTF16()); break; case (byte) 0x83: // Item Data write(packetId); write(in.readShort()); write(in.readShort()); short length = in.readShort(); write(length); - copyNBytes(0xff & length); + copyNBytes(length); break; case (byte) 0x84: // added in 12w06a write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(in.readByte()); short nbtLength = write(in.readShort()); if (nbtLength > 0) { copyNBytes(nbtLength); } break; case (byte) 0xc3: // BukkitContrib write(packetId); write(in.readInt()); copyNBytes(write(in.readInt())); break; case (byte) 0xc8: // Increment Statistic write(packetId); copyNBytes(5); break; case (byte) 0xc9: // Player List Item write(packetId); write(readUTF16()); write(in.readByte()); write(in.readShort()); break; case (byte) 0xca: // Player Abilities write(packetId); write(in.readByte()); write(in.readByte()); write(in.readByte()); break; case (byte) 0xcb: // Tab-Completion write(packetId); write(readUTF16()); break; case (byte) 0xcc: // Locale and View Distance write(packetId); write(readUTF16()); write(in.readByte()); write(in.readByte()); write(in.readByte()); write(in.readBoolean()); break; case (byte) 0xcd: // Login & Respawn write(packetId); write(in.readByte()); break; case (byte) 0xd3: // Red Power (mod by Eloraam) write(packetId); copyNBytes(1); copyVLC(); copyVLC(); copyVLC(); copyNBytes((int) copyVLC()); break; case (byte) 0xe6: // ModLoaderMP by SDK write(packetId); write(in.readInt()); // mod write(in.readInt()); // packet id copyNBytes(write(in.readInt()) * 4); // ints copyNBytes(write(in.readInt()) * 4); // floats copyNBytes(write(in.readInt()) * 8); // doubles int sizeString = write(in.readInt()); // strings for (int i = 0; i < sizeString; i++) { copyNBytes(write(in.readInt())); } break; case (byte) 0xfa: // Plugin Message write(packetId); write(readUTF16()); copyNBytes(write(in.readShort())); break; case (byte) 0xfc: // Encryption Key Response byte[] sharedKey = new byte[in.readShort()]; in.readFully(sharedKey); byte[] challengeTokenResponse = new byte[in.readShort()]; in.readFully(challengeTokenResponse); if (!isServerTunnel) { if (!player.clientEncryption.checkChallengeToken(challengeTokenResponse)) { player.kick("Invalid client response"); break; } player.clientEncryption.setEncryptedSharedKey(sharedKey); sharedKey = player.serverEncryption.getEncryptedSharedKey(); } if (!isServerTunnel && server.authenticator.useCustAuth(player) && !server.authenticator.onlineAuthenticate(player)) { player.kick(t("%s Failed to login: User not premium", "[CustAuth]")); break; } write(packetId); write((short) sharedKey.length); write(sharedKey); challengeTokenResponse = player.serverEncryption.encryptChallengeToken(); write((short) challengeTokenResponse.length); write(challengeTokenResponse); if (isServerTunnel) { in = new DataInputStream(new BufferedInputStream(player.serverEncryption.encryptedInputStream(inputStream))); out = new DataOutputStream(new BufferedOutputStream(player.clientEncryption.encryptedOutputStream(outputStream))); } else { in = new DataInputStream(new BufferedInputStream(player.clientEncryption.encryptedInputStream(inputStream))); out = new DataOutputStream(new BufferedOutputStream(player.serverEncryption.encryptedOutputStream(outputStream))); } break; case (byte) 0xfd: // Encryption Key Request (server -> client) tunneler.setName(streamType + "-" + player.getName()); write(packetId); String serverId = readUTF16(); if (!server.authenticator.useCustAuth(player)) { serverId = "-"; } else { serverId = player.getConnectionHash(); } write(serverId); byte[] keyBytes = new byte[in.readShort()]; in.readFully(keyBytes); byte[] challengeToken = new byte[in.readShort()]; in.readFully(challengeToken); player.serverEncryption.setPublicKey(keyBytes); byte[] key = player.clientEncryption.getPublicKey(); write((short) key.length); write(key); write((short) challengeToken.length); write(challengeToken); player.serverEncryption.setChallengeToken(challengeToken); player.clientEncryption.setChallengeToken(challengeToken); break; case (byte) 0xfe: // Server List Ping write(packetId); write(in.readByte()); break; case (byte) 0xff: // Disconnect/Kick write(packetId); String reason = readUTF16(); if (reason.startsWith("\u00a71")) { reason = String.format("\u00a71\0%s\0%s\0%s\0%s\0%s", Main.protocolVersion, Main.minecraftVersion, server.config.properties.get("serverDescription"), server.playerList.size(), server.config.properties.getInt("maxPlayers")); } write(reason); if (reason.startsWith("Took too long")) { server.addRobot(player); } player.close(); break; default: if (EXPENSIVE_DEBUG_LOGGING) { while (true) { skipNBytes(1); flushAll(); } } else { if (lastPacket != null) { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName() + " (after 0x" + Integer.toHexString(lastPacket)); } else { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName()); } } } packetFinished(); lastPacket = (packetId == 0x00) ? lastPacket : packetId; } private void copyItem() throws IOException { if (write(in.readShort()) > 0) { write(in.readByte()); write(in.readShort()); short length; if ((length = write(in.readShort())) > 0) { copyNBytes(length); } } } private long copyVLC() throws IOException { long value = 0; int shift = 0; while (true) { int i = write(in.readByte()); value |= (i & 0x7F) << shift; if ((i & 0x80) == 0) { break; } shift += 7; } return value; } private String readUTF16() throws IOException { short length = in.readShort(); StringBuilder string = new StringBuilder(); for (int i = 0; i < length; i++) { string.append(in.readChar()); } return string.toString(); } private void lockChest(Coordinate coordinate) { Chest adjacentChest = server.data.chests.adjacentChest(coordinate); if (player.isAttemptLock() || adjacentChest != null && !adjacentChest.isOpen()) { if (adjacentChest != null && !adjacentChest.isOpen()) { server.data.chests.giveLock(adjacentChest.owner, coordinate, adjacentChest.name); } else { if (adjacentChest != null) { adjacentChest.lock(player); adjacentChest.name = player.nextChestName(); } server.data.chests.giveLock(player, coordinate, player.nextChestName()); } player.setAttemptedAction(null); player.addTMessage(Color.GRAY, "This chest is now locked."); } else if (!server.data.chests.isChest(coordinate)) { server.data.chests.addOpenChest(coordinate); } server.data.save(); } private void copyPlayerLocation() throws IOException { double x = in.readDouble(); double y = in.readDouble(); double stance = in.readDouble(); double z = in.readDouble(); player.position.updatePosition(x, y, z, stance); if (server.options.getBoolean("enableEvents")) { player.checkLocationEvents(); } write(x); write(y); write(stance); write(z); } private void copyPlayerLook() throws IOException { float yaw = in.readFloat(); float pitch = in.readFloat(); player.position.updateLook(yaw, pitch); write(yaw); write(pitch); } private void copyUnknownBlob() throws IOException { byte unknown = in.readByte(); write(unknown); while (unknown != 0x7f) { int type = (unknown & 0xE0) >> 5; switch (type) { case 0: write(in.readByte()); break; case 1: write(in.readShort()); break; case 2: write(in.readInt()); break; case 3: write(in.readFloat()); break; case 4: write(readUTF16()); break; case 5: copyItem(); } unknown = in.readByte(); write(unknown); } } private void skipUnknownBlob() throws IOException { byte unknown = in.readByte(); while (unknown != 0x7f) { int type = (unknown & 0xE0) >> 5; switch (type) { case 0: in.readByte(); break; case 1: in.readShort(); break; case 2: in.readInt(); break; case 3: in.readFloat(); break; case 4: readUTF16(); break; } unknown = in.readByte(); } } private byte write(byte b) throws IOException { out.writeByte(b); return b; } private byte[] write(byte[] b) throws IOException { out.write(b); return b; } private short write(short s) throws IOException { out.writeShort(s); return s; } private int write(int i) throws IOException { out.writeInt(i); return i; } private long write(long l) throws IOException { out.writeLong(l); return l; } private float write(float f) throws IOException { out.writeFloat(f); return f; } private double write(double d) throws IOException { out.writeDouble(d); return d; } private String write(String s) throws IOException { write((short) s.length()); out.writeChars(s); return s; } private boolean write(boolean b) throws IOException { out.writeBoolean(b); return b; } private void skipNBytes(int bytes) throws IOException { int overflow = bytes / buffer.length; for (int c = 0; c < overflow; ++c) { in.readFully(buffer, 0, buffer.length); } in.readFully(buffer, 0, bytes % buffer.length); } private void copyNBytes(int bytes) throws IOException { int overflow = bytes / buffer.length; for (int c = 0; c < overflow; ++c) { in.readFully(buffer, 0, buffer.length); out.write(buffer, 0, buffer.length); } in.readFully(buffer, 0, bytes % buffer.length); out.write(buffer, 0, bytes % buffer.length); } private void kick(String reason) throws IOException { write((byte) 0xff); write(reason); packetFinished(); } private String getLastColorCode(String message) { String colorCode = ""; int lastIndex = message.lastIndexOf('\u00a7'); if (lastIndex != -1 && lastIndex + 1 < message.length()) { colorCode = message.substring(lastIndex, lastIndex + 2); } return colorCode; } private void sendMessage(String message) throws IOException { if (message.length() > 0) { if (message.length() > MESSAGE_SIZE) { int end = MESSAGE_SIZE - 1; while (end > 0 && message.charAt(end) != ' ') { end--; } if (end == 0) { end = MESSAGE_SIZE; } else { end++; } if (end > 0 && message.charAt(end) == '\u00a7') { end--; } String firstPart = message.substring(0, end); sendMessagePacket(firstPart); sendMessage(getLastColorCode(firstPart) + message.substring(end)); } else { int end = message.length(); if (message.charAt(end - 1) == '\u00a7') { end--; } sendMessagePacket(message.substring(0, end)); } } } private void sendMessagePacket(String message) throws IOException { if (message.length() > MESSAGE_SIZE) { println("Invalid message size: " + message); return; } if (message.length() > 0) { write((byte) 0x03); write(message); packetFinished(); } } private void packetFinished() throws IOException { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.packetFinished(); outputDumper.packetFinished(); } } private void flushAll() throws IOException { try { ((OutputStream) out).flush(); } finally { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.flush(); } } } private final class Tunneler extends Thread { @Override public void run() { try { while (run) { lastRead = System.currentTimeMillis(); try { handlePacket(); if (isServerTunnel) { while (player.hasMessages()) { sendMessage(player.getMessage()); } } else { while (player.hasForwardMessages()) { sendMessage(player.getForwardMessage()); } } flushAll(); } catch (IOException e) { if (run && !player.isRobot()) { println(e); print(streamType + " error handling traffic for " + player.getIPAddress()); if (lastPacket != null) { System.out.print(" (" + Integer.toHexString(lastPacket) + ")"); } System.out.println(); } break; } } try { if (player.isKicked()) { kick(player.getKickMsg()); } flushAll(); } catch (IOException e) { } } finally { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.cleanup(); outputDumper.cleanup(); } } } } }
true
true
private void handlePacket() throws IOException { Byte packetId = in.readByte(); // System.out.println((isServerTunnel ? "server " : "client ") + // String.format("%02x", packetId)); int x; byte y; int z; byte dimension; Coordinate coordinate; switch (packetId) { case 0x00: // Keep Alive write(packetId); write(in.readInt()); // random number that is returned from server break; case 0x01: // Login Request/Response write(packetId); if (!isServerTunnel) { write(in.readInt()); write(readUTF16()); copyNBytes(5); break; } player.setEntityId(write(in.readInt())); write(readUTF16()); write(in.readByte()); dimension = in.readByte(); if (isServerTunnel) { player.setDimension(Dimension.get(dimension)); } write(dimension); write(in.readByte()); write(in.readByte()); if (isServerTunnel) { in.readByte(); write((byte) server.config.properties.getInt("maxPlayers")); } else { write(in.readByte()); } break; case 0x02: // Handshake byte version = in.readByte(); String name = readUTF16(); boolean nameSet = false; if (name.contains(";")) { name = name.substring(0, name.indexOf(";")); } if (name.equals("Player") || !server.authenticator.isMinecraftUp) { AuthRequest req = server.authenticator.getAuthRequest(player.getIPAddress()); if (req != null) { name = req.playerName; nameSet = server.authenticator.completeLogin(req, player); } if (req == null || !nameSet) { if (!name.equals("Player")) { player.addTMessage(Color.RED, "Login verification failed."); player.addTMessage(Color.RED, "You were logged in as guest."); } name = server.authenticator.getFreeGuestName(); player.setGuest(true); nameSet = player.setName(name); } } else { nameSet = player.setName(name); if (nameSet) { player.updateRealName(name); } } if (player.isGuest() && !server.authenticator.allowGuestJoin()) { player.kick(t("Failed to login: User not authenticated")); nameSet = false; } tunneler.setName(streamType + "-" + player.getName()); write(packetId); write(version); write(player.getName()); write(readUTF16()); write(in.readInt()); break; case 0x03: // Chat Message String message = readUTF16(); Matcher joinMatcher = JOIN_PATTERN.matcher(message); if (isServerTunnel && joinMatcher.find()) { if (server.bots.ninja(joinMatcher.group(1))) { break; } if (message.contains("join")) { player.addTMessage(Color.YELLOW, "%s joined the game.", joinMatcher.group(1)); } else { player.addTMessage(Color.YELLOW, "%s left the game.", joinMatcher.group(1)); } break; } if (isServerTunnel && server.config.properties.getBoolean("useMsgFormats")) { if (server.config.properties.getBoolean("forwardChat") && server.getMessager().wasForwarded(message)) { break; } Matcher colorMatcher = COLOR_PATTERN.matcher(message); String cleanMessage = colorMatcher.replaceAll(""); Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage); if (messageMatcher.find()) { } else if (cleanMessage.matches(CONSOLE_CHAT_PATTERN) && !server.config.properties.getBoolean("chatConsoleToOps")) { break; } if (server.config.properties.getBoolean("msgWrap")) { sendMessage(message); } else { if (message.length() > MAXIMUM_MESSAGE_SIZE) { message = message.substring(0, MAXIMUM_MESSAGE_SIZE); } write(packetId); write(message); } } else if (!isServerTunnel) { if (player.isMuted() && !message.startsWith("/") && !message.startsWith("!")) { player.addTMessage(Color.RED, "You are muted! You may not send messages to all players."); break; } if (message.charAt(0) == commandPrefix) { message = player.parseCommand(message, false); if (message == null) { break; } write(packetId); write(message); return; } player.sendMessage(message); } break; case 0x04: // Time Update write(packetId); write(in.readLong()); long time = in.readLong(); server.setTime(time); write(time); break; case 0x05: // Player Inventory write(packetId); write(in.readInt()); write(in.readShort()); copyItem(); break; case 0x06: // Spawn Position write(packetId); copyNBytes(12); if (server.options.getBoolean("enableEvents")) { server.eventhost.execute(server.eventhost.findEvent("onPlayerConnect"), player, true, null); } break; case 0x07: // Use Entity int user = in.readInt(); int target = in.readInt(); Player targetPlayer = server.playerList.findPlayer(target); if (targetPlayer != null) { if (targetPlayer.godModeEnabled()) { in.readBoolean(); break; } } write(packetId); write(user); write(target); copyNBytes(1); break; case 0x08: // Update Health write(packetId); player.updateHealth(write(in.readShort())); player.getHealth(); write(in.readShort()); write(in.readFloat()); break; case 0x09: // Respawn write(packetId); if (!isServerTunnel) { break; } player.setDimension(Dimension.get(write(in.readInt()))); write(in.readByte()); write(in.readByte()); write(in.readShort()); write(readUTF16()); // Added in 1.1 (level type) if (server.options.getBoolean("enableEvents") && isServerTunnel) { server.eventhost.execute(server.eventhost.findEvent("onPlayerRespawn"), player, true, null); } break; case 0x0a: // Player write(packetId); copyNBytes(1); if (!inGame && !isServerTunnel) { player.sendMOTD(); if (server.config.properties.getBoolean("showListOnConnect")) { // display player list if enabled in config player.execute(PlayerListCommand.class); } inGame = true; } break; case 0x0b: // Player Position write(packetId); copyPlayerLocation(); copyNBytes(1); break; case 0x0c: // Player Look write(packetId); copyPlayerLook(); copyNBytes(1); break; case 0x0d: // Player Position & Look write(packetId); copyPlayerLocation(); copyPlayerLook(); copyNBytes(1); break; case 0x0e: // Player Digging if (!isServerTunnel) { byte status = in.readByte(); x = in.readInt(); y = in.readByte(); z = in.readInt(); byte face = in.readByte(); coordinate = new Coordinate(x, y, z, player); if (!player.getGroup().ignoreAreas) { BlockPermission perm = server.config.blockPermission(player, coordinate); if (!perm.use && status == 0) { player.addTMessage(Color.RED, "You can not use this block here!"); break; } if (!perm.destroy && status == BLOCK_DESTROYED_STATUS) { player.addTMessage(Color.RED, "You can not destroy this block!"); break; } } boolean locked = server.data.chests.isLocked(coordinate); if (!locked || player.ignoresChestLocks() || server.data.chests.canOpen(player, coordinate)) { if (locked && status == BLOCK_DESTROYED_STATUS) { server.data.chests.releaseLock(coordinate); server.data.save(); } write(packetId); write(status); write(x); write(y); write(z); write(face); if (player.instantDestroyEnabled()) { packetFinished(); write(packetId); write(BLOCK_DESTROYED_STATUS); write(x); write(y); write(z); write(face); } if (status == BLOCK_DESTROYED_STATUS) { player.destroyedBlock(); } } } else { write(packetId); copyNBytes(11); } break; case 0x0f: // Player Block Placement x = in.readInt(); y = in.readByte(); z = in.readInt(); coordinate = new Coordinate(x, y, z, player); final byte direction = in.readByte(); final short dropItem = in.readShort(); byte itemCount = 0; short uses = 0; byte[] data = null; if (dropItem != -1) { itemCount = in.readByte(); uses = in.readShort(); short dataLength = in.readShort(); if (dataLength != -1) { data = new byte[dataLength]; in.readFully(data); } } byte blockX = in.readByte(); byte blockY = in.readByte(); byte blockZ = in.readByte(); boolean writePacket = true; boolean drop = false; BlockPermission perm = server.config.blockPermission(player, coordinate, dropItem); if (server.options.getBoolean("enableEvents")) { player.checkButtonEvents(new Coordinate(x + (x < 0 ? 1 : 0), y + 1, z + (z < 0 ? 1 : 0))); } if (isServerTunnel || server.data.chests.isChest(coordinate)) { // continue } else if (!player.getGroup().ignoreAreas && ((dropItem != -1 && !perm.place) || !perm.use)) { if (!perm.use) { player.addTMessage(Color.RED, "You can not use this block here!"); } else { player.addTMessage(Color.RED, "You can not place this block here!"); } writePacket = false; drop = true; } else if (dropItem == 54) { int xPosition = x; byte yPosition = y; int zPosition = z; switch (direction) { case 0: --yPosition; break; case 1: ++yPosition; break; case 2: --zPosition; break; case 3: ++zPosition; break; case 4: --xPosition; break; case 5: ++xPosition; break; } Coordinate targetBlock = new Coordinate(xPosition, yPosition, zPosition, player); Chest adjacentChest = server.data.chests.adjacentChest(targetBlock); if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) { player.addTMessage(Color.RED, "The adjacent chest is locked!"); writePacket = false; drop = true; } else { player.placingChest(targetBlock); } } if (writePacket) { write(packetId); write(x); write(y); write(z); write(direction); write(dropItem); if (dropItem != -1) { write(itemCount); write(uses); if (data != null) { write((short) data.length); out.write(data); } else { write((short) -1); } if (dropItem <= 94 && direction >= 0) { player.placedBlock(); } } write(blockX); write(blockY); write(blockZ); player.openingChest(coordinate); } else if (drop) { // Drop the item in hand. This keeps the client state in-sync with the // server. This generally prevents empty-hand clicks by the client // from placing blocks the server thinks the client has in hand. write((byte) 0x0e); write((byte) 0x04); write(x); write(y); write(z); write(direction); } break; case 0x10: // Holding Change write(packetId); copyNBytes(2); break; case 0x11: // Use Bed write(packetId); copyNBytes(14); break; case 0x12: // Animation write(packetId); copyNBytes(5); break; case 0x13: // Entity Action write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x14: // Named Entity Spawn int eid = in.readInt(); name = readUTF16(); if (!server.bots.ninja(name)) { write(packetId); write(eid); write(name); copyNBytes(16); copyUnknownBlob(); } else { skipNBytes(16); skipUnknownBlob(); } break; case 0x15: // Pickup Spawn write(packetId); copyNBytes(4); copyItem(); copyNBytes(15); break; case 0x16: // Collect Item write(packetId); copyNBytes(8); break; case 0x17: // Add Object/Vehicle write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readInt()); int flag = in.readInt(); write(flag); if (flag > 0) { write(in.readShort()); write(in.readShort()); write(in.readShort()); } break; case 0x18: // Mob Spawn write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readByte()); write(in.readByte()); write(in.readShort()); write(in.readShort()); write(in.readShort()); copyUnknownBlob(); break; case 0x19: // Entity: Painting write(packetId); write(in.readInt()); write(readUTF16()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); break; case 0x1a: // Experience Orb write(packetId); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readShort()); break; case 0x1c: // Entity Velocity write(packetId); copyNBytes(10); break; case 0x1d: // Destroy Entity write(packetId); byte destoryCount = write(in.readByte()); if (destoryCount > 0) { copyNBytes(destoryCount * 4); } break; case 0x1e: // Entity write(packetId); copyNBytes(4); break; case 0x1f: // Entity Relative Move write(packetId); copyNBytes(7); break; case 0x20: // Entity Look write(packetId); copyNBytes(6); break; case 0x21: // Entity Look and Relative Move write(packetId); copyNBytes(9); break; case 0x22: // Entity Teleport write(packetId); copyNBytes(18); break; case 0x23: // Entitiy Look write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x26: // Entity Status write(packetId); copyNBytes(5); break; case 0x27: // Attach Entity write(packetId); copyNBytes(8); break; case 0x28: // Entity Metadata write(packetId); write(in.readInt()); copyUnknownBlob(); break; case 0x29: // Entity Effect write(packetId); write(in.readInt()); write(in.readByte()); write(in.readByte()); write(in.readShort()); break; case 0x2a: // Remove Entity Effect write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x2b: // Experience write(packetId); player.updateExperience(write(in.readFloat()), write(in.readShort()), write(in.readShort())); break; case 0x33: // Map Chunk write(packetId); write(in.readInt()); write(in.readInt()); write(in.readBoolean()); write(in.readShort()); write(in.readShort()); copyNBytes(write(in.readInt())); break; case 0x34: // Multi Block Change write(packetId); write(in.readInt()); write(in.readInt()); write(in.readShort()); copyNBytes(write(in.readInt())); break; case 0x35: // Block Change write(packetId); x = in.readInt(); y = in.readByte(); z = in.readInt(); short blockType = in.readShort(); byte metadata = in.readByte(); coordinate = new Coordinate(x, y, z, player); if (blockType == 54 && player.placedChest(coordinate)) { lockChest(coordinate); player.placingChest(null); } write(x); write(y); write(z); write(blockType); write(metadata); break; case 0x36: // Block Action write(packetId); copyNBytes(14); break; case 0x37: // Mining progress write(packetId); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); break; case 0x38: // Chunk Bulk write(packetId); copyNBytes(write(in.readShort()) * 12 + write(in.readInt())); break; case 0x3c: // Explosion write(packetId); copyNBytes(28); int recordCount = in.readInt(); write(recordCount); copyNBytes(recordCount * 3); write(in.readFloat()); write(in.readFloat()); write(in.readFloat()); break; case 0x3d: // Sound/Particle Effect write(packetId); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readByte()); break; case 0x3e: // Named Sound/Particle Effect write(packetId); write(readUTF16()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readFloat()); write(in.readByte()); break; case 0x46: // New/Invalid State write(packetId); write(in.readByte()); write(in.readByte()); break; case 0x47: // Thunderbolt write(packetId); copyNBytes(17); break; case 0x64: // Open Window boolean allow = true; byte id = in.readByte(); byte invtype = in.readByte(); String typeString = readUTF16(); byte unknownByte = in.readByte(); if (invtype == 0) { Chest adjacent = server.data.chests.adjacentChest(player.openedChest()); if (!server.data.chests.isChest(player.openedChest())) { if (adjacent == null) { server.data.chests.addOpenChest(player.openedChest()); } else { server.data.chests.giveLock(adjacent.owner, player.openedChest(), adjacent.name); } server.data.save(); } if (!player.getGroup().ignoreAreas && (!server.config.blockPermission(player, player.openedChest()).chest || (adjacent != null && !server.config.blockPermission(player, adjacent.coordinate).chest))) { player.addTMessage(Color.RED, "You can't use chests here"); allow = false; } else if (server.data.chests.canOpen(player, player.openedChest()) || player.ignoresChestLocks()) { if (server.data.chests.isLocked(player.openedChest())) { if (player.isAttemptingUnlock()) { server.data.chests.unlock(player.openedChest()); server.data.save(); player.setAttemptedAction(null); player.addTMessage(Color.RED, "This chest is no longer locked!"); typeString = t("Open Chest"); } else { typeString = server.data.chests.chestName(player.openedChest()); } } else { typeString = t("Open Chest"); if (player.isAttemptLock()) { lockChest(player.openedChest()); typeString = (player.nextChestName() == null) ? t("Locked Chest") : player.nextChestName(); } } } else { player.addTMessage(Color.RED, "This chest is locked!"); allow = false; } } if (!allow) { write((byte) 0x65); write(id); } else { write(packetId); write(id); write(invtype); write(typeString); write(unknownByte); } break; case 0x65: // Close Window write(packetId); write(in.readByte()); break; case 0x66: // Window Click write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); write(in.readShort()); write(in.readByte()); copyItem(); break; case 0x67: // Set Slot write(packetId); write(in.readByte()); write(in.readShort()); copyItem(); break; case 0x68: // Window Items write(packetId); write(in.readByte()); short count = write(in.readShort()); for (int c = 0; c < count; ++c) { copyItem(); } break; case 0x69: // Update Window Property write(packetId); write(in.readByte()); write(in.readShort()); write(in.readShort()); break; case 0x6a: // Transaction write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); break; case 0x6b: // Creative Inventory Action write(packetId); write(in.readShort()); copyItem(); break; case 0x6c: // Enchant Item write(packetId); write(in.readByte()); write(in.readByte()); break; case (byte) 0x82: // Update Sign write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(readUTF16()); write(readUTF16()); write(readUTF16()); write(readUTF16()); break; case (byte) 0x83: // Item Data write(packetId); write(in.readShort()); write(in.readShort()); short length = in.readShort(); write(length); copyNBytes(0xff & length); break; case (byte) 0x84: // added in 12w06a write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(in.readByte()); short nbtLength = write(in.readShort()); if (nbtLength > 0) { copyNBytes(nbtLength); } break; case (byte) 0xc3: // BukkitContrib write(packetId); write(in.readInt()); copyNBytes(write(in.readInt())); break; case (byte) 0xc8: // Increment Statistic write(packetId); copyNBytes(5); break; case (byte) 0xc9: // Player List Item write(packetId); write(readUTF16()); write(in.readByte()); write(in.readShort()); break; case (byte) 0xca: // Player Abilities write(packetId); write(in.readByte()); write(in.readByte()); write(in.readByte()); break; case (byte) 0xcb: // Tab-Completion write(packetId); write(readUTF16()); break; case (byte) 0xcc: // Locale and View Distance write(packetId); write(readUTF16()); write(in.readByte()); write(in.readByte()); write(in.readByte()); write(in.readBoolean()); break; case (byte) 0xcd: // Login & Respawn write(packetId); write(in.readByte()); break; case (byte) 0xd3: // Red Power (mod by Eloraam) write(packetId); copyNBytes(1); copyVLC(); copyVLC(); copyVLC(); copyNBytes((int) copyVLC()); break; case (byte) 0xe6: // ModLoaderMP by SDK write(packetId); write(in.readInt()); // mod write(in.readInt()); // packet id copyNBytes(write(in.readInt()) * 4); // ints copyNBytes(write(in.readInt()) * 4); // floats copyNBytes(write(in.readInt()) * 8); // doubles int sizeString = write(in.readInt()); // strings for (int i = 0; i < sizeString; i++) { copyNBytes(write(in.readInt())); } break; case (byte) 0xfa: // Plugin Message write(packetId); write(readUTF16()); copyNBytes(write(in.readShort())); break; case (byte) 0xfc: // Encryption Key Response byte[] sharedKey = new byte[in.readShort()]; in.readFully(sharedKey); byte[] challengeTokenResponse = new byte[in.readShort()]; in.readFully(challengeTokenResponse); if (!isServerTunnel) { if (!player.clientEncryption.checkChallengeToken(challengeTokenResponse)) { player.kick("Invalid client response"); break; } player.clientEncryption.setEncryptedSharedKey(sharedKey); sharedKey = player.serverEncryption.getEncryptedSharedKey(); } if (!isServerTunnel && server.authenticator.useCustAuth(player) && !server.authenticator.onlineAuthenticate(player)) { player.kick(t("%s Failed to login: User not premium", "[CustAuth]")); break; } write(packetId); write((short) sharedKey.length); write(sharedKey); challengeTokenResponse = player.serverEncryption.encryptChallengeToken(); write((short) challengeTokenResponse.length); write(challengeTokenResponse); if (isServerTunnel) { in = new DataInputStream(new BufferedInputStream(player.serverEncryption.encryptedInputStream(inputStream))); out = new DataOutputStream(new BufferedOutputStream(player.clientEncryption.encryptedOutputStream(outputStream))); } else { in = new DataInputStream(new BufferedInputStream(player.clientEncryption.encryptedInputStream(inputStream))); out = new DataOutputStream(new BufferedOutputStream(player.serverEncryption.encryptedOutputStream(outputStream))); } break; case (byte) 0xfd: // Encryption Key Request (server -> client) tunneler.setName(streamType + "-" + player.getName()); write(packetId); String serverId = readUTF16(); if (!server.authenticator.useCustAuth(player)) { serverId = "-"; } else { serverId = player.getConnectionHash(); } write(serverId); byte[] keyBytes = new byte[in.readShort()]; in.readFully(keyBytes); byte[] challengeToken = new byte[in.readShort()]; in.readFully(challengeToken); player.serverEncryption.setPublicKey(keyBytes); byte[] key = player.clientEncryption.getPublicKey(); write((short) key.length); write(key); write((short) challengeToken.length); write(challengeToken); player.serverEncryption.setChallengeToken(challengeToken); player.clientEncryption.setChallengeToken(challengeToken); break; case (byte) 0xfe: // Server List Ping write(packetId); write(in.readByte()); break; case (byte) 0xff: // Disconnect/Kick write(packetId); String reason = readUTF16(); if (reason.startsWith("\u00a71")) { reason = String.format("\u00a71\0%s\0%s\0%s\0%s\0%s", Main.protocolVersion, Main.minecraftVersion, server.config.properties.get("serverDescription"), server.playerList.size(), server.config.properties.getInt("maxPlayers")); } write(reason); if (reason.startsWith("Took too long")) { server.addRobot(player); } player.close(); break; default: if (EXPENSIVE_DEBUG_LOGGING) { while (true) { skipNBytes(1); flushAll(); } } else { if (lastPacket != null) { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName() + " (after 0x" + Integer.toHexString(lastPacket)); } else { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName()); } } } packetFinished(); lastPacket = (packetId == 0x00) ? lastPacket : packetId; }
private void handlePacket() throws IOException { Byte packetId = in.readByte(); // System.out.println((isServerTunnel ? "server " : "client ") + // String.format("%02x", packetId)); int x; byte y; int z; byte dimension; Coordinate coordinate; switch (packetId) { case 0x00: // Keep Alive write(packetId); write(in.readInt()); // random number that is returned from server break; case 0x01: // Login Request/Response write(packetId); if (!isServerTunnel) { write(in.readInt()); write(readUTF16()); copyNBytes(5); break; } player.setEntityId(write(in.readInt())); write(readUTF16()); write(in.readByte()); dimension = in.readByte(); if (isServerTunnel) { player.setDimension(Dimension.get(dimension)); } write(dimension); write(in.readByte()); write(in.readByte()); if (isServerTunnel) { in.readByte(); write((byte) server.config.properties.getInt("maxPlayers")); } else { write(in.readByte()); } break; case 0x02: // Handshake byte version = in.readByte(); String name = readUTF16(); boolean nameSet = false; if (name.contains(";")) { name = name.substring(0, name.indexOf(";")); } if (name.equals("Player") || !server.authenticator.isMinecraftUp) { AuthRequest req = server.authenticator.getAuthRequest(player.getIPAddress()); if (req != null) { name = req.playerName; nameSet = server.authenticator.completeLogin(req, player); } if (req == null || !nameSet) { if (!name.equals("Player")) { player.addTMessage(Color.RED, "Login verification failed."); player.addTMessage(Color.RED, "You were logged in as guest."); } name = server.authenticator.getFreeGuestName(); player.setGuest(true); nameSet = player.setName(name); } } else { nameSet = player.setName(name); if (nameSet) { player.updateRealName(name); } } if (player.isGuest() && !server.authenticator.allowGuestJoin()) { player.kick(t("Failed to login: User not authenticated")); nameSet = false; } tunneler.setName(streamType + "-" + player.getName()); write(packetId); write(version); write(player.getName()); write(readUTF16()); write(in.readInt()); break; case 0x03: // Chat Message String message = readUTF16(); Matcher joinMatcher = JOIN_PATTERN.matcher(message); if (isServerTunnel && joinMatcher.find()) { if (server.bots.ninja(joinMatcher.group(1))) { break; } if (message.contains("join")) { player.addTMessage(Color.YELLOW, "%s joined the game.", joinMatcher.group(1)); } else { player.addTMessage(Color.YELLOW, "%s left the game.", joinMatcher.group(1)); } break; } if (isServerTunnel && server.config.properties.getBoolean("useMsgFormats")) { if (server.config.properties.getBoolean("forwardChat") && server.getMessager().wasForwarded(message)) { break; } Matcher colorMatcher = COLOR_PATTERN.matcher(message); String cleanMessage = colorMatcher.replaceAll(""); Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage); if (messageMatcher.find()) { } else if (cleanMessage.matches(CONSOLE_CHAT_PATTERN) && !server.config.properties.getBoolean("chatConsoleToOps")) { break; } if (server.config.properties.getBoolean("msgWrap")) { sendMessage(message); } else { if (message.length() > MAXIMUM_MESSAGE_SIZE) { message = message.substring(0, MAXIMUM_MESSAGE_SIZE); } write(packetId); write(message); } } else if (!isServerTunnel) { if (player.isMuted() && !message.startsWith("/") && !message.startsWith("!")) { player.addTMessage(Color.RED, "You are muted! You may not send messages to all players."); break; } if (message.charAt(0) == commandPrefix) { message = player.parseCommand(message, false); if (message == null) { break; } write(packetId); write(message); return; } player.sendMessage(message); } break; case 0x04: // Time Update write(packetId); write(in.readLong()); long time = in.readLong(); server.setTime(time); write(time); break; case 0x05: // Player Inventory write(packetId); write(in.readInt()); write(in.readShort()); copyItem(); break; case 0x06: // Spawn Position write(packetId); copyNBytes(12); if (server.options.getBoolean("enableEvents")) { server.eventhost.execute(server.eventhost.findEvent("onPlayerConnect"), player, true, null); } break; case 0x07: // Use Entity int user = in.readInt(); int target = in.readInt(); Player targetPlayer = server.playerList.findPlayer(target); if (targetPlayer != null) { if (targetPlayer.godModeEnabled()) { in.readBoolean(); break; } } write(packetId); write(user); write(target); copyNBytes(1); break; case 0x08: // Update Health write(packetId); player.updateHealth(write(in.readShort())); player.getHealth(); write(in.readShort()); write(in.readFloat()); break; case 0x09: // Respawn write(packetId); if (!isServerTunnel) { break; } player.setDimension(Dimension.get(write(in.readInt()))); write(in.readByte()); write(in.readByte()); write(in.readShort()); write(readUTF16()); // Added in 1.1 (level type) if (server.options.getBoolean("enableEvents") && isServerTunnel) { server.eventhost.execute(server.eventhost.findEvent("onPlayerRespawn"), player, true, null); } break; case 0x0a: // Player write(packetId); copyNBytes(1); if (!inGame && !isServerTunnel) { player.sendMOTD(); if (server.config.properties.getBoolean("showListOnConnect")) { // display player list if enabled in config player.execute(PlayerListCommand.class); } inGame = true; } break; case 0x0b: // Player Position write(packetId); copyPlayerLocation(); copyNBytes(1); break; case 0x0c: // Player Look write(packetId); copyPlayerLook(); copyNBytes(1); break; case 0x0d: // Player Position & Look write(packetId); copyPlayerLocation(); copyPlayerLook(); copyNBytes(1); break; case 0x0e: // Player Digging if (!isServerTunnel) { byte status = in.readByte(); x = in.readInt(); y = in.readByte(); z = in.readInt(); byte face = in.readByte(); coordinate = new Coordinate(x, y, z, player); if (!player.getGroup().ignoreAreas) { BlockPermission perm = server.config.blockPermission(player, coordinate); if (!perm.use && status == 0) { player.addTMessage(Color.RED, "You can not use this block here!"); break; } if (!perm.destroy && status == BLOCK_DESTROYED_STATUS) { player.addTMessage(Color.RED, "You can not destroy this block!"); break; } } boolean locked = server.data.chests.isLocked(coordinate); if (!locked || player.ignoresChestLocks() || server.data.chests.canOpen(player, coordinate)) { if (locked && status == BLOCK_DESTROYED_STATUS) { server.data.chests.releaseLock(coordinate); server.data.save(); } write(packetId); write(status); write(x); write(y); write(z); write(face); if (player.instantDestroyEnabled()) { packetFinished(); write(packetId); write(BLOCK_DESTROYED_STATUS); write(x); write(y); write(z); write(face); } if (status == BLOCK_DESTROYED_STATUS) { player.destroyedBlock(); } } } else { write(packetId); copyNBytes(11); } break; case 0x0f: // Player Block Placement x = in.readInt(); y = in.readByte(); z = in.readInt(); coordinate = new Coordinate(x, y, z, player); final byte direction = in.readByte(); final short dropItem = in.readShort(); byte itemCount = 0; short uses = 0; byte[] data = null; if (dropItem != -1) { itemCount = in.readByte(); uses = in.readShort(); short dataLength = in.readShort(); if (dataLength != -1) { data = new byte[dataLength]; in.readFully(data); } } byte blockX = in.readByte(); byte blockY = in.readByte(); byte blockZ = in.readByte(); boolean writePacket = true; boolean drop = false; BlockPermission perm = server.config.blockPermission(player, coordinate, dropItem); if (server.options.getBoolean("enableEvents")) { player.checkButtonEvents(new Coordinate(x + (x < 0 ? 1 : 0), y + 1, z + (z < 0 ? 1 : 0))); } if (isServerTunnel || server.data.chests.isChest(coordinate)) { // continue } else if (!player.getGroup().ignoreAreas && ((dropItem != -1 && !perm.place) || !perm.use)) { if (!perm.use) { player.addTMessage(Color.RED, "You can not use this block here!"); } else { player.addTMessage(Color.RED, "You can not place this block here!"); } writePacket = false; drop = true; } else if (dropItem == 54) { int xPosition = x; byte yPosition = y; int zPosition = z; switch (direction) { case 0: --yPosition; break; case 1: ++yPosition; break; case 2: --zPosition; break; case 3: ++zPosition; break; case 4: --xPosition; break; case 5: ++xPosition; break; } Coordinate targetBlock = new Coordinate(xPosition, yPosition, zPosition, player); Chest adjacentChest = server.data.chests.adjacentChest(targetBlock); if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) { player.addTMessage(Color.RED, "The adjacent chest is locked!"); writePacket = false; drop = true; } else { player.placingChest(targetBlock); } } if (writePacket) { write(packetId); write(x); write(y); write(z); write(direction); write(dropItem); if (dropItem != -1) { write(itemCount); write(uses); if (data != null) { write((short) data.length); out.write(data); } else { write((short) -1); } if (dropItem <= 94 && direction >= 0) { player.placedBlock(); } } write(blockX); write(blockY); write(blockZ); player.openingChest(coordinate); } else if (drop) { // Drop the item in hand. This keeps the client state in-sync with the // server. This generally prevents empty-hand clicks by the client // from placing blocks the server thinks the client has in hand. write((byte) 0x0e); write((byte) 0x04); write(x); write(y); write(z); write(direction); } break; case 0x10: // Holding Change write(packetId); copyNBytes(2); break; case 0x11: // Use Bed write(packetId); copyNBytes(14); break; case 0x12: // Animation write(packetId); copyNBytes(5); break; case 0x13: // Entity Action write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x14: // Named Entity Spawn int eid = in.readInt(); name = readUTF16(); if (!server.bots.ninja(name)) { write(packetId); write(eid); write(name); copyNBytes(16); copyUnknownBlob(); } else { skipNBytes(16); skipUnknownBlob(); } break; case 0x15: // Pickup Spawn write(packetId); copyNBytes(4); copyItem(); copyNBytes(15); break; case 0x16: // Collect Item write(packetId); copyNBytes(8); break; case 0x17: // Add Object/Vehicle write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readInt()); int flag = in.readInt(); write(flag); if (flag > 0) { write(in.readShort()); write(in.readShort()); write(in.readShort()); } break; case 0x18: // Mob Spawn write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readByte()); write(in.readByte()); write(in.readShort()); write(in.readShort()); write(in.readShort()); copyUnknownBlob(); break; case 0x19: // Entity: Painting write(packetId); write(in.readInt()); write(readUTF16()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); break; case 0x1a: // Experience Orb write(packetId); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readShort()); break; case 0x1c: // Entity Velocity write(packetId); copyNBytes(10); break; case 0x1d: // Destroy Entity write(packetId); byte destoryCount = write(in.readByte()); if (destoryCount > 0) { copyNBytes(destoryCount * 4); } break; case 0x1e: // Entity write(packetId); copyNBytes(4); break; case 0x1f: // Entity Relative Move write(packetId); copyNBytes(7); break; case 0x20: // Entity Look write(packetId); copyNBytes(6); break; case 0x21: // Entity Look and Relative Move write(packetId); copyNBytes(9); break; case 0x22: // Entity Teleport write(packetId); copyNBytes(18); break; case 0x23: // Entitiy Look write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x26: // Entity Status write(packetId); copyNBytes(5); break; case 0x27: // Attach Entity write(packetId); copyNBytes(8); break; case 0x28: // Entity Metadata write(packetId); write(in.readInt()); copyUnknownBlob(); break; case 0x29: // Entity Effect write(packetId); write(in.readInt()); write(in.readByte()); write(in.readByte()); write(in.readShort()); break; case 0x2a: // Remove Entity Effect write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x2b: // Experience write(packetId); player.updateExperience(write(in.readFloat()), write(in.readShort()), write(in.readShort())); break; case 0x33: // Map Chunk write(packetId); write(in.readInt()); write(in.readInt()); write(in.readBoolean()); write(in.readShort()); write(in.readShort()); copyNBytes(write(in.readInt())); break; case 0x34: // Multi Block Change write(packetId); write(in.readInt()); write(in.readInt()); write(in.readShort()); copyNBytes(write(in.readInt())); break; case 0x35: // Block Change write(packetId); x = in.readInt(); y = in.readByte(); z = in.readInt(); short blockType = in.readShort(); byte metadata = in.readByte(); coordinate = new Coordinate(x, y, z, player); if (blockType == 54 && player.placedChest(coordinate)) { lockChest(coordinate); player.placingChest(null); } write(x); write(y); write(z); write(blockType); write(metadata); break; case 0x36: // Block Action write(packetId); copyNBytes(14); break; case 0x37: // Mining progress write(packetId); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); break; case 0x38: // Chunk Bulk write(packetId); copyNBytes(write(in.readShort()) * 12 + write(in.readInt())); break; case 0x3c: // Explosion write(packetId); copyNBytes(28); int recordCount = in.readInt(); write(recordCount); copyNBytes(recordCount * 3); write(in.readFloat()); write(in.readFloat()); write(in.readFloat()); break; case 0x3d: // Sound/Particle Effect write(packetId); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readByte()); break; case 0x3e: // Named Sound/Particle Effect write(packetId); write(readUTF16()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readFloat()); write(in.readByte()); break; case 0x46: // New/Invalid State write(packetId); write(in.readByte()); write(in.readByte()); break; case 0x47: // Thunderbolt write(packetId); copyNBytes(17); break; case 0x64: // Open Window boolean allow = true; byte id = in.readByte(); byte invtype = in.readByte(); String typeString = readUTF16(); byte unknownByte = in.readByte(); if (invtype == 0) { Chest adjacent = server.data.chests.adjacentChest(player.openedChest()); if (!server.data.chests.isChest(player.openedChest())) { if (adjacent == null) { server.data.chests.addOpenChest(player.openedChest()); } else { server.data.chests.giveLock(adjacent.owner, player.openedChest(), adjacent.name); } server.data.save(); } if (!player.getGroup().ignoreAreas && (!server.config.blockPermission(player, player.openedChest()).chest || (adjacent != null && !server.config.blockPermission(player, adjacent.coordinate).chest))) { player.addTMessage(Color.RED, "You can't use chests here"); allow = false; } else if (server.data.chests.canOpen(player, player.openedChest()) || player.ignoresChestLocks()) { if (server.data.chests.isLocked(player.openedChest())) { if (player.isAttemptingUnlock()) { server.data.chests.unlock(player.openedChest()); server.data.save(); player.setAttemptedAction(null); player.addTMessage(Color.RED, "This chest is no longer locked!"); typeString = t("Open Chest"); } else { typeString = server.data.chests.chestName(player.openedChest()); } } else { typeString = t("Open Chest"); if (player.isAttemptLock()) { lockChest(player.openedChest()); typeString = (player.nextChestName() == null) ? t("Locked Chest") : player.nextChestName(); } } } else { player.addTMessage(Color.RED, "This chest is locked!"); allow = false; } } if (!allow) { write((byte) 0x65); write(id); } else { write(packetId); write(id); write(invtype); write(typeString); write(unknownByte); } break; case 0x65: // Close Window write(packetId); write(in.readByte()); break; case 0x66: // Window Click write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); write(in.readShort()); write(in.readByte()); copyItem(); break; case 0x67: // Set Slot write(packetId); write(in.readByte()); write(in.readShort()); copyItem(); break; case 0x68: // Window Items write(packetId); write(in.readByte()); short count = write(in.readShort()); for (int c = 0; c < count; ++c) { copyItem(); } break; case 0x69: // Update Window Property write(packetId); write(in.readByte()); write(in.readShort()); write(in.readShort()); break; case 0x6a: // Transaction write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); break; case 0x6b: // Creative Inventory Action write(packetId); write(in.readShort()); copyItem(); break; case 0x6c: // Enchant Item write(packetId); write(in.readByte()); write(in.readByte()); break; case (byte) 0x82: // Update Sign write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(readUTF16()); write(readUTF16()); write(readUTF16()); write(readUTF16()); break; case (byte) 0x83: // Item Data write(packetId); write(in.readShort()); write(in.readShort()); short length = in.readShort(); write(length); copyNBytes(length); break; case (byte) 0x84: // added in 12w06a write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(in.readByte()); short nbtLength = write(in.readShort()); if (nbtLength > 0) { copyNBytes(nbtLength); } break; case (byte) 0xc3: // BukkitContrib write(packetId); write(in.readInt()); copyNBytes(write(in.readInt())); break; case (byte) 0xc8: // Increment Statistic write(packetId); copyNBytes(5); break; case (byte) 0xc9: // Player List Item write(packetId); write(readUTF16()); write(in.readByte()); write(in.readShort()); break; case (byte) 0xca: // Player Abilities write(packetId); write(in.readByte()); write(in.readByte()); write(in.readByte()); break; case (byte) 0xcb: // Tab-Completion write(packetId); write(readUTF16()); break; case (byte) 0xcc: // Locale and View Distance write(packetId); write(readUTF16()); write(in.readByte()); write(in.readByte()); write(in.readByte()); write(in.readBoolean()); break; case (byte) 0xcd: // Login & Respawn write(packetId); write(in.readByte()); break; case (byte) 0xd3: // Red Power (mod by Eloraam) write(packetId); copyNBytes(1); copyVLC(); copyVLC(); copyVLC(); copyNBytes((int) copyVLC()); break; case (byte) 0xe6: // ModLoaderMP by SDK write(packetId); write(in.readInt()); // mod write(in.readInt()); // packet id copyNBytes(write(in.readInt()) * 4); // ints copyNBytes(write(in.readInt()) * 4); // floats copyNBytes(write(in.readInt()) * 8); // doubles int sizeString = write(in.readInt()); // strings for (int i = 0; i < sizeString; i++) { copyNBytes(write(in.readInt())); } break; case (byte) 0xfa: // Plugin Message write(packetId); write(readUTF16()); copyNBytes(write(in.readShort())); break; case (byte) 0xfc: // Encryption Key Response byte[] sharedKey = new byte[in.readShort()]; in.readFully(sharedKey); byte[] challengeTokenResponse = new byte[in.readShort()]; in.readFully(challengeTokenResponse); if (!isServerTunnel) { if (!player.clientEncryption.checkChallengeToken(challengeTokenResponse)) { player.kick("Invalid client response"); break; } player.clientEncryption.setEncryptedSharedKey(sharedKey); sharedKey = player.serverEncryption.getEncryptedSharedKey(); } if (!isServerTunnel && server.authenticator.useCustAuth(player) && !server.authenticator.onlineAuthenticate(player)) { player.kick(t("%s Failed to login: User not premium", "[CustAuth]")); break; } write(packetId); write((short) sharedKey.length); write(sharedKey); challengeTokenResponse = player.serverEncryption.encryptChallengeToken(); write((short) challengeTokenResponse.length); write(challengeTokenResponse); if (isServerTunnel) { in = new DataInputStream(new BufferedInputStream(player.serverEncryption.encryptedInputStream(inputStream))); out = new DataOutputStream(new BufferedOutputStream(player.clientEncryption.encryptedOutputStream(outputStream))); } else { in = new DataInputStream(new BufferedInputStream(player.clientEncryption.encryptedInputStream(inputStream))); out = new DataOutputStream(new BufferedOutputStream(player.serverEncryption.encryptedOutputStream(outputStream))); } break; case (byte) 0xfd: // Encryption Key Request (server -> client) tunneler.setName(streamType + "-" + player.getName()); write(packetId); String serverId = readUTF16(); if (!server.authenticator.useCustAuth(player)) { serverId = "-"; } else { serverId = player.getConnectionHash(); } write(serverId); byte[] keyBytes = new byte[in.readShort()]; in.readFully(keyBytes); byte[] challengeToken = new byte[in.readShort()]; in.readFully(challengeToken); player.serverEncryption.setPublicKey(keyBytes); byte[] key = player.clientEncryption.getPublicKey(); write((short) key.length); write(key); write((short) challengeToken.length); write(challengeToken); player.serverEncryption.setChallengeToken(challengeToken); player.clientEncryption.setChallengeToken(challengeToken); break; case (byte) 0xfe: // Server List Ping write(packetId); write(in.readByte()); break; case (byte) 0xff: // Disconnect/Kick write(packetId); String reason = readUTF16(); if (reason.startsWith("\u00a71")) { reason = String.format("\u00a71\0%s\0%s\0%s\0%s\0%s", Main.protocolVersion, Main.minecraftVersion, server.config.properties.get("serverDescription"), server.playerList.size(), server.config.properties.getInt("maxPlayers")); } write(reason); if (reason.startsWith("Took too long")) { server.addRobot(player); } player.close(); break; default: if (EXPENSIVE_DEBUG_LOGGING) { while (true) { skipNBytes(1); flushAll(); } } else { if (lastPacket != null) { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName() + " (after 0x" + Integer.toHexString(lastPacket)); } else { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName()); } } } packetFinished(); lastPacket = (packetId == 0x00) ? lastPacket : packetId; }
diff --git a/ProjectSWOP20102011/src/projectswop20102011/domain/EmergencyStatus.java b/ProjectSWOP20102011/src/projectswop20102011/domain/EmergencyStatus.java index a37c614..aa76909 100644 --- a/ProjectSWOP20102011/src/projectswop20102011/domain/EmergencyStatus.java +++ b/ProjectSWOP20102011/src/projectswop20102011/domain/EmergencyStatus.java @@ -1,256 +1,256 @@ package projectswop20102011.domain; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import projectswop20102011.exceptions.InvalidEmergencyException; import projectswop20102011.exceptions.InvalidEmergencyStatusException; /** * An enumeration that represents the status of an emergency. * @author Willem Van Onsem, Jonas Vanthornhout & Pieter-Jan Vuylsteke */ public enum EmergencyStatus { /** * A state where the emergency is recorded by the operator but not yet handled by the dispatcher. */ RECORDED_BUT_UNHANDLED("recorded but unhandled") { @Override void assignUnits(UnitsNeeded unitsNeeded, Set<Unit> units) throws InvalidEmergencyException { unitsNeeded.assignUnitsToEmergency(units); try { unitsNeeded.getEmergency().setStatus(EmergencyStatus.RESPONSE_IN_PROGRESS); } catch (InvalidEmergencyStatusException ex) { //We assume this can't happen. Logger.getLogger(EmergencyStatus.class.getName()).log(Level.SEVERE, null, ex); } } @Override void finishUnit(UnitsNeeded unitsNeeded, Unit unit) throws InvalidEmergencyStatusException { throw new InvalidEmergencyStatusException("Can't finish units from an unhandled emergency."); } @Override void withdrawUnit(UnitsNeeded unitsNeeded, Unit unit) throws InvalidEmergencyStatusException { throw new InvalidEmergencyStatusException("Can't withdraw units from an unhandled emergency."); } @Override boolean canAssignUnits(UnitsNeeded unitsNeeded, Set<Unit> unit) { return unitsNeeded.canAssignUnitsToEmergency(unit); } @Override Set<Unit> getPolicyProposal(UnitsNeeded unitsNeeded, List<? extends Unit> availableUnits) { return unitsNeeded.getPolicyProposal(availableUnits); } @Override boolean canBeResolved(UnitsNeeded unitsNeeded, Collection<Unit> availableUnits) { return unitsNeeded.canBeResolved(availableUnits); } }, /** * A state of an emergency where the dispatcher has already sent units (this does not mean there are still units working or already finished). */ RESPONSE_IN_PROGRESS("response in progress") { @Override void assignUnits(UnitsNeeded unitsNeeded, Set<Unit> units) throws InvalidEmergencyException { unitsNeeded.assignUnitsToEmergency(units); } @Override void finishUnit(UnitsNeeded unitsNeeded, Unit unit) { unitsNeeded.unitFinishedJob(unit); - if (unitsNeeded.canFinish()) { + if (unitsNeeded.canCompleteEmergency()) { try { unitsNeeded.getEmergency().setStatus(COMPLETED); } catch (InvalidEmergencyStatusException ex) { //We assume this can't happen Logger.getLogger(EmergencyStatus.class.getName()).log(Level.SEVERE, null, ex); } } } @Override void withdrawUnit(UnitsNeeded unitsNeeded, Unit unit) { unitsNeeded.withdrawUnit(unit); } @Override boolean canAssignUnits(UnitsNeeded unitsNeeded, Set<Unit> units) { return unitsNeeded.canAssignUnitsToEmergency(units); } @Override Set<Unit> getPolicyProposal(UnitsNeeded unitsNeeded, List<? extends Unit> availableUnits) { return unitsNeeded.getPolicyProposal(availableUnits); } @Override boolean canBeResolved(UnitsNeeded unitsNeeded, Collection<Unit> availableUnits) { return unitsNeeded.canBeResolved(availableUnits); } }, /** * A state of an emergency where the emergency has been completly handled. All the units needed for this emergency have finished. */ COMPLETED("completed") { @Override void assignUnits(UnitsNeeded unitsNeeded, Set<Unit> units) throws InvalidEmergencyStatusException { throw new InvalidEmergencyStatusException("Unable to assign units to a completed emergency."); } @Override void finishUnit(UnitsNeeded unitsNeeded, Unit unit) throws InvalidEmergencyStatusException { throw new InvalidEmergencyStatusException("Unable to finish units from a completed emergency."); } @Override void withdrawUnit(UnitsNeeded unitsNeeded, Unit unit) throws InvalidEmergencyStatusException { throw new InvalidEmergencyStatusException("Unable to withdraw units from a competed emergency."); } @Override boolean canAssignUnits(UnitsNeeded unitsNeeded, Set<Unit> units) { return false; } @Override Set<Unit> getPolicyProposal(UnitsNeeded unitsNeeded, List<? extends Unit> availableUnits) { return new HashSet<Unit>();//a proposal containing no units } @Override boolean canBeResolved(UnitsNeeded unitsNeeded, Collection<Unit> availableUnits) { return true; } }; /** * The textual representation of an EmergencyStatus. */ private final String textual; /** * Creates a new instance of the EmergencyStatus class with a given textual representation. * @param textual * The textual representation of the EmergencyStatus, used for parsing and user interaction. * @post The textual representation is set to the given textual representation. * | new.toString().equals(textual) */ private EmergencyStatus(String textual) { this.textual = textual; } /** * Returns the textual representation of the EmergencyStatus. * @return A textual representation of the EmergencyStatus. */ @Override public String toString() { return textual; } /** * Tests if a given textual representation of an EmergencyStatus matches this EmergencyStatus. * @param textualRepresentation * The textual representation to test. * @return True if the textual representation matches, otherwise false. */ public boolean matches(String textualRepresentation) { return this.toString().equals(textualRepresentation.toLowerCase()); } /** * Parses a textual representation into its EmergencyStatus equivalent. * @param textualRepresentation * The textual representation to parse. * @return An EmergencyStatus that is the equivalent of the textual representation. * @throws InvalidEmergencyStatusException * If no EmergencyStatus matches the textual representation. */ public static EmergencyStatus parse(String textualRepresentation) throws InvalidEmergencyStatusException { for (EmergencyStatus es : EmergencyStatus.values()) { if (es.matches(textualRepresentation)) { return es; } } throw new InvalidEmergencyStatusException(String.format("Unknown emergency status level \"%s\".", textualRepresentation)); } /** * A method representing a potential transition where units are allocated to the emergency. * @param unitsNeeded * The unitsNeeded object of the emergency where the action takes place. * @param units * The units to allocate to the emergency. * @throws InvalidEmergencyStatusException * If the status of the emergency is invalid. * @throws Exception * If another exception is thrown. * @note This method has a package visibility: Only the emergency class can call this method. */ abstract void assignUnits(UnitsNeeded unitsNeeded, Set<Unit> units) throws InvalidEmergencyStatusException, Exception; /** * A method representing a transition where a unit signals it has finished it's job. * @param unitsNeeded * The unitsNeeded object of the emergency where the action takes place. * @param unit * The unit that signals it has finished its job. * @throws InvalidEmergencyStatusException * If the status of the emergency is invalid. * @note This method has a package visibility: Only the emergency class can call this method. */ abstract void finishUnit(UnitsNeeded unitsNeeded, Unit unit) throws InvalidEmergencyStatusException; /** * A method that handles a situation where a given unit withdraws from a given emergency. * @param unitsNeeded * The unitsNeeded object of the emergency where the action takes place. * @param unit * The unit that withdraws from an emergency. * @throws InvalidEmergencyStatusException * If the status of the emergency is invalid. * @note This method has a package visibility: Only the emergency class can call this method. */ abstract void withdrawUnit(UnitsNeeded unitsNeeded, Unit unit) throws InvalidEmergencyStatusException; /** * A method that checks if the given units can be assigned to the given emergency. * @param unitsNeeded * The unitsNeeded object of the emergency where the action takes place. * @param units * A list of units to check for. * @return True if the given list of units can be assigned, otherwise false (this also includes states where no allocation can be done). */ abstract boolean canAssignUnits(UnitsNeeded unitsNeeded, Set<Unit> units); /** * Gets a proposal generated by the policy of this emergency. * @param unitsNeeded * The unitsNeeded object of the emergency where the action takes place. * @param availableUnits * A list of available units that can be selected. * @return A set of units that represents the proposal of the policy. */ abstract Set<Unit> getPolicyProposal(UnitsNeeded unitsNeeded, List<? extends Unit> availableUnits); /** * Checks if the given emergency can be resolved with a given collection of all the available units. * @param unitsNeeded * The unitsNeeded object of the emergency where the action takes place. * @param availableUnits * A collection of all the available units. * @return True if the given emergency can be resolved, otherwise false. */ abstract boolean canBeResolved(UnitsNeeded unitsNeeded, Collection<Unit> availableUnits); }
true
true
void finishUnit(UnitsNeeded unitsNeeded, Unit unit) { unitsNeeded.unitFinishedJob(unit); if (unitsNeeded.canFinish()) { try { unitsNeeded.getEmergency().setStatus(COMPLETED); } catch (InvalidEmergencyStatusException ex) { //We assume this can't happen Logger.getLogger(EmergencyStatus.class.getName()).log(Level.SEVERE, null, ex); } } }
void finishUnit(UnitsNeeded unitsNeeded, Unit unit) { unitsNeeded.unitFinishedJob(unit); if (unitsNeeded.canCompleteEmergency()) { try { unitsNeeded.getEmergency().setStatus(COMPLETED); } catch (InvalidEmergencyStatusException ex) { //We assume this can't happen Logger.getLogger(EmergencyStatus.class.getName()).log(Level.SEVERE, null, ex); } } }
diff --git a/src/info/micdm/ftr/activities/GroupActivity.java b/src/info/micdm/ftr/activities/GroupActivity.java index a622996..ebea003 100644 --- a/src/info/micdm/ftr/activities/GroupActivity.java +++ b/src/info/micdm/ftr/activities/GroupActivity.java @@ -1,201 +1,201 @@ package info.micdm.ftr.activities; import info.micdm.ftr.Forum; import info.micdm.ftr.Group; import info.micdm.ftr.R; import info.micdm.ftr.Theme; import info.micdm.ftr.utils.Log; import java.util.ArrayList; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; /** * Адаптер для списка тем. * @author Mic, 2011 * */ class ThemeListAdapter extends BaseAdapter { /** * Класс для кэширования, как предлагают в официальных примерах. * @author Mic, 2011 * */ static class ViewHolder { TextView author; TextView updated; TextView title; } /** * Этот товарищ будет создавать новый элемент из XML. */ protected LayoutInflater _inflater; /** * Список тем. */ protected ArrayList<Theme> _themes; public ThemeListAdapter(Context context, ArrayList<Theme> themes) { _inflater = LayoutInflater.from(context); _themes = themes; } /** * Возвращает количество элементов. */ public int getCount() { return _themes.size(); } /** * Возвращает элемент в указанной позиции. */ public Object getItem(int position) { return _themes.get(position); } /** * Возвращает идентификатор элемента в указанной позиции. */ public long getItemId(int position) { return position; } /** * Возвращает заполненный элемент списка. */ public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = _inflater.inflate(R.layout.theme_list_item, null); holder = new ViewHolder(); holder.author = (TextView)convertView.findViewById(R.id.themeAuthor); holder.updated = (TextView)convertView.findViewById(R.id.themeUpdated); holder.title = (TextView)convertView.findViewById(R.id.themeTitle); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } Theme theme = (Theme)getItem(position); holder.author.setText(theme.getAuthor()); - holder.updated.setText(theme.getUpdatedAsString()); + holder.updated.setText(", " + theme.getUpdatedAsString()); holder.title.setText(theme.getTitle()); return convertView; } } /** * Экран с темами внутри конкретной группы. * @author Mic, 2011 * */ public class GroupActivity extends ListActivity { /** * Диалог про загрузку списка тем. */ protected ProgressDialog _loadingThemesDialog = null; /** * Вызывается, когда будет доступен список тем. */ protected void _onThemesAvailable(ArrayList<Theme> themes) { // TODO: не пересоздавать адаптер Log.debug(themes.size() + " themes available"); ThemeListAdapter adapter = new ThemeListAdapter(this, themes); getListView().setAdapter(adapter); } /** * Отображает темы внутри группы. */ protected void _showThemes(Group group) { _loadingThemesDialog = ProgressDialog.show(this, "", "Загружается список тем"); group.getThemes(new Group.Command() { @Override public void callback(ArrayList<Theme> themes) { _onThemesAvailable(themes); if (_loadingThemesDialog != null) { _loadingThemesDialog.dismiss(); } } }); } /** * Слушает клик по кнопке "Обновить". */ protected void _listenForReload(final Group group) { ImageButton reload = (ImageButton)findViewById(R.id.reloadGroup); reload.setOnClickListener(new ImageButton.OnClickListener() { @Override public void onClick(View view) { _showThemes(group); } }); } /** * Вызывается при выборе темы. */ protected void _onThemeSelected(Theme theme) { Log.debug("theme \"" + theme.getTitle() + "\" (" + theme.getId() + ") selected"); Intent intent = new Intent(this, ThemeActivity.class); intent.putExtra("groupId", theme.getGroupId()); intent.putExtra("themeId", theme.getId()); startActivity(intent); } /** * Слушает клик по элементу списка, чтобы перейти в соответствующую тему. */ protected void _listenForThemeSelected() { getListView().setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { Theme theme = (Theme)adapter.getItemAtPosition(position); _onThemeSelected(theme); } }); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.group); Integer groupId = getIntent().getExtras().getInt("groupId"); Group group = Forum.INSTANCE.getGroup(groupId); TextView title = (TextView)findViewById(R.id.groupTitle); title.setText(group.getTitle()); _listenForReload(group); _listenForThemeSelected(); _showThemes(group); } @Override public void onDestroy() { if (_loadingThemesDialog.isShowing()) { _loadingThemesDialog.dismiss(); _loadingThemesDialog = null; } super.onDestroy(); } }
true
true
public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = _inflater.inflate(R.layout.theme_list_item, null); holder = new ViewHolder(); holder.author = (TextView)convertView.findViewById(R.id.themeAuthor); holder.updated = (TextView)convertView.findViewById(R.id.themeUpdated); holder.title = (TextView)convertView.findViewById(R.id.themeTitle); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } Theme theme = (Theme)getItem(position); holder.author.setText(theme.getAuthor()); holder.updated.setText(theme.getUpdatedAsString()); holder.title.setText(theme.getTitle()); return convertView; }
public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = _inflater.inflate(R.layout.theme_list_item, null); holder = new ViewHolder(); holder.author = (TextView)convertView.findViewById(R.id.themeAuthor); holder.updated = (TextView)convertView.findViewById(R.id.themeUpdated); holder.title = (TextView)convertView.findViewById(R.id.themeTitle); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } Theme theme = (Theme)getItem(position); holder.author.setText(theme.getAuthor()); holder.updated.setText(", " + theme.getUpdatedAsString()); holder.title.setText(theme.getTitle()); return convertView; }
diff --git a/src/test/org/joda/time/TestDateTimeFieldType.java b/src/test/org/joda/time/TestDateTimeFieldType.java index 4246410..0e0babe 100644 --- a/src/test/org/joda/time/TestDateTimeFieldType.java +++ b/src/test/org/joda/time/TestDateTimeFieldType.java @@ -1,326 +1,327 @@ /* * Copyright 2001-2005 Stephen Colebourne * * 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.joda.time; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Constructor; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.chrono.CopticChronology; /** * This class is a Junit unit test for Chronology. * * @author Stephen Colebourne */ public class TestDateTimeFieldType extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestDateTimeFieldType.class); } public TestDateTimeFieldType(String name) { super(name); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } //----------------------------------------------------------------------- public void test_era() throws Exception { assertEquals(DateTimeFieldType.era(), DateTimeFieldType.era()); assertEquals("era", DateTimeFieldType.era().getName()); assertEquals(DurationFieldType.eras(), DateTimeFieldType.era().getDurationType()); assertEquals(null, DateTimeFieldType.era().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().era(), DateTimeFieldType.era().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().era().isSupported(), DateTimeFieldType.era().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.era()); } public void test_centuryOfEra() throws Exception { assertEquals(DateTimeFieldType.centuryOfEra(), DateTimeFieldType.centuryOfEra()); assertEquals("centuryOfEra", DateTimeFieldType.centuryOfEra().getName()); assertEquals(DurationFieldType.centuries(), DateTimeFieldType.centuryOfEra().getDurationType()); assertEquals(DurationFieldType.eras(), DateTimeFieldType.centuryOfEra().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().centuryOfEra(), DateTimeFieldType.centuryOfEra().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().centuryOfEra().isSupported(), DateTimeFieldType.centuryOfEra().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.centuryOfEra()); } public void test_yearOfCentury() throws Exception { assertEquals(DateTimeFieldType.yearOfCentury(), DateTimeFieldType.yearOfCentury()); assertEquals("yearOfCentury", DateTimeFieldType.yearOfCentury().getName()); assertEquals(DurationFieldType.years(), DateTimeFieldType.yearOfCentury().getDurationType()); assertEquals(DurationFieldType.centuries(), DateTimeFieldType.yearOfCentury().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().yearOfCentury(), DateTimeFieldType.yearOfCentury().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().yearOfCentury().isSupported(), DateTimeFieldType.yearOfCentury().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.yearOfCentury()); } public void test_yearOfEra() throws Exception { assertEquals(DateTimeFieldType.yearOfEra(), DateTimeFieldType.yearOfEra()); assertEquals("yearOfEra", DateTimeFieldType.yearOfEra().getName()); assertEquals(DurationFieldType.years(), DateTimeFieldType.yearOfEra().getDurationType()); assertEquals(DurationFieldType.eras(), DateTimeFieldType.yearOfEra().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().yearOfEra(), DateTimeFieldType.yearOfEra().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().yearOfEra().isSupported(), DateTimeFieldType.yearOfEra().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.yearOfEra()); } public void test_year() throws Exception { assertEquals(DateTimeFieldType.year(), DateTimeFieldType.year()); assertEquals("year", DateTimeFieldType.year().getName()); assertEquals(DurationFieldType.years(), DateTimeFieldType.year().getDurationType()); assertEquals(null, DateTimeFieldType.year().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().year(), DateTimeFieldType.year().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().year().isSupported(), DateTimeFieldType.year().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.year()); } public void test_monthOfYear() throws Exception { assertEquals(DateTimeFieldType.monthOfYear(), DateTimeFieldType.monthOfYear()); assertEquals("monthOfYear", DateTimeFieldType.monthOfYear().getName()); assertEquals(DurationFieldType.months(), DateTimeFieldType.monthOfYear().getDurationType()); assertEquals(DurationFieldType.years(), DateTimeFieldType.monthOfYear().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().monthOfYear(), DateTimeFieldType.monthOfYear().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().monthOfYear().isSupported(), DateTimeFieldType.monthOfYear().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.monthOfYear()); } public void test_weekyearOfCentury() throws Exception { assertEquals(DateTimeFieldType.weekyearOfCentury(), DateTimeFieldType.weekyearOfCentury()); assertEquals("weekyearOfCentury", DateTimeFieldType.weekyearOfCentury().getName()); assertEquals(DurationFieldType.weekyears(), DateTimeFieldType.weekyearOfCentury().getDurationType()); assertEquals(DurationFieldType.centuries(), DateTimeFieldType.weekyearOfCentury().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().weekyearOfCentury(), DateTimeFieldType.weekyearOfCentury().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().weekyearOfCentury().isSupported(), DateTimeFieldType.weekyearOfCentury().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.weekyearOfCentury()); } public void test_weekyear() throws Exception { assertEquals(DateTimeFieldType.weekyear(), DateTimeFieldType.weekyear()); assertEquals("weekyear", DateTimeFieldType.weekyear().getName()); assertEquals(DurationFieldType.weekyears(), DateTimeFieldType.weekyear().getDurationType()); assertEquals(null, DateTimeFieldType.weekyear().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().weekyear(), DateTimeFieldType.weekyear().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().weekyear().isSupported(), DateTimeFieldType.weekyear().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.weekyear()); } public void test_weekOfWeekyear() throws Exception { assertEquals(DateTimeFieldType.weekOfWeekyear(), DateTimeFieldType.weekOfWeekyear()); assertEquals("weekOfWeekyear", DateTimeFieldType.weekOfWeekyear().getName()); assertEquals(DurationFieldType.weeks(), DateTimeFieldType.weekOfWeekyear().getDurationType()); assertEquals(DurationFieldType.weekyears(), DateTimeFieldType.weekOfWeekyear().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().weekOfWeekyear(), DateTimeFieldType.weekOfWeekyear().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().weekOfWeekyear().isSupported(), DateTimeFieldType.weekOfWeekyear().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.weekOfWeekyear()); } public void test_dayOfYear() throws Exception { assertEquals(DateTimeFieldType.dayOfYear(), DateTimeFieldType.dayOfYear()); assertEquals("dayOfYear", DateTimeFieldType.dayOfYear().getName()); assertEquals(DurationFieldType.days(), DateTimeFieldType.dayOfYear().getDurationType()); assertEquals(DurationFieldType.years(), DateTimeFieldType.dayOfYear().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().dayOfYear(), DateTimeFieldType.dayOfYear().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().dayOfYear().isSupported(), DateTimeFieldType.dayOfYear().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.dayOfYear()); } public void test_dayOfMonth() throws Exception { assertEquals(DateTimeFieldType.dayOfMonth(), DateTimeFieldType.dayOfMonth()); assertEquals("dayOfMonth", DateTimeFieldType.dayOfMonth().getName()); assertEquals(DurationFieldType.days(), DateTimeFieldType.dayOfMonth().getDurationType()); assertEquals(DurationFieldType.months(), DateTimeFieldType.dayOfMonth().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().dayOfMonth(), DateTimeFieldType.dayOfMonth().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().dayOfMonth().isSupported(), DateTimeFieldType.dayOfMonth().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.dayOfMonth()); } public void test_dayOfWeek() throws Exception { assertEquals(DateTimeFieldType.dayOfWeek(), DateTimeFieldType.dayOfWeek()); assertEquals("dayOfWeek", DateTimeFieldType.dayOfWeek().getName()); assertEquals(DurationFieldType.days(), DateTimeFieldType.dayOfWeek().getDurationType()); assertEquals(DurationFieldType.weeks(), DateTimeFieldType.dayOfWeek().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().dayOfWeek(), DateTimeFieldType.dayOfWeek().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().dayOfWeek().isSupported(), DateTimeFieldType.dayOfWeek().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.dayOfWeek()); } public void test_halfdayOfDay() throws Exception { assertEquals(DateTimeFieldType.halfdayOfDay(), DateTimeFieldType.halfdayOfDay()); assertEquals("halfdayOfDay", DateTimeFieldType.halfdayOfDay().getName()); assertEquals(DurationFieldType.halfdays(), DateTimeFieldType.halfdayOfDay().getDurationType()); assertEquals(DurationFieldType.days(), DateTimeFieldType.halfdayOfDay().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().halfdayOfDay(), DateTimeFieldType.halfdayOfDay().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().halfdayOfDay().isSupported(), DateTimeFieldType.halfdayOfDay().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.halfdayOfDay()); } public void test_clockhourOfDay() throws Exception { assertEquals(DateTimeFieldType.clockhourOfDay(), DateTimeFieldType.clockhourOfDay()); assertEquals("clockhourOfDay", DateTimeFieldType.clockhourOfDay().getName()); assertEquals(DurationFieldType.hours(), DateTimeFieldType.clockhourOfDay().getDurationType()); assertEquals(DurationFieldType.days(), DateTimeFieldType.clockhourOfDay().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().clockhourOfDay(), DateTimeFieldType.clockhourOfDay().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().clockhourOfDay().isSupported(), DateTimeFieldType.clockhourOfDay().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.clockhourOfDay()); } public void test_clockhourOfHalfday() throws Exception { assertEquals(DateTimeFieldType.clockhourOfHalfday(), DateTimeFieldType.clockhourOfHalfday()); assertEquals("clockhourOfHalfday", DateTimeFieldType.clockhourOfHalfday().getName()); assertEquals(DurationFieldType.hours(), DateTimeFieldType.clockhourOfHalfday().getDurationType()); assertEquals(DurationFieldType.halfdays(), DateTimeFieldType.clockhourOfHalfday().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().clockhourOfHalfday(), DateTimeFieldType.clockhourOfHalfday().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().clockhourOfHalfday().isSupported(), DateTimeFieldType.clockhourOfHalfday().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.clockhourOfHalfday()); } public void test_hourOfHalfday() throws Exception { assertEquals(DateTimeFieldType.hourOfHalfday(), DateTimeFieldType.hourOfHalfday()); assertEquals("hourOfHalfday", DateTimeFieldType.hourOfHalfday().getName()); assertEquals(DurationFieldType.hours(), DateTimeFieldType.hourOfHalfday().getDurationType()); assertEquals(DurationFieldType.halfdays(), DateTimeFieldType.hourOfHalfday().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().hourOfHalfday(), DateTimeFieldType.hourOfHalfday().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().hourOfHalfday().isSupported(), DateTimeFieldType.hourOfHalfday().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.hourOfHalfday()); } public void test_hourOfDay() throws Exception { assertEquals(DateTimeFieldType.hourOfDay(), DateTimeFieldType.hourOfDay()); assertEquals("hourOfDay", DateTimeFieldType.hourOfDay().getName()); assertEquals(DurationFieldType.hours(), DateTimeFieldType.hourOfDay().getDurationType()); assertEquals(DurationFieldType.days(), DateTimeFieldType.hourOfDay().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().hourOfDay(), DateTimeFieldType.hourOfDay().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().hourOfDay().isSupported(), DateTimeFieldType.hourOfDay().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.hourOfDay()); } public void test_minuteOfDay() throws Exception { assertEquals(DateTimeFieldType.minuteOfDay(), DateTimeFieldType.minuteOfDay()); assertEquals("minuteOfDay", DateTimeFieldType.minuteOfDay().getName()); assertEquals(DurationFieldType.minutes(), DateTimeFieldType.minuteOfDay().getDurationType()); assertEquals(DurationFieldType.days(), DateTimeFieldType.minuteOfDay().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().minuteOfDay(), DateTimeFieldType.minuteOfDay().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().minuteOfDay().isSupported(), DateTimeFieldType.minuteOfDay().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.minuteOfDay()); } public void test_minuteOfHour() throws Exception { assertEquals(DateTimeFieldType.minuteOfHour(), DateTimeFieldType.minuteOfHour()); assertEquals("minuteOfHour", DateTimeFieldType.minuteOfHour().getName()); assertEquals(DurationFieldType.minutes(), DateTimeFieldType.minuteOfHour().getDurationType()); assertEquals(DurationFieldType.hours(), DateTimeFieldType.minuteOfHour().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().minuteOfHour(), DateTimeFieldType.minuteOfHour().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().minuteOfHour().isSupported(), DateTimeFieldType.minuteOfHour().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.minuteOfHour()); } public void test_secondOfDay() throws Exception { assertEquals(DateTimeFieldType.secondOfDay(), DateTimeFieldType.secondOfDay()); assertEquals("secondOfDay", DateTimeFieldType.secondOfDay().getName()); assertEquals(DurationFieldType.seconds(), DateTimeFieldType.secondOfDay().getDurationType()); assertEquals(DurationFieldType.days(), DateTimeFieldType.secondOfDay().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().secondOfDay(), DateTimeFieldType.secondOfDay().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().secondOfDay().isSupported(), DateTimeFieldType.secondOfDay().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.secondOfDay()); } public void test_secondOfMinute() throws Exception { assertEquals(DateTimeFieldType.secondOfMinute(), DateTimeFieldType.secondOfMinute()); assertEquals("secondOfMinute", DateTimeFieldType.secondOfMinute().getName()); assertEquals(DurationFieldType.seconds(), DateTimeFieldType.secondOfMinute().getDurationType()); assertEquals(DurationFieldType.minutes(), DateTimeFieldType.secondOfMinute().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().secondOfMinute(), DateTimeFieldType.secondOfMinute().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().secondOfMinute().isSupported(), DateTimeFieldType.secondOfMinute().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.secondOfMinute()); } public void test_millisOfDay() throws Exception { assertEquals(DateTimeFieldType.millisOfDay(), DateTimeFieldType.millisOfDay()); assertEquals("millisOfDay", DateTimeFieldType.millisOfDay().getName()); assertEquals(DurationFieldType.millis(), DateTimeFieldType.millisOfDay().getDurationType()); assertEquals(DurationFieldType.days(), DateTimeFieldType.millisOfDay().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().millisOfDay(), DateTimeFieldType.millisOfDay().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().millisOfDay().isSupported(), DateTimeFieldType.millisOfDay().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.millisOfDay()); } public void test_millisOfSecond() throws Exception { assertEquals(DateTimeFieldType.millisOfSecond(), DateTimeFieldType.millisOfSecond()); assertEquals("millisOfSecond", DateTimeFieldType.millisOfSecond().getName()); assertEquals(DurationFieldType.millis(), DateTimeFieldType.millisOfSecond().getDurationType()); assertEquals(DurationFieldType.seconds(), DateTimeFieldType.millisOfSecond().getRangeDurationType()); assertEquals(CopticChronology.getInstanceUTC().millisOfSecond(), DateTimeFieldType.millisOfSecond().getField(CopticChronology.getInstanceUTC())); assertEquals(CopticChronology.getInstanceUTC().millisOfSecond().isSupported(), DateTimeFieldType.millisOfSecond().isSupported(CopticChronology.getInstanceUTC())); assertSerialization(DateTimeFieldType.millisOfSecond()); } public void test_other() throws Exception { assertEquals(1, DateTimeFieldType.class.getDeclaredClasses().length); Class cls = DateTimeFieldType.class.getDeclaredClasses()[0]; assertEquals(1, cls.getDeclaredConstructors().length); Constructor con = cls.getDeclaredConstructors()[0]; Object[] params = new Object[] { "other", new Byte((byte) 128), DurationFieldType.hours(), DurationFieldType.months()}; + con.setAccessible(true); // for Apache Harmony JVM DateTimeFieldType type = (DateTimeFieldType) con.newInstance(params); assertEquals("other", type.getName()); assertSame(DurationFieldType.hours(), type.getDurationType()); assertSame(DurationFieldType.months(), type.getRangeDurationType()); try { type.getField(CopticChronology.getInstanceUTC()); fail(); } catch (InternalError ex) {} DateTimeFieldType result = doSerialization(type); assertEquals(type.getName(), result.getName()); assertNotSame(type, result); } //----------------------------------------------------------------------- private void assertSerialization(DateTimeFieldType type) throws Exception { DateTimeFieldType result = doSerialization(type); assertSame(type, result); } private DateTimeFieldType doSerialization(DateTimeFieldType type) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(type); byte[] bytes = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); DateTimeFieldType result = (DateTimeFieldType) ois.readObject(); ois.close(); return result; } }
true
true
public void test_other() throws Exception { assertEquals(1, DateTimeFieldType.class.getDeclaredClasses().length); Class cls = DateTimeFieldType.class.getDeclaredClasses()[0]; assertEquals(1, cls.getDeclaredConstructors().length); Constructor con = cls.getDeclaredConstructors()[0]; Object[] params = new Object[] { "other", new Byte((byte) 128), DurationFieldType.hours(), DurationFieldType.months()}; DateTimeFieldType type = (DateTimeFieldType) con.newInstance(params); assertEquals("other", type.getName()); assertSame(DurationFieldType.hours(), type.getDurationType()); assertSame(DurationFieldType.months(), type.getRangeDurationType()); try { type.getField(CopticChronology.getInstanceUTC()); fail(); } catch (InternalError ex) {} DateTimeFieldType result = doSerialization(type); assertEquals(type.getName(), result.getName()); assertNotSame(type, result); }
public void test_other() throws Exception { assertEquals(1, DateTimeFieldType.class.getDeclaredClasses().length); Class cls = DateTimeFieldType.class.getDeclaredClasses()[0]; assertEquals(1, cls.getDeclaredConstructors().length); Constructor con = cls.getDeclaredConstructors()[0]; Object[] params = new Object[] { "other", new Byte((byte) 128), DurationFieldType.hours(), DurationFieldType.months()}; con.setAccessible(true); // for Apache Harmony JVM DateTimeFieldType type = (DateTimeFieldType) con.newInstance(params); assertEquals("other", type.getName()); assertSame(DurationFieldType.hours(), type.getDurationType()); assertSame(DurationFieldType.months(), type.getRangeDurationType()); try { type.getField(CopticChronology.getInstanceUTC()); fail(); } catch (InternalError ex) {} DateTimeFieldType result = doSerialization(type); assertEquals(type.getName(), result.getName()); assertNotSame(type, result); }
diff --git a/src/main/java/grisu/gricli/command/InteractiveLoginCommand.java b/src/main/java/grisu/gricli/command/InteractiveLoginCommand.java index a696c39..21f65f2 100644 --- a/src/main/java/grisu/gricli/command/InteractiveLoginCommand.java +++ b/src/main/java/grisu/gricli/command/InteractiveLoginCommand.java @@ -1,65 +1,65 @@ package grisu.gricli.command; import grisu.control.ServiceInterface; import grisu.frontend.control.login.LoginException; import grisu.frontend.control.login.LoginManager; import grisu.gricli.Gricli; import grisu.gricli.GricliEnvironment; import grisu.gricli.GricliRuntimeException; import grisu.gricli.completors.BackendCompletor; import grisu.gricli.completors.CompletionCache; import grisu.gricli.completors.CompletionCacheImpl; import grisu.model.GrisuRegistryManager; import java.io.File; import org.apache.commons.lang.StringUtils; public class InteractiveLoginCommand implements GricliCommand { private final String backend; @SyntaxDescription(command={"ilogin"},arguments={"backend"}) @AutoComplete(completors={BackendCompletor.class}) public InteractiveLoginCommand(String backend) { this.backend = backend; } public GricliEnvironment execute(GricliEnvironment env) throws GricliRuntimeException { try { ServiceInterface si = LoginManager.loginCommandline(backend); env.setServiceInterface(si); CompletionCache cc = new CompletionCacheImpl(env); GrisuRegistryManager.getDefault(si).set( Gricli.COMPLETION_CACHE_REGISTRY_KEY, cc); Gricli.completionCache = cc; new ChdirCommand(System.getProperty("user.dir")).execute(env); String value = System .getenv(LocalLoginCommand.GRICLI_LOGIN_SCRIPT_ENV_NAME); if (StringUtils - .isNotBlank(LocalLoginCommand.GRICLI_LOGIN_SCRIPT_ENV_NAME)) { + .isNotBlank(value)) { File script = new File(value); if (script.canExecute()) { new ExecCommand(script.getPath()).execute(env); } } // CompletionCache.jobnames = si.getAllJobnames(null).asSortedSet(); // CompletionCache.fqans = si.getFqans().asSortedSet(); // CompletionCache.queues = si.getAllSubmissionLocations() // .asSubmissionLocationStrings(); // CompletionCache.sites = si.getAllSites().asArray(); return env; } catch (LoginException ex) { throw new GricliRuntimeException(ex); } } }
true
true
public GricliEnvironment execute(GricliEnvironment env) throws GricliRuntimeException { try { ServiceInterface si = LoginManager.loginCommandline(backend); env.setServiceInterface(si); CompletionCache cc = new CompletionCacheImpl(env); GrisuRegistryManager.getDefault(si).set( Gricli.COMPLETION_CACHE_REGISTRY_KEY, cc); Gricli.completionCache = cc; new ChdirCommand(System.getProperty("user.dir")).execute(env); String value = System .getenv(LocalLoginCommand.GRICLI_LOGIN_SCRIPT_ENV_NAME); if (StringUtils .isNotBlank(LocalLoginCommand.GRICLI_LOGIN_SCRIPT_ENV_NAME)) { File script = new File(value); if (script.canExecute()) { new ExecCommand(script.getPath()).execute(env); } } // CompletionCache.jobnames = si.getAllJobnames(null).asSortedSet(); // CompletionCache.fqans = si.getFqans().asSortedSet(); // CompletionCache.queues = si.getAllSubmissionLocations() // .asSubmissionLocationStrings(); // CompletionCache.sites = si.getAllSites().asArray(); return env; } catch (LoginException ex) { throw new GricliRuntimeException(ex); } }
public GricliEnvironment execute(GricliEnvironment env) throws GricliRuntimeException { try { ServiceInterface si = LoginManager.loginCommandline(backend); env.setServiceInterface(si); CompletionCache cc = new CompletionCacheImpl(env); GrisuRegistryManager.getDefault(si).set( Gricli.COMPLETION_CACHE_REGISTRY_KEY, cc); Gricli.completionCache = cc; new ChdirCommand(System.getProperty("user.dir")).execute(env); String value = System .getenv(LocalLoginCommand.GRICLI_LOGIN_SCRIPT_ENV_NAME); if (StringUtils .isNotBlank(value)) { File script = new File(value); if (script.canExecute()) { new ExecCommand(script.getPath()).execute(env); } } // CompletionCache.jobnames = si.getAllJobnames(null).asSortedSet(); // CompletionCache.fqans = si.getFqans().asSortedSet(); // CompletionCache.queues = si.getAllSubmissionLocations() // .asSubmissionLocationStrings(); // CompletionCache.sites = si.getAllSites().asArray(); return env; } catch (LoginException ex) { throw new GricliRuntimeException(ex); } }
diff --git a/source/src/main/java/com/redcats/tst/factory/impl/FactoryTCase.java b/source/src/main/java/com/redcats/tst/factory/impl/FactoryTCase.java index 4a420c234..4b3f04009 100644 --- a/source/src/main/java/com/redcats/tst/factory/impl/FactoryTCase.java +++ b/source/src/main/java/com/redcats/tst/factory/impl/FactoryTCase.java @@ -1,69 +1,69 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.redcats.tst.factory.impl; import com.redcats.tst.entity.*; import com.redcats.tst.factory.IFactoryTCase; import org.springframework.stereotype.Service; import java.util.List; /** * @author bcivel */ @Service public class FactoryTCase implements IFactoryTCase { private TCase newTestCase; @Override public TCase create(String test, String testCase, String origin, String refOrigin, String creator, String implementer, String lastModifier, String project, String ticket, String application, String runQA, String runUAT, String runPROD, int priority, String group, String status, String shortDescription, String description, String howTo, String active, String fromSprint, String fromRevision, String toSprint, String toRevision, String lastExecutionStatus, String bugID, String targetSprint, String targetRevision, String comment, List<TestCaseCountry> testCaseCountry, List<TestCaseCountryProperties> testCaseCountryProperties, List<TestCaseStep> testCaseStep, List<TestCaseStepBatch> testCaseStepBatch) { newTestCase = new TCase(); newTestCase.setActive(active); newTestCase.setApplication(application); newTestCase.setBugID(bugID); newTestCase.setComment(comment); newTestCase.setCreator(creator); newTestCase.setDescription(description); newTestCase.setFromRevision(fromRevision); newTestCase.setFromSprint(fromSprint); newTestCase.setGroup(group); newTestCase.setHowTo(howTo); newTestCase.setImplementer(implementer); newTestCase.setLastExecutionStatus(lastExecutionStatus); newTestCase.setLastModifier(lastModifier); - newTestCase.setOrigin(refOrigin); + newTestCase.setOrigin(origin); newTestCase.setPriority(priority); newTestCase.setProject(project); newTestCase.setRefOrigin(refOrigin); newTestCase.setRunPROD(runPROD); newTestCase.setRunQA(runQA); newTestCase.setRunUAT(runUAT); newTestCase.setShortDescription(shortDescription); newTestCase.setStatus(status); newTestCase.setTargetRevision(targetRevision); newTestCase.setTargetSprint(targetSprint); newTestCase.setTest(test); newTestCase.setTestCase(testCase); newTestCase.setTicket(ticket); newTestCase.setToRevision(toRevision); newTestCase.setToSprint(toSprint); newTestCase.setTestCaseCountry(testCaseCountry); newTestCase.setTestCaseCountryProperties(testCaseCountryProperties); newTestCase.setTestCaseStep(testCaseStep); newTestCase.setTestCaseStepBatch(testCaseStepBatch); return newTestCase; } @Override public TCase create(String test, String testCase) { newTestCase = new TCase(); newTestCase.setTest(test); newTestCase.setTestCase(testCase); return newTestCase; } }
true
true
public TCase create(String test, String testCase, String origin, String refOrigin, String creator, String implementer, String lastModifier, String project, String ticket, String application, String runQA, String runUAT, String runPROD, int priority, String group, String status, String shortDescription, String description, String howTo, String active, String fromSprint, String fromRevision, String toSprint, String toRevision, String lastExecutionStatus, String bugID, String targetSprint, String targetRevision, String comment, List<TestCaseCountry> testCaseCountry, List<TestCaseCountryProperties> testCaseCountryProperties, List<TestCaseStep> testCaseStep, List<TestCaseStepBatch> testCaseStepBatch) { newTestCase = new TCase(); newTestCase.setActive(active); newTestCase.setApplication(application); newTestCase.setBugID(bugID); newTestCase.setComment(comment); newTestCase.setCreator(creator); newTestCase.setDescription(description); newTestCase.setFromRevision(fromRevision); newTestCase.setFromSprint(fromSprint); newTestCase.setGroup(group); newTestCase.setHowTo(howTo); newTestCase.setImplementer(implementer); newTestCase.setLastExecutionStatus(lastExecutionStatus); newTestCase.setLastModifier(lastModifier); newTestCase.setOrigin(refOrigin); newTestCase.setPriority(priority); newTestCase.setProject(project); newTestCase.setRefOrigin(refOrigin); newTestCase.setRunPROD(runPROD); newTestCase.setRunQA(runQA); newTestCase.setRunUAT(runUAT); newTestCase.setShortDescription(shortDescription); newTestCase.setStatus(status); newTestCase.setTargetRevision(targetRevision); newTestCase.setTargetSprint(targetSprint); newTestCase.setTest(test); newTestCase.setTestCase(testCase); newTestCase.setTicket(ticket); newTestCase.setToRevision(toRevision); newTestCase.setToSprint(toSprint); newTestCase.setTestCaseCountry(testCaseCountry); newTestCase.setTestCaseCountryProperties(testCaseCountryProperties); newTestCase.setTestCaseStep(testCaseStep); newTestCase.setTestCaseStepBatch(testCaseStepBatch); return newTestCase; }
public TCase create(String test, String testCase, String origin, String refOrigin, String creator, String implementer, String lastModifier, String project, String ticket, String application, String runQA, String runUAT, String runPROD, int priority, String group, String status, String shortDescription, String description, String howTo, String active, String fromSprint, String fromRevision, String toSprint, String toRevision, String lastExecutionStatus, String bugID, String targetSprint, String targetRevision, String comment, List<TestCaseCountry> testCaseCountry, List<TestCaseCountryProperties> testCaseCountryProperties, List<TestCaseStep> testCaseStep, List<TestCaseStepBatch> testCaseStepBatch) { newTestCase = new TCase(); newTestCase.setActive(active); newTestCase.setApplication(application); newTestCase.setBugID(bugID); newTestCase.setComment(comment); newTestCase.setCreator(creator); newTestCase.setDescription(description); newTestCase.setFromRevision(fromRevision); newTestCase.setFromSprint(fromSprint); newTestCase.setGroup(group); newTestCase.setHowTo(howTo); newTestCase.setImplementer(implementer); newTestCase.setLastExecutionStatus(lastExecutionStatus); newTestCase.setLastModifier(lastModifier); newTestCase.setOrigin(origin); newTestCase.setPriority(priority); newTestCase.setProject(project); newTestCase.setRefOrigin(refOrigin); newTestCase.setRunPROD(runPROD); newTestCase.setRunQA(runQA); newTestCase.setRunUAT(runUAT); newTestCase.setShortDescription(shortDescription); newTestCase.setStatus(status); newTestCase.setTargetRevision(targetRevision); newTestCase.setTargetSprint(targetSprint); newTestCase.setTest(test); newTestCase.setTestCase(testCase); newTestCase.setTicket(ticket); newTestCase.setToRevision(toRevision); newTestCase.setToSprint(toSprint); newTestCase.setTestCaseCountry(testCaseCountry); newTestCase.setTestCaseCountryProperties(testCaseCountryProperties); newTestCase.setTestCaseStep(testCaseStep); newTestCase.setTestCaseStepBatch(testCaseStepBatch); return newTestCase; }
diff --git a/src/com/btmura/android/reddit/widget/SubredditView.java b/src/com/btmura/android/reddit/widget/SubredditView.java index 2645b52f..773dee0e 100644 --- a/src/com/btmura/android/reddit/widget/SubredditView.java +++ b/src/com/btmura/android/reddit/widget/SubredditView.java @@ -1,174 +1,174 @@ /* * Copyright (C) 2012 Brian Muramatsu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmura.android.reddit.widget; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.text.BoringLayout; import android.text.Layout.Alignment; import android.text.SpannableStringBuilder; import android.text.TextPaint; import android.text.TextUtils.TruncateAt; import android.text.style.ForegroundColorSpan; import android.util.AttributeSet; import com.btmura.android.reddit.R; import com.btmura.android.reddit.database.Subreddits; /** * {@link CustomView} for displaying subreddit names. It can show subscriber * count if the information is available. */ public class SubredditView extends CustomView { private String title; private BoringLayout.Metrics titleMetrics; private BoringLayout titleLayout; private SpannableStringBuilder statusText; private BoringLayout.Metrics statusMetrics; private BoringLayout statusLayout; public SubredditView(Context context) { this(context, null); } public SubredditView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SubredditView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * @param name of the subreddit or empty string for front page * @param over18 of the subreddit's content * @param subscribers or -1 if no subscriber info available */ public void setData(String name, boolean over18, int subscribers) { title = Subreddits.getTitle(getContext(), name); setStatusText(over18, subscribers); requestLayout(); } private void setStatusText(boolean over18, int subscribers) { // If negative subscribers, then it's just a list without status. if (subscribers != -1) { Resources r = getResources(); if (statusText == null) { statusText = new SpannableStringBuilder(); } else { statusText.clear(); statusText.clearSpans(); } if (over18) { String nsfw = r.getString(R.string.nsfw); statusText.append(nsfw).append(" "); statusText.setSpan(new ForegroundColorSpan(Color.RED), 0, nsfw.length(), 0); } statusText.append(r.getQuantityString(R.plurals.subscribers, subscribers, subscribers)); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = 0; int measuredHeight = 0; int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); switch (widthMode) { case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: measuredWidth = widthSize; break; case MeasureSpec.UNSPECIFIED: measuredWidth = getSuggestedMinimumWidth(); break; } - int remains = measuredWidth - PADDING * 2; - setTitleLayout(remains); + int contentWidth = Math.max(measuredWidth - PADDING * 2, 0); + setTitleLayout(contentWidth); if (statusText != null) { - setStatusLayout(remains); + setStatusLayout(contentWidth); } int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); switch (heightMode) { case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: measuredHeight = heightSize; break; case MeasureSpec.UNSPECIFIED: measuredHeight = getMinimumViewHeight(); break; } setMeasuredDimension(measuredWidth, measuredHeight); } @Override protected void onDraw(Canvas c) { c.translate(PADDING, PADDING); titleLayout.draw(c); if (statusText != null) { c.translate(0, titleLayout.getHeight() + ELEMENT_PADDING); statusLayout.draw(c); } } private void setTitleLayout(int width) { TextPaint titlePaint = TEXT_PAINTS[SUBREDDIT_TITLE]; titleMetrics = BoringLayout.isBoring(title, titlePaint, titleMetrics); if (titleLayout == null) { titleLayout = BoringLayout.make(title, titlePaint, width, Alignment.ALIGN_NORMAL, 1f, 0f, titleMetrics, false, TruncateAt.END, width); } else { titleLayout.replaceOrMake(title, titlePaint, width, Alignment.ALIGN_NORMAL, 1f, 0f, titleMetrics, false, TruncateAt.END, width); } } private void setStatusLayout(int width) { TextPaint statusPaint = TEXT_PAINTS[SUBREDDIT_STATUS]; statusMetrics = BoringLayout.isBoring(statusText, statusPaint, statusMetrics); if (statusLayout == null) { statusLayout = BoringLayout.make(statusText, statusPaint, width, Alignment.ALIGN_NORMAL, 1f, 0f, statusMetrics, false, TruncateAt.END, width); } else { statusLayout.replaceOrMake(statusText, statusPaint, width, Alignment.ALIGN_NORMAL, 1f, 0f, statusMetrics, false, TruncateAt.END, width); } } private int getMinimumViewHeight() { int height = PADDING + titleLayout.getHeight(); if (statusText != null) { height += ELEMENT_PADDING + statusLayout.getHeight(); } return height + PADDING; } }
false
true
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = 0; int measuredHeight = 0; int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); switch (widthMode) { case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: measuredWidth = widthSize; break; case MeasureSpec.UNSPECIFIED: measuredWidth = getSuggestedMinimumWidth(); break; } int remains = measuredWidth - PADDING * 2; setTitleLayout(remains); if (statusText != null) { setStatusLayout(remains); } int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); switch (heightMode) { case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: measuredHeight = heightSize; break; case MeasureSpec.UNSPECIFIED: measuredHeight = getMinimumViewHeight(); break; } setMeasuredDimension(measuredWidth, measuredHeight); }
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = 0; int measuredHeight = 0; int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); switch (widthMode) { case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: measuredWidth = widthSize; break; case MeasureSpec.UNSPECIFIED: measuredWidth = getSuggestedMinimumWidth(); break; } int contentWidth = Math.max(measuredWidth - PADDING * 2, 0); setTitleLayout(contentWidth); if (statusText != null) { setStatusLayout(contentWidth); } int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); switch (heightMode) { case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: measuredHeight = heightSize; break; case MeasureSpec.UNSPECIFIED: measuredHeight = getMinimumViewHeight(); break; } setMeasuredDimension(measuredWidth, measuredHeight); }
diff --git a/nuxeo-drive-server/nuxeo-drive-operations/src/main/java/org/nuxeo/drive/operations/test/NuxeoDriveIntegrationTestsHelper.java b/nuxeo-drive-server/nuxeo-drive-operations/src/main/java/org/nuxeo/drive/operations/test/NuxeoDriveIntegrationTestsHelper.java index 235ebb12..e61ec810 100644 --- a/nuxeo-drive-server/nuxeo-drive-operations/src/main/java/org/nuxeo/drive/operations/test/NuxeoDriveIntegrationTestsHelper.java +++ b/nuxeo-drive-server/nuxeo-drive-operations/src/main/java/org/nuxeo/drive/operations/test/NuxeoDriveIntegrationTestsHelper.java @@ -1,80 +1,82 @@ /* * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * * Contributors: * Antoine Taillefer <[email protected]> */ package org.nuxeo.drive.operations.test; import org.nuxeo.common.utils.IdUtils; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentModelList; import org.nuxeo.ecm.core.api.DocumentRef; import org.nuxeo.ecm.core.api.PathRef; import org.nuxeo.ecm.platform.usermanager.UserManager; import org.nuxeo.runtime.api.Framework; /** * Helper for the Nuxeo Drive integration tests. * * @author Antoine Taillefer * @see NuxeoDriveSetupIntegrationTests * @see NuxeoDriveTearDownIntegrationTests */ public final class NuxeoDriveIntegrationTestsHelper { static final String TEST_USER_NAME_PREFIX = "nuxeoDriveTestUser_"; static final String TEST_WORKSPACE_PARENT_PATH = "/default-domain/workspaces"; static final String TEST_WORKSPACE_NAME = "nuxeo-drive-test-workspace"; static final String TEST_WORKSPACE_TITLE = "Nuxeo Drive Test Workspace"; public static final String TEST_WORKSPACE_PATH = TEST_WORKSPACE_PARENT_PATH + "/" + TEST_WORKSPACE_NAME; public static final String USER_WORKSPACE_PARENT_PATH = "/default-domain/UserWorkspaces"; private NuxeoDriveIntegrationTestsHelper() { // Helper class } public static void cleanUp(CoreSession session) throws Exception { // Delete test users and their personal workspace if exist UserManager userManager = Framework.getLocalService(UserManager.class); DocumentModelList testUsers = userManager.searchUsers(TEST_USER_NAME_PREFIX); for (DocumentModel testUser : testUsers) { String testUserName = (String) testUser.getPropertyValue(userManager.getUserSchemaName() + ":" + userManager.getUserIdField()); if (userManager.getPrincipal(testUserName) != null) { userManager.deleteUser(testUserName); } String testUserWorkspaceName = IdUtils.generateId(testUserName, "-", false, 30); DocumentRef testUserWorkspaceRef = new PathRef( USER_WORKSPACE_PARENT_PATH + "/" + testUserWorkspaceName); if (session.exists(testUserWorkspaceRef)) { session.removeDocument(testUserWorkspaceRef); + session.save(); } } // Delete test workspace if exists DocumentRef testWorkspaceDocRef = new PathRef(TEST_WORKSPACE_PATH); if (session.exists(testWorkspaceDocRef)) { session.removeDocument(testWorkspaceDocRef); + session.save(); } } }
false
true
public static void cleanUp(CoreSession session) throws Exception { // Delete test users and their personal workspace if exist UserManager userManager = Framework.getLocalService(UserManager.class); DocumentModelList testUsers = userManager.searchUsers(TEST_USER_NAME_PREFIX); for (DocumentModel testUser : testUsers) { String testUserName = (String) testUser.getPropertyValue(userManager.getUserSchemaName() + ":" + userManager.getUserIdField()); if (userManager.getPrincipal(testUserName) != null) { userManager.deleteUser(testUserName); } String testUserWorkspaceName = IdUtils.generateId(testUserName, "-", false, 30); DocumentRef testUserWorkspaceRef = new PathRef( USER_WORKSPACE_PARENT_PATH + "/" + testUserWorkspaceName); if (session.exists(testUserWorkspaceRef)) { session.removeDocument(testUserWorkspaceRef); } } // Delete test workspace if exists DocumentRef testWorkspaceDocRef = new PathRef(TEST_WORKSPACE_PATH); if (session.exists(testWorkspaceDocRef)) { session.removeDocument(testWorkspaceDocRef); } }
public static void cleanUp(CoreSession session) throws Exception { // Delete test users and their personal workspace if exist UserManager userManager = Framework.getLocalService(UserManager.class); DocumentModelList testUsers = userManager.searchUsers(TEST_USER_NAME_PREFIX); for (DocumentModel testUser : testUsers) { String testUserName = (String) testUser.getPropertyValue(userManager.getUserSchemaName() + ":" + userManager.getUserIdField()); if (userManager.getPrincipal(testUserName) != null) { userManager.deleteUser(testUserName); } String testUserWorkspaceName = IdUtils.generateId(testUserName, "-", false, 30); DocumentRef testUserWorkspaceRef = new PathRef( USER_WORKSPACE_PARENT_PATH + "/" + testUserWorkspaceName); if (session.exists(testUserWorkspaceRef)) { session.removeDocument(testUserWorkspaceRef); session.save(); } } // Delete test workspace if exists DocumentRef testWorkspaceDocRef = new PathRef(TEST_WORKSPACE_PATH); if (session.exists(testWorkspaceDocRef)) { session.removeDocument(testWorkspaceDocRef); session.save(); } }
diff --git a/bConomy/src/uk/codingbadgers/bconomy/config/Config.java b/bConomy/src/uk/codingbadgers/bconomy/config/Config.java index b2c8e55..ec6d3e0 100644 --- a/bConomy/src/uk/codingbadgers/bconomy/config/Config.java +++ b/bConomy/src/uk/codingbadgers/bconomy/config/Config.java @@ -1,81 +1,81 @@ package uk.codingbadgers.bconomy.config; import org.bukkit.configuration.file.FileConfiguration; import uk.codingbadgers.bconomy.Global; import uk.thecodingbadgers.bDatabaseManager.bDatabaseManager.DatabaseType; public class Config { public static class DatabaseInfo { public DatabaseType driver; public String host; public String dbname; public String tablename; public String user; public String password; public int port = 3306; public int update = 20; } public static class Currency { public String name; public char symbol; public String format; } public static DatabaseInfo m_dbInfo = null; public static Currency m_currency = null; public static int m_startingBalance; public static boolean setupConfig() { FileConfiguration config = Global.getModule().getConfig(); try { // database config config.addDefault("database.driver", "SQL"); config.addDefault("database.host", "localhost"); config.addDefault("database.dbname", "bConomy"); config.addDefault("database.tablename", "bConomy"); config.addDefault("database.user", "root"); config.addDefault("database.password", ""); config.addDefault("database.port", 3306); config.addDefault("database.updateTime", 2); // currency info config config.addDefault("currency.name", "pounds"); - config.addDefault("currency.symbol", "�"); + config.addDefault("currency.symbol", "$"); config.addDefault("currency.format", "@##0.00"); // economy config config.addDefault("economy.startingBalance", 30); config.options().copyDefaults(true); } catch (Exception ex) { ex.printStackTrace(); return false; } m_dbInfo = new DatabaseInfo(); m_dbInfo.driver = DatabaseType.valueOf(config.getString("database.driver", "SQL")); m_dbInfo.host = config.getString("database.host", "localhost"); m_dbInfo.dbname = config.getString("database.dbname", "bConomy"); m_dbInfo.tablename = config.getString("database.tablename", "bConomy"); m_dbInfo.user = config.getString("database.user", "root"); m_dbInfo.password = config.getString("database.password", ""); m_dbInfo.port = config.getInt("database.port", 3306); m_dbInfo.update = config.getInt("database.updateTime", 2); m_currency = new Currency(); m_currency.name = config.getString("currency.name", "pounds"); - m_currency.symbol = config.getString("currency.symbol", "�").toCharArray()[0]; + m_currency.symbol = config.getString("currency.symbol", "$").toCharArray()[0]; m_currency.format = config.getString("currency.fomat", "@#,##0.00").replace('@', m_currency.symbol); m_startingBalance = config.getInt("economy.startingBalance", 30); Global.getPlugin().saveConfig(); return true; } }
false
true
public static boolean setupConfig() { FileConfiguration config = Global.getModule().getConfig(); try { // database config config.addDefault("database.driver", "SQL"); config.addDefault("database.host", "localhost"); config.addDefault("database.dbname", "bConomy"); config.addDefault("database.tablename", "bConomy"); config.addDefault("database.user", "root"); config.addDefault("database.password", ""); config.addDefault("database.port", 3306); config.addDefault("database.updateTime", 2); // currency info config config.addDefault("currency.name", "pounds"); config.addDefault("currency.symbol", "�"); config.addDefault("currency.format", "@##0.00"); // economy config config.addDefault("economy.startingBalance", 30); config.options().copyDefaults(true); } catch (Exception ex) { ex.printStackTrace(); return false; } m_dbInfo = new DatabaseInfo(); m_dbInfo.driver = DatabaseType.valueOf(config.getString("database.driver", "SQL")); m_dbInfo.host = config.getString("database.host", "localhost"); m_dbInfo.dbname = config.getString("database.dbname", "bConomy"); m_dbInfo.tablename = config.getString("database.tablename", "bConomy"); m_dbInfo.user = config.getString("database.user", "root"); m_dbInfo.password = config.getString("database.password", ""); m_dbInfo.port = config.getInt("database.port", 3306); m_dbInfo.update = config.getInt("database.updateTime", 2); m_currency = new Currency(); m_currency.name = config.getString("currency.name", "pounds"); m_currency.symbol = config.getString("currency.symbol", "�").toCharArray()[0]; m_currency.format = config.getString("currency.fomat", "@#,##0.00").replace('@', m_currency.symbol); m_startingBalance = config.getInt("economy.startingBalance", 30); Global.getPlugin().saveConfig(); return true; }
public static boolean setupConfig() { FileConfiguration config = Global.getModule().getConfig(); try { // database config config.addDefault("database.driver", "SQL"); config.addDefault("database.host", "localhost"); config.addDefault("database.dbname", "bConomy"); config.addDefault("database.tablename", "bConomy"); config.addDefault("database.user", "root"); config.addDefault("database.password", ""); config.addDefault("database.port", 3306); config.addDefault("database.updateTime", 2); // currency info config config.addDefault("currency.name", "pounds"); config.addDefault("currency.symbol", "$"); config.addDefault("currency.format", "@##0.00"); // economy config config.addDefault("economy.startingBalance", 30); config.options().copyDefaults(true); } catch (Exception ex) { ex.printStackTrace(); return false; } m_dbInfo = new DatabaseInfo(); m_dbInfo.driver = DatabaseType.valueOf(config.getString("database.driver", "SQL")); m_dbInfo.host = config.getString("database.host", "localhost"); m_dbInfo.dbname = config.getString("database.dbname", "bConomy"); m_dbInfo.tablename = config.getString("database.tablename", "bConomy"); m_dbInfo.user = config.getString("database.user", "root"); m_dbInfo.password = config.getString("database.password", ""); m_dbInfo.port = config.getInt("database.port", 3306); m_dbInfo.update = config.getInt("database.updateTime", 2); m_currency = new Currency(); m_currency.name = config.getString("currency.name", "pounds"); m_currency.symbol = config.getString("currency.symbol", "$").toCharArray()[0]; m_currency.format = config.getString("currency.fomat", "@#,##0.00").replace('@', m_currency.symbol); m_startingBalance = config.getInt("economy.startingBalance", 30); Global.getPlugin().saveConfig(); return true; }
diff --git a/services/src/main/java/org/keycloak/services/managers/RealmManager.java b/services/src/main/java/org/keycloak/services/managers/RealmManager.java index d0f3e954c9..1387f12fee 100755 --- a/services/src/main/java/org/keycloak/services/managers/RealmManager.java +++ b/services/src/main/java/org/keycloak/services/managers/RealmManager.java @@ -1,462 +1,462 @@ package org.keycloak.services.managers; import org.jboss.resteasy.logging.Logger; import org.keycloak.models.*; import org.keycloak.representations.idm.*; import org.keycloak.models.UserModel.RequiredAction; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.atomic.AtomicLong; /** * Per request object * * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public class RealmManager { protected static final Logger logger = Logger.getLogger(RealmManager.class); private static AtomicLong counter = new AtomicLong(1); public static String generateId() { return counter.getAndIncrement() + "-" + System.currentTimeMillis(); } protected KeycloakSession identitySession; public RealmManager(KeycloakSession identitySession) { this.identitySession = identitySession; } public RealmModel getKeycloakAdminstrationRealm() { return getRealm(Constants.ADMIN_REALM); } public RealmModel getRealm(String id) { return identitySession.getRealm(id); } public RealmModel createRealm(String name) { return createRealm(generateId(), name); } public RealmModel createRealm(String id, String name) { RealmModel realm = identitySession.createRealm(id, name); realm.setName(name); realm.addRole(Constants.WILDCARD_ROLE); realm.addRole(Constants.APPLICATION_ROLE); realm.addRole(Constants.IDENTITY_REQUESTER_ROLE); return realm; } public void generateRealmKeys(RealmModel realm) { KeyPair keyPair = null; try { keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } realm.setPrivateKey(keyPair.getPrivate()); realm.setPublicKey(keyPair.getPublic()); } public void updateRealm(RealmRepresentation rep, RealmModel realm) { if (rep.getRealm() != null) realm.setName(rep.getRealm()); if (rep.isEnabled() != null) realm.setEnabled(rep.isEnabled()); if (rep.isSocial() != null) realm.setSocial(rep.isSocial()); if (rep.isCookieLoginAllowed() != null) realm.setCookieLoginAllowed(rep.isCookieLoginAllowed()); if (rep.isRegistrationAllowed() != null) realm.setRegistrationAllowed(rep.isRegistrationAllowed()); if (rep.isVerifyEmail() != null) realm.setVerifyEmail(rep.isVerifyEmail()); if (rep.isResetPasswordAllowed() != null) realm.setResetPasswordAllowed(rep.isResetPasswordAllowed()); if (rep.isAutomaticRegistrationAfterSocialLogin() != null) realm.setAutomaticRegistrationAfterSocialLogin(rep.isAutomaticRegistrationAfterSocialLogin()); if (rep.isSslNotRequired() != null) realm.setSslNotRequired((rep.isSslNotRequired())); if (rep.getAccessCodeLifespan() != null) realm.setAccessCodeLifespan(rep.getAccessCodeLifespan()); if (rep.getAccessCodeLifespanUserAction() != null) realm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction()); if (rep.getTokenLifespan() != null) realm.setTokenLifespan(rep.getTokenLifespan()); if (rep.getRequiredOAuthClientCredentials() != null) { realm.updateRequiredOAuthClientCredentials(rep.getRequiredOAuthClientCredentials()); } if (rep.getRequiredCredentials() != null) { realm.updateRequiredCredentials(rep.getRequiredCredentials()); } if (rep.getRequiredApplicationCredentials() != null) { realm.updateRequiredApplicationCredentials(rep.getRequiredApplicationCredentials()); } if (rep.getDefaultRoles() != null) { realm.updateDefaultRoles(rep.getDefaultRoles()); } if (rep.getAccountManagement() != null && rep.getAccountManagement()) { enableAccountManagement(realm); } else { disableAccountManagement(realm); } if (rep.getSmtpServer() != null) { realm.setSmtpConfig(new HashMap(rep.getSmtpServer())); } if (rep.getSocialProviders() != null) { realm.setSocialConfig(new HashMap(rep.getSocialProviders())); } } private void enableAccountManagement(RealmModel realm) { ApplicationModel application = realm.getApplicationById(Constants.ACCOUNT_MANAGEMENT_APPLICATION); if (application == null) { application = realm.addApplication(Constants.ACCOUNT_MANAGEMENT_APPLICATION); UserCredentialModel password = new UserCredentialModel(); password.setType(UserCredentialModel.PASSWORD); password.setValue(UUID.randomUUID().toString()); // just a random password as we'll never access it realm.updateCredential(application.getApplicationUser(), password); RoleModel applicationRole = realm.getRole(Constants.APPLICATION_ROLE); realm.grantRole(application.getApplicationUser(), applicationRole); } application.setEnabled(true); } private void disableAccountManagement(RealmModel realm) { ApplicationModel application = realm.getApplicationNameMap().get(Constants.ACCOUNT_MANAGEMENT_APPLICATION); if (application != null) { application.setEnabled(false); // TODO Should we delete the application instead? } } public RealmModel importRealm(RealmRepresentation rep, UserModel realmCreator) { //verifyRealmRepresentation(rep); RealmModel realm = createRealm(rep.getRealm()); importRealm(rep, realm); return realm; } public void importRealm(RealmRepresentation rep, RealmModel newRealm) { newRealm.setName(rep.getRealm()); if (rep.isEnabled() != null) newRealm.setEnabled(rep.isEnabled()); if (rep.isSocial() != null) newRealm.setSocial(rep.isSocial()); if (rep.getTokenLifespan() != null) newRealm.setTokenLifespan(rep.getTokenLifespan()); else newRealm.setTokenLifespan(300); if (rep.getAccessCodeLifespan() != null) newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan()); else newRealm.setAccessCodeLifespan(60); if (rep.getAccessCodeLifespanUserAction() != null) newRealm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction()); else newRealm.setAccessCodeLifespanUserAction(300); if (rep.isSslNotRequired() != null) newRealm.setSslNotRequired(rep.isSslNotRequired()); if (rep.isCookieLoginAllowed() != null) newRealm.setCookieLoginAllowed(rep.isCookieLoginAllowed()); if (rep.isRegistrationAllowed() != null) newRealm.setRegistrationAllowed(rep.isRegistrationAllowed()); if (rep.isVerifyEmail() != null) newRealm.setVerifyEmail(rep.isVerifyEmail()); if (rep.isResetPasswordAllowed() != null) newRealm.setResetPasswordAllowed(rep.isResetPasswordAllowed()); if (rep.isAutomaticRegistrationAfterSocialLogin() != null) newRealm.setAutomaticRegistrationAfterSocialLogin(rep.isAutomaticRegistrationAfterSocialLogin()); if (rep.getPrivateKey() == null || rep.getPublicKey() == null) { generateRealmKeys(newRealm); } else { newRealm.setPrivateKeyPem(rep.getPrivateKey()); newRealm.setPublicKeyPem(rep.getPublicKey()); } Map<String, UserModel> userMap = new HashMap<String, UserModel>(); if (rep.getRequiredCredentials() != null) { for (String requiredCred : rep.getRequiredCredentials()) { addRequiredCredential(newRealm, requiredCred); } } else { addRequiredCredential(newRealm, CredentialRepresentation.PASSWORD); } if (rep.getRequiredApplicationCredentials() != null) { for (String requiredCred : rep.getRequiredApplicationCredentials()) { addResourceRequiredCredential(newRealm, requiredCred); } } else { addResourceRequiredCredential(newRealm, CredentialRepresentation.PASSWORD); } if (rep.getRequiredOAuthClientCredentials() != null) { for (String requiredCred : rep.getRequiredOAuthClientCredentials()) { addOAuthClientRequiredCredential(newRealm, requiredCred); } } else { addOAuthClientRequiredCredential(newRealm, CredentialRepresentation.PASSWORD); } if (rep.getUsers() != null) { for (UserRepresentation userRep : rep.getUsers()) { UserModel user = createUser(newRealm, userRep); userMap.put(user.getLoginName(), user); } } if (rep.getRoles() != null) { for (RoleRepresentation roleRep : rep.getRoles()) { createRole(newRealm, roleRep); } } if (rep.getDefaultRoles() != null) { for (String roleString : rep.getDefaultRoles()) { newRealm.addDefaultRole(roleString.trim()); } } if (rep.getApplications() != null) { createApplications(rep, newRealm); } if (rep.getRoleMappings() != null) { for (UserRoleMappingRepresentation mapping : rep.getRoleMappings()) { UserModel user = userMap.get(mapping.getUsername()); for (String roleString : mapping.getRoles()) { RoleModel role = newRealm.getRole(roleString.trim()); if (role == null) { role = newRealm.addRole(roleString.trim()); } newRealm.grantRole(user, role); } } } if (rep.getScopeMappings() != null) { for (ScopeMappingRepresentation scope : rep.getScopeMappings()) { for (String roleString : scope.getRoles()) { RoleModel role = newRealm.getRole(roleString.trim()); if (role == null) { role = newRealm.addRole(roleString.trim()); } UserModel user = userMap.get(scope.getUsername()); newRealm.addScopeMapping(user, role.getName()); } } } if (rep.getSocialMappings() != null) { for (SocialMappingRepresentation socialMapping : rep.getSocialMappings()) { UserModel user = userMap.get(socialMapping.getUsername()); for (SocialLinkRepresentation link : socialMapping.getSocialLinks()) { SocialLinkModel mappingModel = new SocialLinkModel(link.getSocialProvider(), link.getSocialUsername()); newRealm.addSocialLink(user, mappingModel); } } } - if (rep.isAccountManagement() != null && rep.isAccountManagement()) { + if (rep.getAccountManagement() != null && rep.getAccountManagement()) { enableAccountManagement(newRealm); } if (rep.getSmtpServer() != null) { newRealm.setSmtpConfig(new HashMap(rep.getSmtpServer())); } if (rep.getSocialProviders() != null) { newRealm.setSocialConfig(new HashMap(rep.getSocialProviders())); } } public void createRole(RealmModel newRealm, RoleRepresentation roleRep) { RoleModel role = newRealm.addRole(roleRep.getName()); if (roleRep.getDescription() != null) role.setDescription(roleRep.getDescription()); } public UserModel createUser(RealmModel newRealm, UserRepresentation userRep) { UserModel user = newRealm.addUser(userRep.getUsername()); user.setEnabled(userRep.isEnabled()); user.setEmail(userRep.getEmail()); if (userRep.getAttributes() != null) { for (Map.Entry<String, String> entry : userRep.getAttributes().entrySet()) { user.setAttribute(entry.getKey(), entry.getValue()); } } if (userRep.getRequiredActions() != null) { for (String requiredAction : userRep.getRequiredActions()) { user.addRequiredAction(RequiredAction.valueOf(requiredAction)); } } if (userRep.getCredentials() != null) { for (CredentialRepresentation cred : userRep.getCredentials()) { UserCredentialModel credential = fromRepresentation(cred); newRealm.updateCredential(user, credential); } } return user; } public static UserCredentialModel fromRepresentation(CredentialRepresentation cred) { UserCredentialModel credential = new UserCredentialModel(); credential.setType(cred.getType()); credential.setValue(cred.getValue()); return credential; } /** * Query users based on a search string: * <p/> * "Bill Burke" first and last name * "[email protected]" email * "Burke" lastname or username * * @param searchString * @param realmModel * @return */ public List<UserModel> searchUsers(String searchString, RealmModel realmModel) { if (searchString == null) { return Collections.emptyList(); } String search = searchString.trim(); if (search.contains(" ")) { //first and last name String[] split = search.split(" "); if (split.length != 2) { return Collections.emptyList(); } Map<String, String> attributes = new HashMap<String, String>(); attributes.put(UserModel.FIRST_NAME, split[0]); attributes.put(UserModel.LAST_NAME, split[1]); return realmModel.searchForUserByAttributes(attributes); } else if (search.contains("@")) { // email Map<String, String> attributes = new HashMap<String, String>(); attributes.put(UserModel.EMAIL, search); return realmModel.searchForUserByAttributes(attributes); } else { // username and lastname Map<String, String> attributes = new HashMap<String, String>(); attributes.put(UserModel.LOGIN_NAME, search); List<UserModel> usernameQuery = realmModel.searchForUserByAttributes(attributes); attributes.clear(); attributes.put(UserModel.LAST_NAME, search); List<UserModel> lastnameQuery = realmModel.searchForUserByAttributes(attributes); if (usernameQuery.size() == 0) { return lastnameQuery; } else if (lastnameQuery.size() == 0) { return usernameQuery; } List<UserModel> results = new ArrayList<UserModel>(); results.addAll(usernameQuery); for (UserModel lastnameUser : lastnameQuery) { boolean found = false; for (UserModel usernameUser : usernameQuery) { if (usernameUser.getLoginName().equals(lastnameUser.getLoginName())) { found = true; break; } } if (!found) { results.add(lastnameUser); } } return results; } } public void addRequiredCredential(RealmModel newRealm, String requiredCred) { newRealm.addRequiredCredential(requiredCred); } public void addResourceRequiredCredential(RealmModel newRealm, String requiredCred) { newRealm.addRequiredResourceCredential(requiredCred); } public void addOAuthClientRequiredCredential(RealmModel newRealm, String requiredCred) { newRealm.addRequiredOAuthClientCredential(requiredCred); } protected void createApplications(RealmRepresentation rep, RealmModel realm) { RoleModel loginRole = realm.getRole(Constants.APPLICATION_ROLE); ApplicationManager manager = new ApplicationManager(this); for (ApplicationRepresentation resourceRep : rep.getApplications()) { manager.createApplication(realm, loginRole, resourceRep); } } public static UserRepresentation toRepresentation(UserModel user) { UserRepresentation rep = new UserRepresentation(); rep.setUsername(user.getLoginName()); rep.setLastName(user.getLastName()); rep.setFirstName(user.getFirstName()); rep.setEmail(user.getEmail()); Map<String, String> attrs = new HashMap<String, String>(); attrs.putAll(user.getAttributes()); rep.setAttributes(attrs); return rep; } public static RoleRepresentation toRepresentation(RoleModel role) { RoleRepresentation rep = new RoleRepresentation(); rep.setId(role.getId()); rep.setName(role.getName()); rep.setDescription(role.getDescription()); return rep; } public static RealmRepresentation toRepresentation(RealmModel realm) { RealmRepresentation rep = new RealmRepresentation(); rep.setId(realm.getId()); rep.setRealm(realm.getName()); rep.setEnabled(realm.isEnabled()); rep.setSocial(realm.isSocial()); rep.setAutomaticRegistrationAfterSocialLogin(realm.isAutomaticRegistrationAfterSocialLogin()); rep.setSslNotRequired(realm.isSslNotRequired()); rep.setCookieLoginAllowed(realm.isCookieLoginAllowed()); rep.setPublicKey(realm.getPublicKeyPem()); rep.setPrivateKey(realm.getPrivateKeyPem()); rep.setRegistrationAllowed(realm.isRegistrationAllowed()); rep.setVerifyEmail(realm.isVerifyEmail()); rep.setResetPasswordAllowed(realm.isResetPasswordAllowed()); rep.setTokenLifespan(realm.getTokenLifespan()); rep.setAccessCodeLifespan(realm.getAccessCodeLifespan()); rep.setAccessCodeLifespanUserAction(realm.getAccessCodeLifespanUserAction()); rep.setSmtpServer(realm.getSmtpConfig()); rep.setSocialProviders(realm.getSocialConfig()); ApplicationModel accountManagementApplication = realm.getApplicationNameMap().get(Constants.ACCOUNT_MANAGEMENT_APPLICATION); rep.setAccountManagement(accountManagementApplication != null && accountManagementApplication.isEnabled()); List<RoleModel> defaultRoles = realm.getDefaultRoles(); if (defaultRoles.size() > 0) { String[] d = new String[defaultRoles.size()]; for (int i = 0; i < d.length; i++) { d[i] = defaultRoles.get(i).getName(); } rep.setDefaultRoles(d); } List<RequiredCredentialModel> requiredCredentialModels = realm.getRequiredCredentials(); if (requiredCredentialModels.size() > 0) { rep.setRequiredCredentials(new HashSet<String>()); for (RequiredCredentialModel cred : requiredCredentialModels) { rep.getRequiredCredentials().add(cred.getType()); } } List<RequiredCredentialModel> requiredResourceCredentialModels = realm.getRequiredApplicationCredentials(); if (requiredResourceCredentialModels.size() > 0) { rep.setRequiredApplicationCredentials(new HashSet<String>()); for (RequiredCredentialModel cred : requiredResourceCredentialModels) { rep.getRequiredApplicationCredentials().add(cred.getType()); } } List<RequiredCredentialModel> requiredOAuthCredentialModels = realm.getRequiredOAuthClientCredentials(); if (requiredOAuthCredentialModels.size() > 0) { rep.setRequiredOAuthClientCredentials(new HashSet<String>()); for (RequiredCredentialModel cred : requiredOAuthCredentialModels) { rep.getRequiredOAuthClientCredentials().add(cred.getType()); } } return rep; } }
true
true
public void importRealm(RealmRepresentation rep, RealmModel newRealm) { newRealm.setName(rep.getRealm()); if (rep.isEnabled() != null) newRealm.setEnabled(rep.isEnabled()); if (rep.isSocial() != null) newRealm.setSocial(rep.isSocial()); if (rep.getTokenLifespan() != null) newRealm.setTokenLifespan(rep.getTokenLifespan()); else newRealm.setTokenLifespan(300); if (rep.getAccessCodeLifespan() != null) newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan()); else newRealm.setAccessCodeLifespan(60); if (rep.getAccessCodeLifespanUserAction() != null) newRealm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction()); else newRealm.setAccessCodeLifespanUserAction(300); if (rep.isSslNotRequired() != null) newRealm.setSslNotRequired(rep.isSslNotRequired()); if (rep.isCookieLoginAllowed() != null) newRealm.setCookieLoginAllowed(rep.isCookieLoginAllowed()); if (rep.isRegistrationAllowed() != null) newRealm.setRegistrationAllowed(rep.isRegistrationAllowed()); if (rep.isVerifyEmail() != null) newRealm.setVerifyEmail(rep.isVerifyEmail()); if (rep.isResetPasswordAllowed() != null) newRealm.setResetPasswordAllowed(rep.isResetPasswordAllowed()); if (rep.isAutomaticRegistrationAfterSocialLogin() != null) newRealm.setAutomaticRegistrationAfterSocialLogin(rep.isAutomaticRegistrationAfterSocialLogin()); if (rep.getPrivateKey() == null || rep.getPublicKey() == null) { generateRealmKeys(newRealm); } else { newRealm.setPrivateKeyPem(rep.getPrivateKey()); newRealm.setPublicKeyPem(rep.getPublicKey()); } Map<String, UserModel> userMap = new HashMap<String, UserModel>(); if (rep.getRequiredCredentials() != null) { for (String requiredCred : rep.getRequiredCredentials()) { addRequiredCredential(newRealm, requiredCred); } } else { addRequiredCredential(newRealm, CredentialRepresentation.PASSWORD); } if (rep.getRequiredApplicationCredentials() != null) { for (String requiredCred : rep.getRequiredApplicationCredentials()) { addResourceRequiredCredential(newRealm, requiredCred); } } else { addResourceRequiredCredential(newRealm, CredentialRepresentation.PASSWORD); } if (rep.getRequiredOAuthClientCredentials() != null) { for (String requiredCred : rep.getRequiredOAuthClientCredentials()) { addOAuthClientRequiredCredential(newRealm, requiredCred); } } else { addOAuthClientRequiredCredential(newRealm, CredentialRepresentation.PASSWORD); } if (rep.getUsers() != null) { for (UserRepresentation userRep : rep.getUsers()) { UserModel user = createUser(newRealm, userRep); userMap.put(user.getLoginName(), user); } } if (rep.getRoles() != null) { for (RoleRepresentation roleRep : rep.getRoles()) { createRole(newRealm, roleRep); } } if (rep.getDefaultRoles() != null) { for (String roleString : rep.getDefaultRoles()) { newRealm.addDefaultRole(roleString.trim()); } } if (rep.getApplications() != null) { createApplications(rep, newRealm); } if (rep.getRoleMappings() != null) { for (UserRoleMappingRepresentation mapping : rep.getRoleMappings()) { UserModel user = userMap.get(mapping.getUsername()); for (String roleString : mapping.getRoles()) { RoleModel role = newRealm.getRole(roleString.trim()); if (role == null) { role = newRealm.addRole(roleString.trim()); } newRealm.grantRole(user, role); } } } if (rep.getScopeMappings() != null) { for (ScopeMappingRepresentation scope : rep.getScopeMappings()) { for (String roleString : scope.getRoles()) { RoleModel role = newRealm.getRole(roleString.trim()); if (role == null) { role = newRealm.addRole(roleString.trim()); } UserModel user = userMap.get(scope.getUsername()); newRealm.addScopeMapping(user, role.getName()); } } } if (rep.getSocialMappings() != null) { for (SocialMappingRepresentation socialMapping : rep.getSocialMappings()) { UserModel user = userMap.get(socialMapping.getUsername()); for (SocialLinkRepresentation link : socialMapping.getSocialLinks()) { SocialLinkModel mappingModel = new SocialLinkModel(link.getSocialProvider(), link.getSocialUsername()); newRealm.addSocialLink(user, mappingModel); } } } if (rep.isAccountManagement() != null && rep.isAccountManagement()) { enableAccountManagement(newRealm); } if (rep.getSmtpServer() != null) { newRealm.setSmtpConfig(new HashMap(rep.getSmtpServer())); } if (rep.getSocialProviders() != null) { newRealm.setSocialConfig(new HashMap(rep.getSocialProviders())); } }
public void importRealm(RealmRepresentation rep, RealmModel newRealm) { newRealm.setName(rep.getRealm()); if (rep.isEnabled() != null) newRealm.setEnabled(rep.isEnabled()); if (rep.isSocial() != null) newRealm.setSocial(rep.isSocial()); if (rep.getTokenLifespan() != null) newRealm.setTokenLifespan(rep.getTokenLifespan()); else newRealm.setTokenLifespan(300); if (rep.getAccessCodeLifespan() != null) newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan()); else newRealm.setAccessCodeLifespan(60); if (rep.getAccessCodeLifespanUserAction() != null) newRealm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction()); else newRealm.setAccessCodeLifespanUserAction(300); if (rep.isSslNotRequired() != null) newRealm.setSslNotRequired(rep.isSslNotRequired()); if (rep.isCookieLoginAllowed() != null) newRealm.setCookieLoginAllowed(rep.isCookieLoginAllowed()); if (rep.isRegistrationAllowed() != null) newRealm.setRegistrationAllowed(rep.isRegistrationAllowed()); if (rep.isVerifyEmail() != null) newRealm.setVerifyEmail(rep.isVerifyEmail()); if (rep.isResetPasswordAllowed() != null) newRealm.setResetPasswordAllowed(rep.isResetPasswordAllowed()); if (rep.isAutomaticRegistrationAfterSocialLogin() != null) newRealm.setAutomaticRegistrationAfterSocialLogin(rep.isAutomaticRegistrationAfterSocialLogin()); if (rep.getPrivateKey() == null || rep.getPublicKey() == null) { generateRealmKeys(newRealm); } else { newRealm.setPrivateKeyPem(rep.getPrivateKey()); newRealm.setPublicKeyPem(rep.getPublicKey()); } Map<String, UserModel> userMap = new HashMap<String, UserModel>(); if (rep.getRequiredCredentials() != null) { for (String requiredCred : rep.getRequiredCredentials()) { addRequiredCredential(newRealm, requiredCred); } } else { addRequiredCredential(newRealm, CredentialRepresentation.PASSWORD); } if (rep.getRequiredApplicationCredentials() != null) { for (String requiredCred : rep.getRequiredApplicationCredentials()) { addResourceRequiredCredential(newRealm, requiredCred); } } else { addResourceRequiredCredential(newRealm, CredentialRepresentation.PASSWORD); } if (rep.getRequiredOAuthClientCredentials() != null) { for (String requiredCred : rep.getRequiredOAuthClientCredentials()) { addOAuthClientRequiredCredential(newRealm, requiredCred); } } else { addOAuthClientRequiredCredential(newRealm, CredentialRepresentation.PASSWORD); } if (rep.getUsers() != null) { for (UserRepresentation userRep : rep.getUsers()) { UserModel user = createUser(newRealm, userRep); userMap.put(user.getLoginName(), user); } } if (rep.getRoles() != null) { for (RoleRepresentation roleRep : rep.getRoles()) { createRole(newRealm, roleRep); } } if (rep.getDefaultRoles() != null) { for (String roleString : rep.getDefaultRoles()) { newRealm.addDefaultRole(roleString.trim()); } } if (rep.getApplications() != null) { createApplications(rep, newRealm); } if (rep.getRoleMappings() != null) { for (UserRoleMappingRepresentation mapping : rep.getRoleMappings()) { UserModel user = userMap.get(mapping.getUsername()); for (String roleString : mapping.getRoles()) { RoleModel role = newRealm.getRole(roleString.trim()); if (role == null) { role = newRealm.addRole(roleString.trim()); } newRealm.grantRole(user, role); } } } if (rep.getScopeMappings() != null) { for (ScopeMappingRepresentation scope : rep.getScopeMappings()) { for (String roleString : scope.getRoles()) { RoleModel role = newRealm.getRole(roleString.trim()); if (role == null) { role = newRealm.addRole(roleString.trim()); } UserModel user = userMap.get(scope.getUsername()); newRealm.addScopeMapping(user, role.getName()); } } } if (rep.getSocialMappings() != null) { for (SocialMappingRepresentation socialMapping : rep.getSocialMappings()) { UserModel user = userMap.get(socialMapping.getUsername()); for (SocialLinkRepresentation link : socialMapping.getSocialLinks()) { SocialLinkModel mappingModel = new SocialLinkModel(link.getSocialProvider(), link.getSocialUsername()); newRealm.addSocialLink(user, mappingModel); } } } if (rep.getAccountManagement() != null && rep.getAccountManagement()) { enableAccountManagement(newRealm); } if (rep.getSmtpServer() != null) { newRealm.setSmtpConfig(new HashMap(rep.getSmtpServer())); } if (rep.getSocialProviders() != null) { newRealm.setSocialConfig(new HashMap(rep.getSocialProviders())); } }
diff --git a/src/main/java/net/alpha01/jwtest/exports/ResultODSExporter.java b/src/main/java/net/alpha01/jwtest/exports/ResultODSExporter.java index 53971fc..aaaef61 100644 --- a/src/main/java/net/alpha01/jwtest/exports/ResultODSExporter.java +++ b/src/main/java/net/alpha01/jwtest/exports/ResultODSExporter.java @@ -1,105 +1,107 @@ package net.alpha01.jwtest.exports; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.math.BigInteger; import java.util.Iterator; import org.jsoup.Jsoup; import com.sun.star.comp.helper.BootstrapException; import com.sun.star.lang.XComponent; import com.sun.star.sheet.XSpreadsheet; import com.sun.star.uno.Exception; import net.alpha01.jwtest.beans.Requirement; import net.alpha01.jwtest.beans.Result; import net.alpha01.jwtest.beans.Session; import net.alpha01.jwtest.beans.Step; import net.alpha01.jwtest.beans.TestCase; import net.alpha01.jwtest.dao.RequirementMapper; import net.alpha01.jwtest.dao.ResultMapper; import net.alpha01.jwtest.dao.ResultMapper.ResultSort; import net.alpha01.jwtest.dao.SessionMapper; import net.alpha01.jwtest.dao.SqlConnection; import net.alpha01.jwtest.dao.SqlSessionMapper; import net.alpha01.jwtest.dao.StepMapper; import net.alpha01.jwtest.dao.TestCaseMapper; import net.alpha01.jwtest.exceptions.JWTestException; import au.com.bytecode.opencsv.CSVWriter; public class ResultODSExporter { public static File exportToODS(int idSession) throws JWTestException{ File tmpFile; try { tmpFile = File.createTempFile("jwtest_export_results", ".ods"); tmpFile.deleteOnExit(); SqlSessionMapper<ResultMapper> sesMapper = SqlConnection.getSessionMapper(ResultMapper.class); SessionMapper sessionMapper = sesMapper.getSqlSession().getMapper(SessionMapper.class); TestCaseMapper testMapper = sesMapper.getSqlSession().getMapper(TestCaseMapper.class); RequirementMapper reqMapper = sesMapper.getSqlSession().getMapper(RequirementMapper.class); StepMapper stepMapper = sesMapper.getSqlSession().getMapper(StepMapper.class); Session sess=sessionMapper.get(BigInteger.valueOf(idSession)); XComponent xComponent=PlanODSExporter.exportToXComponent(sess.getId_plan().intValue()); XSpreadsheet xSpreadsheet=RequirementODSExporter.getSpreadSheet(xComponent, "Esecuzione"); Iterator<Result> itr = sesMapper.getMapper().getAll(new ResultSort(idSession)).iterator(); int y=10; while (itr.hasNext()){ Result res = itr.next(); TestCase test = testMapper.get(res.getId_testcase()); Requirement req= reqMapper.get(test.getId_requirement()); String description=test.getDescription()!=null?Jsoup.parse(test.getDescription()).text():""; String expectedResult=test.getExpected_result()!=null?Jsoup.parse(test.getExpected_result()).text():""; String idReq=req.getType()+"-"+req.getNum()+"-"+test.getId().toString(); String name=test.getName()!=null?Jsoup.parse(test.getName()).text():""; String note=res.getNote()!=null?Jsoup.parse(res.getNote()).text():""; Iterator<Step> its = stepMapper.getAll(test.getId().intValue()).iterator(); int i=0; while (its.hasNext()){ i++; Step step = its.next(); - description+=i+") "+step.getDescription(); - expectedResult+=i+") "+step.getExpected_result(); + String stepDescription=step.getDescription()!=null?Jsoup.parse(step.getDescription()).text():""; + String stepExpectedResult=step.getExpected_result()!=null?Jsoup.parse(step.getExpected_result()).text():""; + description+=i+") "+stepDescription; + expectedResult+=i+") "+stepExpectedResult; } String result; if (res.getSuccess()){ result="OK"; }else{ result="C"; } xSpreadsheet.getCellByPosition(1, y).setFormula(idReq); xSpreadsheet.getCellByPosition(2, y).setFormula(name); xSpreadsheet.getCellByPosition(3, y).setFormula(description); xSpreadsheet.getCellByPosition(4, y).setFormula(expectedResult); xSpreadsheet.getCellByPosition(5, y).setFormula(result); xSpreadsheet.getCellByPosition(7, y++).setFormula(note); } sesMapper.close(); RequirementODSExporter.storeDocComponent(xComponent, "file:///"+tmpFile.getAbsolutePath().replace('\\', '/')); RequirementODSExporter.closeDocComponent(xComponent); return tmpFile; } catch (IOException e) { throw new JWTestException(ResultODSExporter.class,e); } catch (BootstrapException e) { throw new JWTestException(ResultODSExporter.class,e); } catch (Exception e) { throw new JWTestException(ResultODSExporter.class,e); } catch (java.lang.Exception e) { throw new JWTestException(ResultODSExporter.class,e); } } }
true
true
public static File exportToODS(int idSession) throws JWTestException{ File tmpFile; try { tmpFile = File.createTempFile("jwtest_export_results", ".ods"); tmpFile.deleteOnExit(); SqlSessionMapper<ResultMapper> sesMapper = SqlConnection.getSessionMapper(ResultMapper.class); SessionMapper sessionMapper = sesMapper.getSqlSession().getMapper(SessionMapper.class); TestCaseMapper testMapper = sesMapper.getSqlSession().getMapper(TestCaseMapper.class); RequirementMapper reqMapper = sesMapper.getSqlSession().getMapper(RequirementMapper.class); StepMapper stepMapper = sesMapper.getSqlSession().getMapper(StepMapper.class); Session sess=sessionMapper.get(BigInteger.valueOf(idSession)); XComponent xComponent=PlanODSExporter.exportToXComponent(sess.getId_plan().intValue()); XSpreadsheet xSpreadsheet=RequirementODSExporter.getSpreadSheet(xComponent, "Esecuzione"); Iterator<Result> itr = sesMapper.getMapper().getAll(new ResultSort(idSession)).iterator(); int y=10; while (itr.hasNext()){ Result res = itr.next(); TestCase test = testMapper.get(res.getId_testcase()); Requirement req= reqMapper.get(test.getId_requirement()); String description=test.getDescription()!=null?Jsoup.parse(test.getDescription()).text():""; String expectedResult=test.getExpected_result()!=null?Jsoup.parse(test.getExpected_result()).text():""; String idReq=req.getType()+"-"+req.getNum()+"-"+test.getId().toString(); String name=test.getName()!=null?Jsoup.parse(test.getName()).text():""; String note=res.getNote()!=null?Jsoup.parse(res.getNote()).text():""; Iterator<Step> its = stepMapper.getAll(test.getId().intValue()).iterator(); int i=0; while (its.hasNext()){ i++; Step step = its.next(); description+=i+") "+step.getDescription(); expectedResult+=i+") "+step.getExpected_result(); } String result; if (res.getSuccess()){ result="OK"; }else{ result="C"; } xSpreadsheet.getCellByPosition(1, y).setFormula(idReq); xSpreadsheet.getCellByPosition(2, y).setFormula(name); xSpreadsheet.getCellByPosition(3, y).setFormula(description); xSpreadsheet.getCellByPosition(4, y).setFormula(expectedResult); xSpreadsheet.getCellByPosition(5, y).setFormula(result); xSpreadsheet.getCellByPosition(7, y++).setFormula(note); } sesMapper.close(); RequirementODSExporter.storeDocComponent(xComponent, "file:///"+tmpFile.getAbsolutePath().replace('\\', '/')); RequirementODSExporter.closeDocComponent(xComponent); return tmpFile; } catch (IOException e) { throw new JWTestException(ResultODSExporter.class,e); } catch (BootstrapException e) { throw new JWTestException(ResultODSExporter.class,e); } catch (Exception e) { throw new JWTestException(ResultODSExporter.class,e); } catch (java.lang.Exception e) { throw new JWTestException(ResultODSExporter.class,e); } }
public static File exportToODS(int idSession) throws JWTestException{ File tmpFile; try { tmpFile = File.createTempFile("jwtest_export_results", ".ods"); tmpFile.deleteOnExit(); SqlSessionMapper<ResultMapper> sesMapper = SqlConnection.getSessionMapper(ResultMapper.class); SessionMapper sessionMapper = sesMapper.getSqlSession().getMapper(SessionMapper.class); TestCaseMapper testMapper = sesMapper.getSqlSession().getMapper(TestCaseMapper.class); RequirementMapper reqMapper = sesMapper.getSqlSession().getMapper(RequirementMapper.class); StepMapper stepMapper = sesMapper.getSqlSession().getMapper(StepMapper.class); Session sess=sessionMapper.get(BigInteger.valueOf(idSession)); XComponent xComponent=PlanODSExporter.exportToXComponent(sess.getId_plan().intValue()); XSpreadsheet xSpreadsheet=RequirementODSExporter.getSpreadSheet(xComponent, "Esecuzione"); Iterator<Result> itr = sesMapper.getMapper().getAll(new ResultSort(idSession)).iterator(); int y=10; while (itr.hasNext()){ Result res = itr.next(); TestCase test = testMapper.get(res.getId_testcase()); Requirement req= reqMapper.get(test.getId_requirement()); String description=test.getDescription()!=null?Jsoup.parse(test.getDescription()).text():""; String expectedResult=test.getExpected_result()!=null?Jsoup.parse(test.getExpected_result()).text():""; String idReq=req.getType()+"-"+req.getNum()+"-"+test.getId().toString(); String name=test.getName()!=null?Jsoup.parse(test.getName()).text():""; String note=res.getNote()!=null?Jsoup.parse(res.getNote()).text():""; Iterator<Step> its = stepMapper.getAll(test.getId().intValue()).iterator(); int i=0; while (its.hasNext()){ i++; Step step = its.next(); String stepDescription=step.getDescription()!=null?Jsoup.parse(step.getDescription()).text():""; String stepExpectedResult=step.getExpected_result()!=null?Jsoup.parse(step.getExpected_result()).text():""; description+=i+") "+stepDescription; expectedResult+=i+") "+stepExpectedResult; } String result; if (res.getSuccess()){ result="OK"; }else{ result="C"; } xSpreadsheet.getCellByPosition(1, y).setFormula(idReq); xSpreadsheet.getCellByPosition(2, y).setFormula(name); xSpreadsheet.getCellByPosition(3, y).setFormula(description); xSpreadsheet.getCellByPosition(4, y).setFormula(expectedResult); xSpreadsheet.getCellByPosition(5, y).setFormula(result); xSpreadsheet.getCellByPosition(7, y++).setFormula(note); } sesMapper.close(); RequirementODSExporter.storeDocComponent(xComponent, "file:///"+tmpFile.getAbsolutePath().replace('\\', '/')); RequirementODSExporter.closeDocComponent(xComponent); return tmpFile; } catch (IOException e) { throw new JWTestException(ResultODSExporter.class,e); } catch (BootstrapException e) { throw new JWTestException(ResultODSExporter.class,e); } catch (Exception e) { throw new JWTestException(ResultODSExporter.class,e); } catch (java.lang.Exception e) { throw new JWTestException(ResultODSExporter.class,e); } }
diff --git a/LunchBunch/src/source/code/Global.java b/LunchBunch/src/source/code/Global.java index 4cf2638..6d5b599 100644 --- a/LunchBunch/src/source/code/Global.java +++ b/LunchBunch/src/source/code/Global.java @@ -1,313 +1,314 @@ package source.code; import java.util.ArrayList; import java.util.Calendar; import android.app.Application; import android.content.Intent; public class Global extends Application { private ArrayList<Lunch> lunchInvites; private ArrayList<Lunch> lunchesAttending; private ArrayList<Lunch> lunchReminders; private Lunch currentCreatingLunch; private Lunch currentClickedLunch; private ArrayList<Friend> lunchFriends; private FriendListAdapter<Friend> friendListAdapter; private Calendar startTime; private Lunch fakeInvite; private boolean fakeInviteBool = false; public void removeOldLunches(){ ArrayList<Lunch> toberemoved = new ArrayList<Lunch>(); for(Lunch lunch:lunchInvites){ if(lunch.getLunchTime().getTimeInMillis()<System.currentTimeMillis()){ toberemoved.add(lunch); } } lunchInvites.removeAll(toberemoved); toberemoved.clear(); for(Lunch lunch:lunchesAttending){ if(lunch.getLunchTime().getTimeInMillis()<System.currentTimeMillis()){ toberemoved.add(lunch); System.out.println("removed"+ lunch.getTitle()); } } lunchesAttending.removeAll(toberemoved); toberemoved.clear(); } public void makeLunches() { if (lunchInvites == null) { Calendar systemTime = Calendar.getInstance(); startTime = (Calendar)systemTime.clone(); Calendar firstLunchTime = (Calendar)systemTime.clone(); firstLunchTime.add(Calendar.DAY_OF_YEAR, 1); firstLunchTime.add(Calendar.MINUTE, 35); ArrayList<Friend> attending = new ArrayList<Friend>(); attending.add(new Friend("Anjali Muralidhar")); attending.add(new Friend("Michael Puncel")); attending.add(new Friend("Pallavi Powale")); lunchInvites = new ArrayList<Lunch>(); lunchesAttending = new ArrayList<Lunch>(); lunchReminders = new ArrayList<Lunch>(); Lunch tbell = new Lunch("Taco Bell"); tbell.setLunchTime(firstLunchTime); tbell.setFriends(attending); tbell.addAcceptedFriend(attending.get(0)); tbell.addAcceptedFriend(attending.get(1)); Lunch cosi = new Lunch("Cosi"); Calendar secondLunchTime = (Calendar)firstLunchTime.clone(); secondLunchTime.add(Calendar.DAY_OF_YEAR, 1); secondLunchTime.add(Calendar.MINUTE, 35); cosi.setLunchTime(secondLunchTime); cosi.setFriends(attending); cosi.addAcceptedFriend(attending.get(2)); cosi.addAcceptedFriend(attending.get(1)); Lunch masa = new Lunch("Masa"); Calendar thirdLunchTime = (Calendar)secondLunchTime.clone(); thirdLunchTime.add(Calendar.MINUTE, 35); thirdLunchTime.add(Calendar.DAY_OF_YEAR, 1); masa.setLunchTime(thirdLunchTime); masa.setFriends(attending); masa.addAcceptedFriend(attending.get(0)); masa.addAcceptedFriend(attending.get(1)); lunchInvites.add(tbell); lunchInvites.add(cosi); lunchInvites.add(masa); Lunch dhaba = new Lunch("Desi Dhaba"); Calendar attendTime = (Calendar)systemTime.clone(); attendTime.add(Calendar.MINUTE, 35); dhaba.setLunchTime(attendTime); dhaba.setFriends(attending); dhaba.addAcceptedFriend(attending.get(0)); dhaba.addAcceptedFriend(attending.get(1)); dhaba.setConfirmationRequested(true); dhaba.setReminderTime(34); Lunch maggianos = new Lunch("Maggiano's"); Calendar attendTime2 = (Calendar)systemTime.clone(); attendTime2.add(Calendar.MINUTE, 36); maggianos.setLunchTime(attendTime2); maggianos.setFriends(attending); maggianos.addAcceptedFriend(attending.get(2)); maggianos.addAcceptedFriend(attending.get(1)); addLunchAttending(dhaba); addLunchAttending(maggianos); Intent intent = new Intent(this, NotificationService.class); startService(intent); fakeInvite = new Lunch("Cinderella's"); - attendTime.add(Calendar.DAY_OF_MONTH, 1); + Calendar fakeTime = (Calendar)attendTime.clone(); + fakeTime.add(Calendar.DAY_OF_MONTH, 1); fakeInvite.setLunchTime(attendTime); fakeInvite.setFriends(attending); fakeInvite.addAcceptedFriend(attending.get(2)); } } public Lunch getFakeLunch() { return this.fakeInvite; } public Calendar getStartTime() { return this.startTime; } public void createLunchDone() { int insertionindex = 0; for(Lunch lunch:lunchesAttending){ int compare=currentCreatingLunch.compareTo(lunch); if(compare>0){ insertionindex +=1; } } addLunchAttending(currentCreatingLunch, insertionindex); } public Lunch getCurrentCreatingLunch() { return currentCreatingLunch; } public void setCurrentCreatingLunch(Lunch l) { currentCreatingLunch = l; } public Lunch getCreatingLunch() { return this.currentCreatingLunch; } public void setCurrentClickedLunch(Lunch l) { currentClickedLunch = l; } public Lunch getCurrentClickedLunch() { return this.currentClickedLunch; } public ArrayList<Friend> getLunchFriends() { return lunchFriends; } public void setFakeInviteBool(boolean bool) { this.fakeInviteBool = bool; } public boolean getFakeInviteBool() { return this.fakeInviteBool; } public void addLunchInvite(Lunch lunch){ int insertionindex = 0; for(Lunch l:lunchInvites){ int compare=lunch.compareTo(l); if(compare>0){ insertionindex +=1; } } lunchInvites.add(insertionindex,lunch); } public synchronized void addLunchAttending(Lunch lunch) { lunchesAttending.add(lunch); if(lunch.getReminderTime() != null) { if (lunchReminders.size() == 0 ) { lunchReminders.add(lunch); } else { for (int i = 0; i < lunchReminders.size(); i++) { if (lunchReminders.get(i).getReminderTime().after(lunch.getReminderTime())){ lunchReminders.add(i, lunch); break; } if (i == lunchReminders.size() - 1) { lunchReminders.add(lunch); break; } } } } } public synchronized void addLunchAttending(Lunch lunch, int index){ lunchesAttending.add(index, lunch); if(lunch.getReminderTime() != null) { if (lunchReminders.size() == 0 ) { lunchReminders.add(lunch); } else { for (int i = 0; i < lunchReminders.size(); i++) { if (lunchReminders.get(i).getReminderTime().after(lunch.getReminderTime())){ lunchReminders.add(i, lunch); break; } if (i == lunchReminders.size() - 1) { lunchReminders.add(lunch); break; } } } } } public synchronized Lunch getNextReminder() { return lunchReminders.get(0); } public synchronized int numLunchReminders() { return lunchReminders.size(); } public synchronized void lunchReminded() { lunchReminders.remove(0); } public void removeLunchInvite(String lunchTitle){ for (int i = 0; i < lunchInvites.size(); i++) { if (lunchTitle.startsWith(lunchInvites.get(i).getTitle())) { lunchInvites.remove(i); break; } } } public void removeLunchesAttending(String lunchTitle){ for (int i = 0; i < lunchesAttending.size(); i++) { if (lunchTitle.startsWith(lunchesAttending.get(i).getTitle())) { lunchesAttending.remove(i); break; } } for (int i = 0; i < lunchReminders.size(); i++) { if (lunchTitle.startsWith(lunchReminders.get(i).getTitle())) { lunchReminders.remove(i); break; } } } public void setLunchInvites(ArrayList<Lunch> lunches) { lunchInvites = lunches; } public void setLunchesAttending(ArrayList<Lunch> lunches) { lunchesAttending = lunches; } public ArrayList<Lunch> getLunchInvites() { return lunchInvites; } public Lunch getLunchInvite(int position) { return lunchInvites.get(position); } public void removeLunchInvite(int position) { lunchInvites.remove(position); } public synchronized ArrayList<Lunch> getLunchesAttending() { return lunchesAttending; } public synchronized int numLunchesAttending() { return lunchesAttending.size(); } public Lunch getLunchAttending(int position) { return lunchesAttending.get(position); } public void removeLunchAttending(int position) { lunchesAttending.remove(position); } public void setFriendListAdapter(FriendListAdapter<Friend> friendListAdapter) { this.friendListAdapter = friendListAdapter; } public FriendListAdapter<Friend> getFriendListAdapter() { return this.friendListAdapter; } }
true
true
public void makeLunches() { if (lunchInvites == null) { Calendar systemTime = Calendar.getInstance(); startTime = (Calendar)systemTime.clone(); Calendar firstLunchTime = (Calendar)systemTime.clone(); firstLunchTime.add(Calendar.DAY_OF_YEAR, 1); firstLunchTime.add(Calendar.MINUTE, 35); ArrayList<Friend> attending = new ArrayList<Friend>(); attending.add(new Friend("Anjali Muralidhar")); attending.add(new Friend("Michael Puncel")); attending.add(new Friend("Pallavi Powale")); lunchInvites = new ArrayList<Lunch>(); lunchesAttending = new ArrayList<Lunch>(); lunchReminders = new ArrayList<Lunch>(); Lunch tbell = new Lunch("Taco Bell"); tbell.setLunchTime(firstLunchTime); tbell.setFriends(attending); tbell.addAcceptedFriend(attending.get(0)); tbell.addAcceptedFriend(attending.get(1)); Lunch cosi = new Lunch("Cosi"); Calendar secondLunchTime = (Calendar)firstLunchTime.clone(); secondLunchTime.add(Calendar.DAY_OF_YEAR, 1); secondLunchTime.add(Calendar.MINUTE, 35); cosi.setLunchTime(secondLunchTime); cosi.setFriends(attending); cosi.addAcceptedFriend(attending.get(2)); cosi.addAcceptedFriend(attending.get(1)); Lunch masa = new Lunch("Masa"); Calendar thirdLunchTime = (Calendar)secondLunchTime.clone(); thirdLunchTime.add(Calendar.MINUTE, 35); thirdLunchTime.add(Calendar.DAY_OF_YEAR, 1); masa.setLunchTime(thirdLunchTime); masa.setFriends(attending); masa.addAcceptedFriend(attending.get(0)); masa.addAcceptedFriend(attending.get(1)); lunchInvites.add(tbell); lunchInvites.add(cosi); lunchInvites.add(masa); Lunch dhaba = new Lunch("Desi Dhaba"); Calendar attendTime = (Calendar)systemTime.clone(); attendTime.add(Calendar.MINUTE, 35); dhaba.setLunchTime(attendTime); dhaba.setFriends(attending); dhaba.addAcceptedFriend(attending.get(0)); dhaba.addAcceptedFriend(attending.get(1)); dhaba.setConfirmationRequested(true); dhaba.setReminderTime(34); Lunch maggianos = new Lunch("Maggiano's"); Calendar attendTime2 = (Calendar)systemTime.clone(); attendTime2.add(Calendar.MINUTE, 36); maggianos.setLunchTime(attendTime2); maggianos.setFriends(attending); maggianos.addAcceptedFriend(attending.get(2)); maggianos.addAcceptedFriend(attending.get(1)); addLunchAttending(dhaba); addLunchAttending(maggianos); Intent intent = new Intent(this, NotificationService.class); startService(intent); fakeInvite = new Lunch("Cinderella's"); attendTime.add(Calendar.DAY_OF_MONTH, 1); fakeInvite.setLunchTime(attendTime); fakeInvite.setFriends(attending); fakeInvite.addAcceptedFriend(attending.get(2)); } }
public void makeLunches() { if (lunchInvites == null) { Calendar systemTime = Calendar.getInstance(); startTime = (Calendar)systemTime.clone(); Calendar firstLunchTime = (Calendar)systemTime.clone(); firstLunchTime.add(Calendar.DAY_OF_YEAR, 1); firstLunchTime.add(Calendar.MINUTE, 35); ArrayList<Friend> attending = new ArrayList<Friend>(); attending.add(new Friend("Anjali Muralidhar")); attending.add(new Friend("Michael Puncel")); attending.add(new Friend("Pallavi Powale")); lunchInvites = new ArrayList<Lunch>(); lunchesAttending = new ArrayList<Lunch>(); lunchReminders = new ArrayList<Lunch>(); Lunch tbell = new Lunch("Taco Bell"); tbell.setLunchTime(firstLunchTime); tbell.setFriends(attending); tbell.addAcceptedFriend(attending.get(0)); tbell.addAcceptedFriend(attending.get(1)); Lunch cosi = new Lunch("Cosi"); Calendar secondLunchTime = (Calendar)firstLunchTime.clone(); secondLunchTime.add(Calendar.DAY_OF_YEAR, 1); secondLunchTime.add(Calendar.MINUTE, 35); cosi.setLunchTime(secondLunchTime); cosi.setFriends(attending); cosi.addAcceptedFriend(attending.get(2)); cosi.addAcceptedFriend(attending.get(1)); Lunch masa = new Lunch("Masa"); Calendar thirdLunchTime = (Calendar)secondLunchTime.clone(); thirdLunchTime.add(Calendar.MINUTE, 35); thirdLunchTime.add(Calendar.DAY_OF_YEAR, 1); masa.setLunchTime(thirdLunchTime); masa.setFriends(attending); masa.addAcceptedFriend(attending.get(0)); masa.addAcceptedFriend(attending.get(1)); lunchInvites.add(tbell); lunchInvites.add(cosi); lunchInvites.add(masa); Lunch dhaba = new Lunch("Desi Dhaba"); Calendar attendTime = (Calendar)systemTime.clone(); attendTime.add(Calendar.MINUTE, 35); dhaba.setLunchTime(attendTime); dhaba.setFriends(attending); dhaba.addAcceptedFriend(attending.get(0)); dhaba.addAcceptedFriend(attending.get(1)); dhaba.setConfirmationRequested(true); dhaba.setReminderTime(34); Lunch maggianos = new Lunch("Maggiano's"); Calendar attendTime2 = (Calendar)systemTime.clone(); attendTime2.add(Calendar.MINUTE, 36); maggianos.setLunchTime(attendTime2); maggianos.setFriends(attending); maggianos.addAcceptedFriend(attending.get(2)); maggianos.addAcceptedFriend(attending.get(1)); addLunchAttending(dhaba); addLunchAttending(maggianos); Intent intent = new Intent(this, NotificationService.class); startService(intent); fakeInvite = new Lunch("Cinderella's"); Calendar fakeTime = (Calendar)attendTime.clone(); fakeTime.add(Calendar.DAY_OF_MONTH, 1); fakeInvite.setLunchTime(attendTime); fakeInvite.setFriends(attending); fakeInvite.addAcceptedFriend(attending.get(2)); } }
diff --git a/mes-plugins/mes-plugins-states/src/main/java/com/qcadoo/mes/states/service/client/StateChangeViewClientValidationUtil.java b/mes-plugins/mes-plugins-states/src/main/java/com/qcadoo/mes/states/service/client/StateChangeViewClientValidationUtil.java index 131cefa1f6..66baa109fc 100644 --- a/mes-plugins/mes-plugins-states/src/main/java/com/qcadoo/mes/states/service/client/StateChangeViewClientValidationUtil.java +++ b/mes-plugins/mes-plugins-states/src/main/java/com/qcadoo/mes/states/service/client/StateChangeViewClientValidationUtil.java @@ -1,105 +1,107 @@ package com.qcadoo.mes.states.service.client; import static com.qcadoo.mes.states.messages.constants.MessageFields.CORRESPOND_FIELD_NAME; import static com.qcadoo.mes.states.messages.constants.MessageType.VALIDATION_ERROR; import static com.qcadoo.mes.states.messages.util.MessagesUtil.convertViewMessageType; import static com.qcadoo.mes.states.messages.util.MessagesUtil.getArgs; import static com.qcadoo.mes.states.messages.util.MessagesUtil.getKey; import static org.apache.commons.lang.StringUtils.join; import static org.springframework.context.i18n.LocaleContextHolder.getLocale; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Predicate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.google.common.collect.Lists; import com.qcadoo.localization.api.TranslationService; import com.qcadoo.mes.states.messages.util.MessagesUtil; import com.qcadoo.mes.states.messages.util.ValidationMessagePredicate; import com.qcadoo.model.api.DataDefinition; import com.qcadoo.model.api.Entity; import com.qcadoo.view.api.ComponentState; import com.qcadoo.view.api.components.FormComponent; @Service public class StateChangeViewClientValidationUtil { @Autowired private TranslationService translationService; private static final Predicate VALIDATION_MESSAGES_PREDICATE = new ValidationMessagePredicate(); public void addValidationErrorMessages(final ComponentState component, final Entity entity, final List<Entity> messages) { if (component instanceof FormComponent) { addValidationErrorsToForm((FormComponent) component, messages); } else { addValidationErrors(component, entity, messages); } } private void addValidationErrorsToForm(final FormComponent form, final List<Entity> messages) { final Entity entity = form.getEntity(); final DataDefinition dataDefinition = entity.getDataDefinition(); CollectionUtils.filter(messages, VALIDATION_MESSAGES_PREDICATE); for (Entity message : messages) { if (MessagesUtil.hasCorrespondField(message)) { final String fieldName = message.getStringField(CORRESPOND_FIELD_NAME); entity.addError(dataDefinition.getField(fieldName), getKey(message), getArgs(message)); } else { entity.addGlobalError(getKey(message), getArgs(message)); } } form.setEntity(entity); } private void addValidationErrors(final ComponentState component, final Entity entity, final List<Entity> messages) { final List<String> errorMessages = Lists.newArrayList(); CollectionUtils.filter(messages, VALIDATION_MESSAGES_PREDICATE); for (Entity message : messages) { if (MessagesUtil.hasCorrespondField(message)) { errorMessages.add(composeTranslatedFieldValidationMessage(entity, message)); } else { errorMessages.add(composeTranslatedGlobalValidationMessage(message)); } } - final StringBuilder sb = new StringBuilder(); - sb.append(translationService.translate("states.messages.change.failure.validationErrors", getLocale(), - join(errorMessages, ' '))); - component.addTranslatedMessage(sb.toString(), convertViewMessageType(VALIDATION_ERROR)); + if (!errorMessages.isEmpty()) { + final StringBuilder sb = new StringBuilder(); + sb.append(translationService.translate("states.messages.change.failure.validationErrors", getLocale(), + join(errorMessages, ' '))); + component.addTranslatedMessage(sb.toString(), convertViewMessageType(VALIDATION_ERROR)); + } } private String composeTranslatedGlobalValidationMessage(final Entity globalMessage) { final StringBuilder sb = new StringBuilder(); sb.append("<li>"); sb.append(translationService.translate(getKey(globalMessage), getLocale(), getArgs(globalMessage))); sb.append("</li>"); return sb.toString(); } private String composeTranslatedFieldValidationMessage(final Entity entity, final Entity fieldMessage) { final StringBuilder sb = new StringBuilder(); sb.append("<li>"); sb.append(getTranslatedFieldName(entity, fieldMessage.getStringField(CORRESPOND_FIELD_NAME))); sb.append(": "); sb.append(translationService.translate(getKey(fieldMessage), getLocale(), getArgs(fieldMessage))); sb.append("</li>"); return sb.toString(); } private String getTranslatedFieldName(final Entity entity, final String fieldName) { final StringBuilder sb = new StringBuilder(); sb.append(entity.getDataDefinition().getPluginIdentifier()); sb.append('.'); sb.append(entity.getDataDefinition().getName()); sb.append('.'); sb.append(fieldName); sb.append(".label"); return translationService.translate(sb.toString(), getLocale()); } }
true
true
private void addValidationErrors(final ComponentState component, final Entity entity, final List<Entity> messages) { final List<String> errorMessages = Lists.newArrayList(); CollectionUtils.filter(messages, VALIDATION_MESSAGES_PREDICATE); for (Entity message : messages) { if (MessagesUtil.hasCorrespondField(message)) { errorMessages.add(composeTranslatedFieldValidationMessage(entity, message)); } else { errorMessages.add(composeTranslatedGlobalValidationMessage(message)); } } final StringBuilder sb = new StringBuilder(); sb.append(translationService.translate("states.messages.change.failure.validationErrors", getLocale(), join(errorMessages, ' '))); component.addTranslatedMessage(sb.toString(), convertViewMessageType(VALIDATION_ERROR)); }
private void addValidationErrors(final ComponentState component, final Entity entity, final List<Entity> messages) { final List<String> errorMessages = Lists.newArrayList(); CollectionUtils.filter(messages, VALIDATION_MESSAGES_PREDICATE); for (Entity message : messages) { if (MessagesUtil.hasCorrespondField(message)) { errorMessages.add(composeTranslatedFieldValidationMessage(entity, message)); } else { errorMessages.add(composeTranslatedGlobalValidationMessage(message)); } } if (!errorMessages.isEmpty()) { final StringBuilder sb = new StringBuilder(); sb.append(translationService.translate("states.messages.change.failure.validationErrors", getLocale(), join(errorMessages, ' '))); component.addTranslatedMessage(sb.toString(), convertViewMessageType(VALIDATION_ERROR)); } }
diff --git a/webapp/WEB-INF/classes/org/makumba/parade/access/DatabaseLogServlet.java b/webapp/WEB-INF/classes/org/makumba/parade/access/DatabaseLogServlet.java index 24b8b4c..d1927aa 100644 --- a/webapp/WEB-INF/classes/org/makumba/parade/access/DatabaseLogServlet.java +++ b/webapp/WEB-INF/classes/org/makumba/parade/access/DatabaseLogServlet.java @@ -1,230 +1,230 @@ package org.makumba.parade.access; import java.io.IOException; import java.util.Date; import java.util.logging.LogRecord; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.spi.LoggingEvent; import org.hibernate.Session; import org.hibernate.Transaction; import org.makumba.parade.init.InitServlet; import org.makumba.parade.model.ActionLog; import org.makumba.parade.model.Log; import org.makumba.parade.tools.PerThreadPrintStreamLogRecord; import org.makumba.parade.tools.TriggerFilter; import org.makumba.parade.view.TickerTapeData; import org.makumba.parade.view.TickerTapeServlet; /** * This servlet makes it possible to log events from various sources into the database. * It persists two kinds of logs: * <ul> * <li>ActionLogs, generated at each access</li> * <li>Logs, which are representing one log "line" and link to the ActionLog which led to their generation</li> * </ul> * * TODO improve filtering * * @author Manuel Gay * */ public class DatabaseLogServlet extends HttpServlet { public void init(ServletConfig conf) { } public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException { // when we start tomcat we are not ready yet to log // we first need a Hibernate SessionFactory to be initalised // this happens only after the Initservlet was loaded req.removeAttribute("org.makumba.parade.servletSuccess"); if(InitServlet.getSessionFactory() == null) return; req.setAttribute("org.makumba.parade.servletSuccess", true); // retrieve the record guy Object record = req.getAttribute("org.makumba.parade.servletParam"); if (record == null) return; // open a new session, which we need to perform extraction Session s = null; try { s = InitServlet.getSessionFactory().openSession(); if(record instanceof ActionLogDTO) { handleActionLog(req, record, s); } else { handleLog(req, record, s); } } finally { // close the session in any case s.close(); } } private void handleActionLog(HttpServletRequest req, Object record, Session s) { ActionLogDTO log = (ActionLogDTO) record; // first check if this should be logged at all if(!shouldLog(log)) return; // filter the log, generate additional information and give some meaning filterLog(log); //let's see if we have already someone. if not, we create one Transaction tx = s.beginTransaction(); ActionLog actionLog = null; if(log.getId() == null) { actionLog = new ActionLog(); } else { actionLog = (ActionLog) s.get(ActionLog.class, log.getId()); } log.populate(actionLog); s.saveOrUpdate(actionLog); tx.commit(); //if we didn't have a brand new actionLog (meaning, a log with some info) //we add the populated actionLog as an event to the tickertape //TODO refactor me if(log.getId() != null) { String row = (log.getParadecontext()==null || log.getParadecontext().equals("null"))?((log.getContext()==null || log.getContext().equals("null"))?"parade2":log.getContext()):log.getParadecontext(); String actionText = ""; if(log.getAction() != null && !log.getAction().equals("null")) actionText = "user "+log.getUser()+" in row "+ row + " did action: "+log.getAction(); TickerTapeData data = new TickerTapeData(actionText, "", log.getDate().toString()); TickerTapeServlet.addItem(data); } // finally we also need to update the ActionLog in the thread log.setId(actionLog.getId()); TriggerFilter.actionLog.set(log); } /** * Simple filter that does some "cosmetics" on the log * @param log the original log to be altered */ private void filterLog(ActionLogDTO log) { String queryString = log.getQueryString(); String uri = log.getUrl(); if(uri == null) uri = ""; if(queryString != null) { // let's analyse a bit this string if(queryString.indexOf("context=")>0) { String context = queryString.substring(queryString.indexOf("context=") +8); if(context.indexOf("&") >0) context = context.substring(0, context.indexOf("&")); log.setParadecontext(context); } if(uri.indexOf("Ant") > 0) { log.setAction("Ant action"); } if(uri.indexOf("Webapp") > 0) { log.setAction("Webapp action"); } if(uri.indexOf("Cvs") > 0) { log.setAction("Cvs"); } } } /** * Checks whether this access should be logged or not * @param log the DTO containing the log entry * @return <code>true</code> if this is worth logging, <code>false</code> otherwise */ private boolean shouldLog(ActionLogDTO log) { if(log.getUrl() != null && ( !log.getUrl().endsWith(".ico") || !log.getUrl().endsWith(".css") || !log.getUrl().endsWith(".gif") || !log.getUrl().endsWith(".js") || log.getUrl().equals("/servlet/ticker")) || (log.getOrigin() != null && log.getOrigin().equals("tomcat"))) { return false; } return true; } private void handleLog(HttpServletRequest req, Object record, Session s) { // extract useful information from the record Log log = new Log(); ActionLog actionLog = retrieveActionLog(s); log.setActionLog(actionLog); // this is a java.util.logging.LogRecord if (record instanceof LogRecord) { LogRecord logrecord = (LogRecord) record; log.setDate(new Date(logrecord.getMillis())); log.setLevel(logrecord.getLevel().getName()); log.setMessage(logrecord.getMessage()); log.setOrigin("java.util.Logging"); //log.setThrowable(logrecord.getThrown()); } else if(record instanceof LoggingEvent) { LoggingEvent logevent = (LoggingEvent) record; log.setOrigin("log4j"); - log.setDate(new Date(logevent.getStartTime())); + log.setDate(new Date(logevent.timeStamp)); log.setLevel(logevent.getLevel().toString()); log.setMessage(logevent.getRenderedMessage()); //if(logevent.getThrowableInformation() != null) //log.setThrowable(logevent.getThrowableInformation().getThrowable()); //else //log.setThrowable(null); } else if(record instanceof PerThreadPrintStreamLogRecord) { PerThreadPrintStreamLogRecord pRecord = (PerThreadPrintStreamLogRecord)record; log.setDate(pRecord.getDate()); log.setOrigin("stdout"); log.setLevel("INFO"); log.setMessage(pRecord.getMessage()); //log.setThrowable(null); } else if(record instanceof Object[]) { Object[] rec = (Object[])record; log.setDate((Date)rec[0]); log.setOrigin("TriggerFilter"); log.setLevel("INFO"); log.setMessage((String)rec[1]); } Transaction tx = s.beginTransaction(); // write the guy to the db s.saveOrUpdate(log); tx.commit(); } private ActionLog retrieveActionLog(Session s) { ActionLogDTO actionLogDTO = TriggerFilter.actionLog.get(); ActionLog actionLog = new ActionLog(); actionLogDTO.populate(actionLog); // if the actionLog is there but not persisted, we persist it first if(actionLog.getId() == null) { Transaction tx = s.beginTransaction(); s.save(actionLog); tx.commit(); actionLogDTO.setId(actionLog.getId()); TriggerFilter.actionLog.set(actionLogDTO); } else { actionLog = (ActionLog) s.get(ActionLog.class, actionLogDTO.getId()); } return actionLog; } }
true
true
private void handleLog(HttpServletRequest req, Object record, Session s) { // extract useful information from the record Log log = new Log(); ActionLog actionLog = retrieveActionLog(s); log.setActionLog(actionLog); // this is a java.util.logging.LogRecord if (record instanceof LogRecord) { LogRecord logrecord = (LogRecord) record; log.setDate(new Date(logrecord.getMillis())); log.setLevel(logrecord.getLevel().getName()); log.setMessage(logrecord.getMessage()); log.setOrigin("java.util.Logging"); //log.setThrowable(logrecord.getThrown()); } else if(record instanceof LoggingEvent) { LoggingEvent logevent = (LoggingEvent) record; log.setOrigin("log4j"); log.setDate(new Date(logevent.getStartTime())); log.setLevel(logevent.getLevel().toString()); log.setMessage(logevent.getRenderedMessage()); //if(logevent.getThrowableInformation() != null) //log.setThrowable(logevent.getThrowableInformation().getThrowable()); //else //log.setThrowable(null); } else if(record instanceof PerThreadPrintStreamLogRecord) { PerThreadPrintStreamLogRecord pRecord = (PerThreadPrintStreamLogRecord)record; log.setDate(pRecord.getDate()); log.setOrigin("stdout"); log.setLevel("INFO"); log.setMessage(pRecord.getMessage()); //log.setThrowable(null); } else if(record instanceof Object[]) { Object[] rec = (Object[])record; log.setDate((Date)rec[0]); log.setOrigin("TriggerFilter"); log.setLevel("INFO"); log.setMessage((String)rec[1]); } Transaction tx = s.beginTransaction(); // write the guy to the db s.saveOrUpdate(log); tx.commit(); }
private void handleLog(HttpServletRequest req, Object record, Session s) { // extract useful information from the record Log log = new Log(); ActionLog actionLog = retrieveActionLog(s); log.setActionLog(actionLog); // this is a java.util.logging.LogRecord if (record instanceof LogRecord) { LogRecord logrecord = (LogRecord) record; log.setDate(new Date(logrecord.getMillis())); log.setLevel(logrecord.getLevel().getName()); log.setMessage(logrecord.getMessage()); log.setOrigin("java.util.Logging"); //log.setThrowable(logrecord.getThrown()); } else if(record instanceof LoggingEvent) { LoggingEvent logevent = (LoggingEvent) record; log.setOrigin("log4j"); log.setDate(new Date(logevent.timeStamp)); log.setLevel(logevent.getLevel().toString()); log.setMessage(logevent.getRenderedMessage()); //if(logevent.getThrowableInformation() != null) //log.setThrowable(logevent.getThrowableInformation().getThrowable()); //else //log.setThrowable(null); } else if(record instanceof PerThreadPrintStreamLogRecord) { PerThreadPrintStreamLogRecord pRecord = (PerThreadPrintStreamLogRecord)record; log.setDate(pRecord.getDate()); log.setOrigin("stdout"); log.setLevel("INFO"); log.setMessage(pRecord.getMessage()); //log.setThrowable(null); } else if(record instanceof Object[]) { Object[] rec = (Object[])record; log.setDate((Date)rec[0]); log.setOrigin("TriggerFilter"); log.setLevel("INFO"); log.setMessage((String)rec[1]); } Transaction tx = s.beginTransaction(); // write the guy to the db s.saveOrUpdate(log); tx.commit(); }
diff --git a/src/test/java/no/uis/service/fsimport/ValidatorTest.java b/src/test/java/no/uis/service/fsimport/ValidatorTest.java index ff8b4ef..dcb42aa 100644 --- a/src/test/java/no/uis/service/fsimport/ValidatorTest.java +++ b/src/test/java/no/uis/service/fsimport/ValidatorTest.java @@ -1,100 +1,105 @@ package no.uis.service.fsimport; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import no.uis.service.fsimport.ValidationErrorHandler.InfoType; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.junit.Test; public class ValidatorTest { /** * The test is disabled by default. It can be enabled by setting the system properties {@code studinfo.year} and {@code studinfo.semester}. The year * is set with the system property {@code studinfo-validate.year}. The semester is set with the system property {@code studinfo-validate.semester}. */ @Test public void validateAll() throws Exception { final String sYear = System.getProperty("studinfo.year"); - final String semester = System.getProperty("studinfo.semester"); + String semester = System.getProperty("studinfo.semester"); final String sInfoType = System.getProperty("studinfo.type"); final String sLang = System.getProperty("studinfo.lang"); System.out.println("Year: " + sYear); System.out.println("Semester: " + semester); if (sYear != null && semester != null) { int year = Integer.parseInt(sYear); + if (semester.startsWith("V")) { + semester = "VÅR"; + } else if (semester.startsWith("H")) { + semester = "HØST"; + } if (!semester.equals("VÅR") && !semester.equals("HØST")) { throw new IllegalArgumentException(semester); } InfoType[] infoTypes = (sInfoType != null ? new InfoType[] {InfoType.valueOf(sInfoType)} : InfoType.values()); String[] langs = (sLang != null ? sLang.split(",") : new String[] {"B", "E", "N"}); StudinfoValidator sinfo = new StudinfoValidator(); // final List<String> messages = sinfo.validateAll(year, semester, infoTypes, langs); final List<String> messages = Arrays.asList(langs); assertThat(new ListWrapper(messages), is(emptyList())); } else { assertTrue(true); } } private static class IsEmptyCollection extends BaseMatcher<Collection<?>> { @Override public boolean matches(Object item) { return (item != null && ((Collection<?>)item).isEmpty()); } @Override public void describeTo(Description description) { description.appendText("empty"); } } private static Matcher<Collection<?>> emptyList() { return new IsEmptyCollection(); } /** * This class overrides the {@link AbstractCollection#toString()} method so that the matcher puts every message on a line. */ @SuppressWarnings("serial") private static class ListWrapper extends ArrayList<String> { public ListWrapper(List<String> wrappee) { super(wrappee); } @Override public String toString() { Iterator<?> i = iterator(); if (!i.hasNext()) { return "[]"; } StringBuilder sb = new StringBuilder(); sb.append("[\n"); for (;;) { Object e = i.next(); sb.append(e == this ? "(this Collection)" : e); if (!i.hasNext()) { return sb.append("\n]").toString(); } sb.append(", \n"); } } } }
false
true
public void validateAll() throws Exception { final String sYear = System.getProperty("studinfo.year"); final String semester = System.getProperty("studinfo.semester"); final String sInfoType = System.getProperty("studinfo.type"); final String sLang = System.getProperty("studinfo.lang"); System.out.println("Year: " + sYear); System.out.println("Semester: " + semester); if (sYear != null && semester != null) { int year = Integer.parseInt(sYear); if (!semester.equals("VÅR") && !semester.equals("HØST")) { throw new IllegalArgumentException(semester); } InfoType[] infoTypes = (sInfoType != null ? new InfoType[] {InfoType.valueOf(sInfoType)} : InfoType.values()); String[] langs = (sLang != null ? sLang.split(",") : new String[] {"B", "E", "N"}); StudinfoValidator sinfo = new StudinfoValidator(); // final List<String> messages = sinfo.validateAll(year, semester, infoTypes, langs); final List<String> messages = Arrays.asList(langs); assertThat(new ListWrapper(messages), is(emptyList())); } else {
public void validateAll() throws Exception { final String sYear = System.getProperty("studinfo.year"); String semester = System.getProperty("studinfo.semester"); final String sInfoType = System.getProperty("studinfo.type"); final String sLang = System.getProperty("studinfo.lang"); System.out.println("Year: " + sYear); System.out.println("Semester: " + semester); if (sYear != null && semester != null) { int year = Integer.parseInt(sYear); if (semester.startsWith("V")) { semester = "VÅR"; } else if (semester.startsWith("H")) { semester = "HØST"; } if (!semester.equals("VÅR") && !semester.equals("HØST")) { throw new IllegalArgumentException(semester); } InfoType[] infoTypes = (sInfoType != null ? new InfoType[] {InfoType.valueOf(sInfoType)} : InfoType.values()); String[] langs = (sLang != null ? sLang.split(",") : new String[] {"B", "E", "N"}); StudinfoValidator sinfo = new StudinfoValidator(); // final List<String> messages = sinfo.validateAll(year, semester, infoTypes, langs); final List<String> messages = Arrays.asList(langs); assertThat(new ListWrapper(messages), is(emptyList())); } else {
diff --git a/main/src/com/google/refine/importers/TsvCsvImporter.java b/main/src/com/google/refine/importers/TsvCsvImporter.java index a4599cfb..0568ab4a 100644 --- a/main/src/com/google/refine/importers/TsvCsvImporter.java +++ b/main/src/com/google/refine/importers/TsvCsvImporter.java @@ -1,206 +1,206 @@ package com.google.refine.importers; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.Reader; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.commons.lang.StringUtils; import au.com.bytecode.opencsv.CSVParser; import com.google.refine.ProjectMetadata; import com.google.refine.expr.ExpressionUtils; import com.google.refine.model.Cell; import com.google.refine.model.Project; import com.google.refine.model.Row; public class TsvCsvImporter implements ReaderImporter,StreamImporter { @Override public void read(Reader reader, Project project, ProjectMetadata metadata, Properties options) throws ImportException { boolean splitIntoColumns = ImporterUtilities.getBooleanOption("split-into-columns", options, true); String sep = options.getProperty("separator"); // auto-detect if not present int ignoreLines = ImporterUtilities.getIntegerOption("ignore", options, -1); int headerLines = ImporterUtilities.getIntegerOption("header-lines", options, 1); int limit = ImporterUtilities.getIntegerOption("limit",options,-1); int skip = ImporterUtilities.getIntegerOption("skip",options,0); boolean guessValueType = ImporterUtilities.getBooleanOption("guess-value-type", options, true); boolean ignoreQuotes = ImporterUtilities.getBooleanOption("ignore-quotes", options, false); LineNumberReader lnReader = new LineNumberReader(reader); try { read(lnReader, project, sep, limit, skip, ignoreLines, headerLines, guessValueType, splitIntoColumns, ignoreQuotes ); } catch (IOException e) { throw new ImportException("Import failed",e); } } /** * * @param lnReader * LineNumberReader used to read file or string contents * @param project * The project into which the parsed data will be added * @param sep * The character used to denote different the break between data points * @param limit * The maximum number of rows of data to import * @param skip * The number of initial data rows to skip * @param ignoreLines * The number of initial lines within the data source which should be ignored entirely * @param headerLines * The number of lines in the data source which describe each column * @param guessValueType * Whether the parser should try and guess the type of the value being parsed * @param splitIntoColumns * Whether the parser should try and split the data source into columns * @param ignoreQuotes * Quotation marks are ignored, and all separators and newlines treated as such regardless of whether they are within quoted values * @throws IOException */ public void read(LineNumberReader lnReader, Project project, String sep, int limit, int skip, int ignoreLines, int headerLines, boolean guessValueType, boolean splitIntoColumns, boolean ignoreQuotes ) throws IOException{ CSVParser parser = (sep != null && sep.length() > 0 && splitIntoColumns) ? new CSVParser(sep.toCharArray()[0],//HACK changing string to char - won't work for multi-char separators. CSVParser.DEFAULT_QUOTE_CHARACTER, - CSVParser.DEFAULT_ESCAPE_CHARACTER, + (char) 0, // escape character CSVParser.DEFAULT_STRICT_QUOTES, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE, ignoreQuotes) : null; List<String> columnNames = new ArrayList<String>(); String line = null; int rowsWithData = 0; while ((line = lnReader.readLine()) != null) { if (ignoreLines > 0) { ignoreLines--; continue; } else if (StringUtils.isBlank(line)) { continue; } //guess separator if (parser == null) { int tab = line.indexOf('\t'); if (tab >= 0) { parser = new CSVParser('\t', CSVParser.DEFAULT_QUOTE_CHARACTER, - CSVParser.DEFAULT_ESCAPE_CHARACTER, + (char) 0, // escape character CSVParser.DEFAULT_STRICT_QUOTES, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE, ignoreQuotes); } else { parser = new CSVParser(',', CSVParser.DEFAULT_QUOTE_CHARACTER, - CSVParser.DEFAULT_ESCAPE_CHARACTER, + (char) 0, // escape character CSVParser.DEFAULT_STRICT_QUOTES, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE, ignoreQuotes); } } if (headerLines > 0) { //column headers headerLines--; ArrayList<String> cells = getCells(line, parser, lnReader, splitIntoColumns); for (int c = 0; c < cells.size(); c++) { String cell = cells.get(c).trim(); //add column even if cell is blank ImporterUtilities.appendColumnName(columnNames, c, cell); } } else { //data Row row = new Row(columnNames.size()); ArrayList<String> cells = getCells(line, parser, lnReader, splitIntoColumns); if( cells != null && cells.size() > 0 ) rowsWithData++; if (skip <=0 || rowsWithData > skip){ //add parsed data to row for(String s : cells){ s = s.trim(); if (ExpressionUtils.isNonBlankData(s)) { Serializable value = guessValueType ? ImporterUtilities.parseCellValue(s) : s; row.cells.add(new Cell(value, null)); }else{ row.cells.add(null); } } project.rows.add(row); project.columnModel.setMaxCellIndex(row.cells.size()); ImporterUtilities.ensureColumnsInRowExist(columnNames, row); if (limit > 0 && project.rows.size() >= limit) { break; } } } } ImporterUtilities.setupColumns(project, columnNames); } protected ArrayList<String> getCells(String line, CSVParser parser, LineNumberReader lnReader, boolean splitIntoColumns) throws IOException{ ArrayList<String> cells = new ArrayList<String>(); if(splitIntoColumns){ String[] tokens = parser.parseLineMulti(line); for(String s : tokens){ cells.add(s); } while(parser.isPending()){ tokens = parser.parseLineMulti(lnReader.readLine()); for(String s : tokens){ cells.add(s); } } }else{ cells.add(line); } return cells; } @Override public void read(InputStream inputStream, Project project, ProjectMetadata metadata, Properties options) throws ImportException { read(new InputStreamReader(inputStream), project, metadata, options); } @Override public boolean canImportData(String contentType, String fileName) { if (contentType != null) { contentType = contentType.toLowerCase().trim(); return "text/plain".equals(contentType) || "text/csv".equals(contentType) || "text/x-csv".equals(contentType) || "text/tab-separated-value".equals(contentType); } else if (fileName != null) { fileName = fileName.toLowerCase(); if (fileName.endsWith(".tsv")) { return true; }else if (fileName.endsWith(".csv")){ return true; } } return false; } }
false
true
public void read(LineNumberReader lnReader, Project project, String sep, int limit, int skip, int ignoreLines, int headerLines, boolean guessValueType, boolean splitIntoColumns, boolean ignoreQuotes ) throws IOException{ CSVParser parser = (sep != null && sep.length() > 0 && splitIntoColumns) ? new CSVParser(sep.toCharArray()[0],//HACK changing string to char - won't work for multi-char separators. CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER, CSVParser.DEFAULT_STRICT_QUOTES, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE, ignoreQuotes) : null; List<String> columnNames = new ArrayList<String>(); String line = null; int rowsWithData = 0; while ((line = lnReader.readLine()) != null) { if (ignoreLines > 0) { ignoreLines--; continue; } else if (StringUtils.isBlank(line)) { continue; } //guess separator if (parser == null) { int tab = line.indexOf('\t'); if (tab >= 0) { parser = new CSVParser('\t', CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER, CSVParser.DEFAULT_STRICT_QUOTES, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE, ignoreQuotes); } else { parser = new CSVParser(',', CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER, CSVParser.DEFAULT_STRICT_QUOTES, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE, ignoreQuotes); } } if (headerLines > 0) { //column headers headerLines--; ArrayList<String> cells = getCells(line, parser, lnReader, splitIntoColumns); for (int c = 0; c < cells.size(); c++) { String cell = cells.get(c).trim(); //add column even if cell is blank ImporterUtilities.appendColumnName(columnNames, c, cell); } } else { //data Row row = new Row(columnNames.size()); ArrayList<String> cells = getCells(line, parser, lnReader, splitIntoColumns); if( cells != null && cells.size() > 0 ) rowsWithData++; if (skip <=0 || rowsWithData > skip){ //add parsed data to row for(String s : cells){ s = s.trim(); if (ExpressionUtils.isNonBlankData(s)) { Serializable value = guessValueType ? ImporterUtilities.parseCellValue(s) : s; row.cells.add(new Cell(value, null)); }else{ row.cells.add(null); } } project.rows.add(row); project.columnModel.setMaxCellIndex(row.cells.size()); ImporterUtilities.ensureColumnsInRowExist(columnNames, row); if (limit > 0 && project.rows.size() >= limit) { break; } } } } ImporterUtilities.setupColumns(project, columnNames); }
public void read(LineNumberReader lnReader, Project project, String sep, int limit, int skip, int ignoreLines, int headerLines, boolean guessValueType, boolean splitIntoColumns, boolean ignoreQuotes ) throws IOException{ CSVParser parser = (sep != null && sep.length() > 0 && splitIntoColumns) ? new CSVParser(sep.toCharArray()[0],//HACK changing string to char - won't work for multi-char separators. CSVParser.DEFAULT_QUOTE_CHARACTER, (char) 0, // escape character CSVParser.DEFAULT_STRICT_QUOTES, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE, ignoreQuotes) : null; List<String> columnNames = new ArrayList<String>(); String line = null; int rowsWithData = 0; while ((line = lnReader.readLine()) != null) { if (ignoreLines > 0) { ignoreLines--; continue; } else if (StringUtils.isBlank(line)) { continue; } //guess separator if (parser == null) { int tab = line.indexOf('\t'); if (tab >= 0) { parser = new CSVParser('\t', CSVParser.DEFAULT_QUOTE_CHARACTER, (char) 0, // escape character CSVParser.DEFAULT_STRICT_QUOTES, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE, ignoreQuotes); } else { parser = new CSVParser(',', CSVParser.DEFAULT_QUOTE_CHARACTER, (char) 0, // escape character CSVParser.DEFAULT_STRICT_QUOTES, CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE, ignoreQuotes); } } if (headerLines > 0) { //column headers headerLines--; ArrayList<String> cells = getCells(line, parser, lnReader, splitIntoColumns); for (int c = 0; c < cells.size(); c++) { String cell = cells.get(c).trim(); //add column even if cell is blank ImporterUtilities.appendColumnName(columnNames, c, cell); } } else { //data Row row = new Row(columnNames.size()); ArrayList<String> cells = getCells(line, parser, lnReader, splitIntoColumns); if( cells != null && cells.size() > 0 ) rowsWithData++; if (skip <=0 || rowsWithData > skip){ //add parsed data to row for(String s : cells){ s = s.trim(); if (ExpressionUtils.isNonBlankData(s)) { Serializable value = guessValueType ? ImporterUtilities.parseCellValue(s) : s; row.cells.add(new Cell(value, null)); }else{ row.cells.add(null); } } project.rows.add(row); project.columnModel.setMaxCellIndex(row.cells.size()); ImporterUtilities.ensureColumnsInRowExist(columnNames, row); if (limit > 0 && project.rows.size() >= limit) { break; } } } } ImporterUtilities.setupColumns(project, columnNames); }
diff --git a/acteur/src/main/java/com/mastfrog/acteur/server/UpstreamHandlerImpl.java b/acteur/src/main/java/com/mastfrog/acteur/server/UpstreamHandlerImpl.java index 6a33164..b623696 100644 --- a/acteur/src/main/java/com/mastfrog/acteur/server/UpstreamHandlerImpl.java +++ b/acteur/src/main/java/com/mastfrog/acteur/server/UpstreamHandlerImpl.java @@ -1,123 +1,119 @@ /* * The MIT License * * Copyright 2013 Tim Boudreau. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.mastfrog.acteur.server; import com.fasterxml.jackson.databind.ObjectMapper; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import com.google.inject.Inject; import com.google.inject.name.Named; import com.mastfrog.acteur.Application; import static com.mastfrog.acteur.server.ServerModule.DECODE_REAL_IP; import com.mastfrog.settings.Settings; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpResponse; import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpVersion.*; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import java.net.InetSocketAddress; import java.net.SocketAddress; /** * * @author Tim Boudreau */ //@ChannelHandler.Sharable //@Singleton final class UpstreamHandlerImpl extends ChannelInboundHandlerAdapter { private final Application application; private final PathFactory paths; @Inject(optional = true) @Named("neverKeepAlive") private boolean neverKeepAlive; private @Inject(optional = true) @Named("aggregateChunks") boolean aggregateChunks = PipelineFactoryImpl.DEFAULT_AGGREGATE_CHUNKS; private final ObjectMapper mapper; private final boolean decodeRealIP; @Inject private UnknownNetworkEventHandler uneh; @Inject UpstreamHandlerImpl(Application application, PathFactory paths, ObjectMapper mapper, Settings settings) { this.application = application; this.paths = paths; this.mapper = mapper; decodeRealIP = settings.getBoolean(DECODE_REAL_IP, true); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { application.internalOnError(cause); } public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - // HttpContent$2 - ? - if (msg instanceof FullHttpRequest) { - ((FullHttpRequest) msg).retain(); - } if (msg instanceof HttpRequest) { final HttpRequest request = (HttpRequest) msg; if (!aggregateChunks && HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx); } SocketAddress addr = ctx.channel().remoteAddress(); if (decodeRealIP) { String hdr = request.headers().get("X-Real-IP"); if (hdr == null) { hdr = request.headers().get("X-Forwarded-For"); } if (hdr != null) { addr = new InetSocketAddress(hdr, addr instanceof InetSocketAddress ? ((InetSocketAddress) addr).getPort() : 80); } } EventImpl evt = new EventImpl(request, addr, ctx.channel(), paths, mapper); evt.setNeverKeepAlive(neverKeepAlive); application.onEvent(evt, ctx.channel()); } else if (msg instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) msg; SocketAddress addr = (SocketAddress) ctx.channel().remoteAddress(); // XXX - any way to decode real IP? WebSocketEvent wsEvent = new WebSocketEvent(frame, ctx.channel(), addr, mapper); application.onEvent(wsEvent, ctx.channel()); } else { if (uneh != null) { uneh.channelRead(ctx, msg); } } } private static void send100Continue(ChannelHandlerContext ctx) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, CONTINUE); ctx.write(response); } }
true
true
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // HttpContent$2 - ? if (msg instanceof FullHttpRequest) { ((FullHttpRequest) msg).retain(); } if (msg instanceof HttpRequest) { final HttpRequest request = (HttpRequest) msg; if (!aggregateChunks && HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx); } SocketAddress addr = ctx.channel().remoteAddress(); if (decodeRealIP) { String hdr = request.headers().get("X-Real-IP"); if (hdr == null) { hdr = request.headers().get("X-Forwarded-For"); } if (hdr != null) { addr = new InetSocketAddress(hdr, addr instanceof InetSocketAddress ? ((InetSocketAddress) addr).getPort() : 80); } } EventImpl evt = new EventImpl(request, addr, ctx.channel(), paths, mapper); evt.setNeverKeepAlive(neverKeepAlive); application.onEvent(evt, ctx.channel()); } else if (msg instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) msg; SocketAddress addr = (SocketAddress) ctx.channel().remoteAddress(); // XXX - any way to decode real IP? WebSocketEvent wsEvent = new WebSocketEvent(frame, ctx.channel(), addr, mapper); application.onEvent(wsEvent, ctx.channel()); } else { if (uneh != null) { uneh.channelRead(ctx, msg); } } }
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { final HttpRequest request = (HttpRequest) msg; if (!aggregateChunks && HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx); } SocketAddress addr = ctx.channel().remoteAddress(); if (decodeRealIP) { String hdr = request.headers().get("X-Real-IP"); if (hdr == null) { hdr = request.headers().get("X-Forwarded-For"); } if (hdr != null) { addr = new InetSocketAddress(hdr, addr instanceof InetSocketAddress ? ((InetSocketAddress) addr).getPort() : 80); } } EventImpl evt = new EventImpl(request, addr, ctx.channel(), paths, mapper); evt.setNeverKeepAlive(neverKeepAlive); application.onEvent(evt, ctx.channel()); } else if (msg instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) msg; SocketAddress addr = (SocketAddress) ctx.channel().remoteAddress(); // XXX - any way to decode real IP? WebSocketEvent wsEvent = new WebSocketEvent(frame, ctx.channel(), addr, mapper); application.onEvent(wsEvent, ctx.channel()); } else { if (uneh != null) { uneh.channelRead(ctx, msg); } } }
diff --git a/src/com/android/calendar/EventInfoFragment.java b/src/com/android/calendar/EventInfoFragment.java index c96789b7..25288951 100644 --- a/src/com/android/calendar/EventInfoFragment.java +++ b/src/com/android/calendar/EventInfoFragment.java @@ -1,1254 +1,1256 @@ /* * 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.calendar; import com.android.calendar.CalendarController.EventType; import com.android.calendar.event.EditEventHelper; import com.android.calendar.event.EventViewUtils; import android.app.Activity; import android.app.Fragment; import android.content.ActivityNotFoundException; import android.content.AsyncQueryHandler; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.OperationApplicationException; import android.content.SharedPreferences; import android.content.res.Resources; import android.database.Cursor; import android.database.MatrixCursor; import android.graphics.PorterDuff; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.os.RemoteException; import android.pim.EventRecurrence; import android.provider.ContactsContract; import android.provider.Calendar.Attendees; import android.provider.Calendar.Calendars; import android.provider.Calendar.Events; import android.provider.Calendar.Reminders; import android.provider.ContactsContract.CommonDataKinds; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Intents; import android.provider.ContactsContract.Presence; import android.provider.ContactsContract.QuickContact; import android.provider.ContactsContract.CommonDataKinds.Email; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.text.format.Time; import android.text.util.Linkify; import android.text.util.Rfc822Token; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.QuickContactBadge; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.TimeZone; import java.util.regex.Pattern; public class EventInfoFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemSelectedListener { public static final boolean DEBUG = true; public static final String TAG = "EventInfoActivity"; private static final String BUNDLE_KEY_EVENT_ID = "key_event_id"; private static final String BUNDLE_KEY_START_MILLIS = "key_start_millis"; private static final String BUNDLE_KEY_END_MILLIS = "key_end_millis"; private static final int MAX_REMINDERS = 5; /** * These are the corresponding indices into the array of strings * "R.array.change_response_labels" in the resource file. */ static final int UPDATE_SINGLE = 0; static final int UPDATE_ALL = 1; // Query tokens for QueryHandler private static final int TOKEN_QUERY_EVENT = 0; private static final int TOKEN_QUERY_CALENDARS = 1; private static final int TOKEN_QUERY_ATTENDEES = 2; private static final int TOKEN_QUERY_REMINDERS = 3; private static final int TOKEN_QUERY_DUPLICATE_CALENDARS = 4; private static final String[] EVENT_PROJECTION = new String[] { Events._ID, // 0 do not remove; used in DeleteEventHelper Events.TITLE, // 1 do not remove; used in DeleteEventHelper Events.RRULE, // 2 do not remove; used in DeleteEventHelper Events.ALL_DAY, // 3 do not remove; used in DeleteEventHelper Events.CALENDAR_ID, // 4 do not remove; used in DeleteEventHelper Events.DTSTART, // 5 do not remove; used in DeleteEventHelper Events._SYNC_ID, // 6 do not remove; used in DeleteEventHelper Events.EVENT_TIMEZONE, // 7 do not remove; used in DeleteEventHelper Events.DESCRIPTION, // 8 Events.EVENT_LOCATION, // 9 Events.HAS_ALARM, // 10 Calendars.ACCESS_LEVEL, // 11 Calendars.COLOR, // 12 Events.HAS_ATTENDEE_DATA, // 13 Events.GUESTS_CAN_MODIFY, // 14 // TODO Events.GUESTS_CAN_INVITE_OTHERS has not been implemented in calendar provider Events.GUESTS_CAN_INVITE_OTHERS, // 15 Events.ORGANIZER, // 16 Events.ORIGINAL_EVENT // 17 do not remove; used in DeleteEventHelper }; private static final int EVENT_INDEX_ID = 0; private static final int EVENT_INDEX_TITLE = 1; private static final int EVENT_INDEX_RRULE = 2; private static final int EVENT_INDEX_ALL_DAY = 3; private static final int EVENT_INDEX_CALENDAR_ID = 4; private static final int EVENT_INDEX_SYNC_ID = 6; private static final int EVENT_INDEX_EVENT_TIMEZONE = 7; private static final int EVENT_INDEX_DESCRIPTION = 8; private static final int EVENT_INDEX_EVENT_LOCATION = 9; private static final int EVENT_INDEX_HAS_ALARM = 10; private static final int EVENT_INDEX_ACCESS_LEVEL = 11; private static final int EVENT_INDEX_COLOR = 12; private static final int EVENT_INDEX_HAS_ATTENDEE_DATA = 13; private static final int EVENT_INDEX_GUESTS_CAN_MODIFY = 14; private static final int EVENT_INDEX_CAN_INVITE_OTHERS = 15; private static final int EVENT_INDEX_ORGANIZER = 16; private static final String[] ATTENDEES_PROJECTION = new String[] { Attendees._ID, // 0 Attendees.ATTENDEE_NAME, // 1 Attendees.ATTENDEE_EMAIL, // 2 Attendees.ATTENDEE_RELATIONSHIP, // 3 Attendees.ATTENDEE_STATUS, // 4 }; private static final int ATTENDEES_INDEX_ID = 0; private static final int ATTENDEES_INDEX_NAME = 1; private static final int ATTENDEES_INDEX_EMAIL = 2; private static final int ATTENDEES_INDEX_RELATIONSHIP = 3; private static final int ATTENDEES_INDEX_STATUS = 4; private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=?"; private static final String ATTENDEES_SORT_ORDER = Attendees.ATTENDEE_NAME + " ASC, " + Attendees.ATTENDEE_EMAIL + " ASC"; static final String[] CALENDARS_PROJECTION = new String[] { Calendars._ID, // 0 Calendars.DISPLAY_NAME, // 1 Calendars.OWNER_ACCOUNT, // 2 Calendars.ORGANIZER_CAN_RESPOND // 3 }; static final int CALENDARS_INDEX_DISPLAY_NAME = 1; static final int CALENDARS_INDEX_OWNER_ACCOUNT = 2; static final int CALENDARS_INDEX_OWNER_CAN_RESPOND = 3; static final String CALENDARS_WHERE = Calendars._ID + "=?"; static final String CALENDARS_DUPLICATE_NAME_WHERE = Calendars.DISPLAY_NAME + "=?"; private static final String[] REMINDERS_PROJECTION = new String[] { Reminders._ID, // 0 Reminders.MINUTES, // 1 }; private static final int REMINDERS_INDEX_MINUTES = 1; private static final String REMINDERS_WHERE = Reminders.EVENT_ID + "=? AND (" + Reminders.METHOD + "=" + Reminders.METHOD_ALERT + " OR " + Reminders.METHOD + "=" + Reminders.METHOD_DEFAULT + ")"; private static final String REMINDERS_SORT = Reminders.MINUTES; private static final int MENU_GROUP_REMINDER = 1; private static final int MENU_GROUP_EDIT = 2; private static final int MENU_GROUP_DELETE = 3; private static final int MENU_ADD_REMINDER = 1; private static final int MENU_EDIT = 2; private static final int MENU_DELETE = 3; private static final int ATTENDEE_ID_NONE = -1; private static final int ATTENDEE_NO_RESPONSE = -1; private static final int[] ATTENDEE_VALUES = { ATTENDEE_NO_RESPONSE, Attendees.ATTENDEE_STATUS_ACCEPTED, Attendees.ATTENDEE_STATUS_TENTATIVE, Attendees.ATTENDEE_STATUS_DECLINED, }; private View mView; private LinearLayout mRemindersContainer; private LinearLayout mOrganizerContainer; private TextView mOrganizerView; private Uri mUri; private long mEventId; private Cursor mEventCursor; private Cursor mAttendeesCursor; private Cursor mCalendarsCursor; private long mStartMillis; private long mEndMillis; private boolean mHasAttendeeData; private boolean mIsOrganizer; private long mCalendarOwnerAttendeeId = ATTENDEE_ID_NONE; private boolean mOrganizerCanRespond; private String mCalendarOwnerAccount; private boolean mCanModifyCalendar; private boolean mIsBusyFreeCalendar; private boolean mCanModifyEvent; private int mNumOfAttendees; private String mOrganizer; private ArrayList<Integer> mOriginalMinutes = new ArrayList<Integer>(); private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0); private ArrayList<Integer> mReminderValues; private ArrayList<String> mReminderLabels; private int mDefaultReminderMinutes; private boolean mOriginalHasAlarm; private EditResponseHelper mEditResponseHelper; private int mResponseOffset; private int mOriginalAttendeeResponse; private int mAttendeeResponseFromIntent = ATTENDEE_NO_RESPONSE; private boolean mIsRepeating; private boolean mIsDuplicateName; private Pattern mWildcardPattern = Pattern.compile("^.*$"); private LayoutInflater mLayoutInflater; private LinearLayout mReminderAdder; // TODO This can be removed when the contacts content provider doesn't return duplicates private int mUpdateCounts; private static class ViewHolder { QuickContactBadge badge; ImageView presence; int updateCounts; } private HashMap<String, ViewHolder> mViewHolders = new HashMap<String, ViewHolder>(); private PresenceQueryHandler mPresenceQueryHandler; private static final Uri CONTACT_DATA_WITH_PRESENCE_URI = Data.CONTENT_URI; int PRESENCE_PROJECTION_CONTACT_ID_INDEX = 0; int PRESENCE_PROJECTION_PRESENCE_INDEX = 1; int PRESENCE_PROJECTION_EMAIL_INDEX = 2; int PRESENCE_PROJECTION_PHOTO_ID_INDEX = 3; private static final String[] PRESENCE_PROJECTION = new String[] { Email.CONTACT_ID, // 0 Email.CONTACT_PRESENCE, // 1 Email.DATA, // 2 Email.PHOTO_ID, // 3 }; ArrayList<Attendee> mAcceptedAttendees = new ArrayList<Attendee>(); ArrayList<Attendee> mDeclinedAttendees = new ArrayList<Attendee>(); ArrayList<Attendee> mTentativeAttendees = new ArrayList<Attendee>(); ArrayList<Attendee> mNoResponseAttendees = new ArrayList<Attendee>(); private int mColor; private QueryHandler mHandler; private class QueryHandler extends AsyncQueryService { public QueryHandler(Context context) { super(context); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { // if the activity is finishing, then close the cursor and return final Activity activity = getActivity(); if (activity == null || activity.isFinishing()) { cursor.close(); return; } switch (token) { case TOKEN_QUERY_EVENT: mEventCursor = Utils.matrixCursorFromCursor(cursor); if (initEventCursor()) { // The cursor is empty. This can happen if the event was // deleted. // FRAG_TODO we should no longer rely on Activity.finish() activity.finish(); return; } updateEvent(mView); // start calendar query Uri uri = Calendars.CONTENT_URI; String[] args = new String[] { Long.toString(mEventCursor.getLong(EVENT_INDEX_CALENDAR_ID))}; startQuery(TOKEN_QUERY_CALENDARS, null, uri, CALENDARS_PROJECTION, CALENDARS_WHERE, args, null); break; case TOKEN_QUERY_CALENDARS: mCalendarsCursor = Utils.matrixCursorFromCursor(cursor); updateCalendar(mView); // FRAG_TODO fragments shouldn't set the title anymore updateTitle(); // update the action bar since our option set might have changed activity.invalidateOptionsMenu(); // this is used for both attendees and reminders args = new String[] { Long.toString(mEventId) }; // start attendees query uri = Attendees.CONTENT_URI; startQuery(TOKEN_QUERY_ATTENDEES, null, uri, ATTENDEES_PROJECTION, ATTENDEES_WHERE, args, ATTENDEES_SORT_ORDER); // start reminders query mOriginalHasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0; if (mOriginalHasAlarm) { uri = Reminders.CONTENT_URI; startQuery(TOKEN_QUERY_REMINDERS, null, uri, REMINDERS_PROJECTION, REMINDERS_WHERE, args, REMINDERS_SORT); } else { // if no reminders, hide the appropriate fields updateRemindersVisibility(); } break; case TOKEN_QUERY_ATTENDEES: mAttendeesCursor = Utils.matrixCursorFromCursor(cursor); initAttendeesCursor(mView); updateResponse(mView); break; case TOKEN_QUERY_REMINDERS: MatrixCursor reminderCursor = Utils.matrixCursorFromCursor(cursor); try { // First pass: collect all the custom reminder minutes // (e.g., a reminder of 8 minutes) into a global list. while (reminderCursor.moveToNext()) { int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES); EventViewUtils.addMinutesToList( activity, mReminderValues, mReminderLabels, minutes); } // Second pass: create the reminder spinners reminderCursor.moveToPosition(-1); while (reminderCursor.moveToNext()) { int minutes = reminderCursor.getInt(REMINDERS_INDEX_MINUTES); mOriginalMinutes.add(minutes); EventViewUtils.addReminder(activity, mRemindersContainer, EventInfoFragment.this, mReminderItems, mReminderValues, mReminderLabels, minutes); } } finally { updateRemindersVisibility(); reminderCursor.close(); } break; case TOKEN_QUERY_DUPLICATE_CALENDARS: mIsDuplicateName = cursor.getCount() > 1; String calendarName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME); String ownerAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT); if (mIsDuplicateName && !calendarName.equalsIgnoreCase(ownerAccount)) { Resources res = activity.getResources(); TextView ownerText = (TextView) mView.findViewById(R.id.owner); ownerText.setText(ownerAccount); ownerText.setTextColor(res.getColor(R.color.calendar_owner_text_color)); } else { setVisibilityCommon(mView, R.id.owner, View.GONE); } setTextCommon(mView, R.id.calendar, calendarName); break; } cursor.close(); } } public EventInfoFragment() { mUri = null; } public EventInfoFragment(Uri uri, long startMillis, long endMillis, int attendeeResponse) { mUri = uri; mStartMillis = startMillis; mEndMillis = endMillis; mAttendeeResponseFromIntent = attendeeResponse; } public EventInfoFragment(long eventId, long startMillis, long endMillis) { this(ContentUris.withAppendedId(Events.CONTENT_URI, eventId), startMillis, endMillis, EventInfoActivity.ATTENDEE_NO_RESPONSE); mEventId = eventId; } // This is called when one of the "remove reminder" buttons is selected. public void onClick(View v) { LinearLayout reminderItem = (LinearLayout) v.getParent(); LinearLayout parent = (LinearLayout) reminderItem.getParent(); parent.removeView(reminderItem); mReminderItems.remove(reminderItem); updateRemindersVisibility(); } public void onItemSelected(AdapterView<?> parent, View v, int position, long id) { // If they selected the "No response" option, then don't display the // dialog asking which events to change. if (id == 0 && mResponseOffset == 0) { return; } // If this is not a repeating event, then don't display the dialog // asking which events to change. if (!mIsRepeating) { return; } // If the selection is the same as the original, then don't display the // dialog asking which events to change. int index = findResponseIndexFor(mOriginalAttendeeResponse); if (position == index + mResponseOffset) { return; } // This is a repeating event. We need to ask the user if they mean to // change just this one instance or all instances. mEditResponseHelper.showDialog(mEditResponseHelper.getWhichEvents()); } public void onNothingSelected(AdapterView<?> parent) { } @Override public void onAttach(Activity activity) { super.onAttach(activity); mEditResponseHelper = new EditResponseHelper(activity); setHasOptionsMenu(true); mHandler = new QueryHandler(activity); mPresenceQueryHandler = new PresenceQueryHandler(activity, activity.getContentResolver()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mLayoutInflater = inflater; mView = inflater.inflate(R.layout.event_info_activity, null); mRemindersContainer = (LinearLayout) mView.findViewById(R.id.reminders_container); mOrganizerContainer = (LinearLayout) mView.findViewById(R.id.organizer_container); mOrganizerView = (TextView) mView.findViewById(R.id.organizer); // Initialize the reminder values array. Resources r = getActivity().getResources(); String[] strings = r.getStringArray(R.array.reminder_minutes_values); int size = strings.length; ArrayList<Integer> list = new ArrayList<Integer>(size); for (int i = 0 ; i < size ; i++) { list.add(Integer.parseInt(strings[i])); } mReminderValues = list; String[] labels = r.getStringArray(R.array.reminder_minutes_labels); mReminderLabels = new ArrayList<String>(Arrays.asList(labels)); SharedPreferences prefs = CalendarPreferenceActivity.getSharedPreferences(getActivity()); String durationString = prefs.getString(CalendarPreferenceActivity.KEY_DEFAULT_REMINDER, "0"); mDefaultReminderMinutes = Integer.parseInt(durationString); // Setup the + Add Reminder Button View.OnClickListener addReminderOnClickListener = new View.OnClickListener() { public void onClick(View v) { addReminder(); } }; ImageButton reminderAddButton = (ImageButton) mView.findViewById(R.id.reminder_add); reminderAddButton.setOnClickListener(addReminderOnClickListener); mReminderAdder = (LinearLayout) mView.findViewById(R.id.reminder_adder); if (mUri == null) { // restore event ID from bundle mEventId = savedInstanceState.getLong(BUNDLE_KEY_EVENT_ID); mUri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId); mStartMillis = savedInstanceState.getLong(BUNDLE_KEY_START_MILLIS); mEndMillis = savedInstanceState.getLong(BUNDLE_KEY_END_MILLIS); } // start loading the data mHandler.startQuery(TOKEN_QUERY_EVENT, null, mUri, EVENT_PROJECTION, null, null, null); return mView; } private void updateTitle() { Resources res = getActivity().getResources(); if (mCanModifyCalendar && !mIsOrganizer) { getActivity().setTitle(res.getString(R.string.event_info_title_invite)); } else { getActivity().setTitle(res.getString(R.string.event_info_title)); } } /** * Initializes the event cursor, which is expected to point to the first * (and only) result from a query. * @return true if the cursor is empty. */ private boolean initEventCursor() { if ((mEventCursor == null) || (mEventCursor.getCount() == 0)) { return true; } mEventCursor.moveToFirst(); mEventId = mEventCursor.getInt(EVENT_INDEX_ID); String rRule = mEventCursor.getString(EVENT_INDEX_RRULE); mIsRepeating = (rRule != null); return false; } private static class Attendee { String mName; String mEmail; Attendee(String name, String email) { mName = name; mEmail = email; } } @SuppressWarnings("fallthrough") private void initAttendeesCursor(View view) { mOriginalAttendeeResponse = ATTENDEE_NO_RESPONSE; mCalendarOwnerAttendeeId = ATTENDEE_ID_NONE; mNumOfAttendees = 0; if (mAttendeesCursor != null) { mNumOfAttendees = mAttendeesCursor.getCount(); if (mAttendeesCursor.moveToFirst()) { mAcceptedAttendees.clear(); mDeclinedAttendees.clear(); mTentativeAttendees.clear(); mNoResponseAttendees.clear(); do { int status = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS); String name = mAttendeesCursor.getString(ATTENDEES_INDEX_NAME); String email = mAttendeesCursor.getString(ATTENDEES_INDEX_EMAIL); if (mAttendeesCursor.getInt(ATTENDEES_INDEX_RELATIONSHIP) == Attendees.RELATIONSHIP_ORGANIZER) { // Overwrites the one from Event table if available if (name != null && name.length() > 0) { mOrganizer = name; } else if (email != null && email.length() > 0) { mOrganizer = email; } } if (mCalendarOwnerAttendeeId == ATTENDEE_ID_NONE && mCalendarOwnerAccount.equalsIgnoreCase(email)) { mCalendarOwnerAttendeeId = mAttendeesCursor.getInt(ATTENDEES_INDEX_ID); mOriginalAttendeeResponse = mAttendeesCursor.getInt(ATTENDEES_INDEX_STATUS); } else { // Don't show your own status in the list because: // 1) it doesn't make sense for event without other guests. // 2) there's a spinner for that for events with guests. switch(status) { case Attendees.ATTENDEE_STATUS_ACCEPTED: mAcceptedAttendees.add(new Attendee(name, email)); break; case Attendees.ATTENDEE_STATUS_DECLINED: mDeclinedAttendees.add(new Attendee(name, email)); break; case Attendees.ATTENDEE_STATUS_NONE: mNoResponseAttendees.add(new Attendee(name, email)); // Fallthrough so that no response is a subset of tentative default: mTentativeAttendees.add(new Attendee(name, email)); } } } while (mAttendeesCursor.moveToNext()); mAttendeesCursor.moveToFirst(); updateAttendees(view); } } // only show the organizer if we're not the organizer and if // we have attendee data (might have been removed by the server // for events with a lot of attendees). if (!mIsOrganizer && mHasAttendeeData) { mOrganizerContainer.setVisibility(View.VISIBLE); mOrganizerView.setText(mOrganizer); } else { mOrganizerContainer.setVisibility(View.GONE); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putLong(BUNDLE_KEY_EVENT_ID, mEventId); outState.putLong(BUNDLE_KEY_START_MILLIS, mStartMillis); outState.putLong(BUNDLE_KEY_END_MILLIS, mEndMillis); } @Override public void onDestroyView() { ArrayList<Integer> reminderMinutes = EventViewUtils.reminderItemsToMinutes(mReminderItems, mReminderValues); ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(3); boolean changed = EditEventHelper.saveReminders(ops, mEventId, reminderMinutes, mOriginalMinutes, false /* no force save */); mHandler.startBatch(mHandler.getNextToken(), null, Calendars.CONTENT_URI.getAuthority(), ops, Utils.UNDO_DELAY); // Update the "hasAlarm" field for the event Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId); int len = reminderMinutes.size(); boolean hasAlarm = len > 0; if (hasAlarm != mOriginalHasAlarm) { ContentValues values = new ContentValues(); values.put(Events.HAS_ALARM, hasAlarm ? 1 : 0); mHandler.startUpdate(mHandler.getNextToken(), null, uri, values, null, null, Utils.UNDO_DELAY); } changed |= saveResponse(); if (changed) { Toast.makeText(getActivity(), R.string.saving_event, Toast.LENGTH_SHORT).show(); } super.onDestroyView(); } @Override public void onDestroy() { super.onDestroy(); if (mEventCursor != null) { mEventCursor.close(); } if (mCalendarsCursor != null) { mCalendarsCursor.close(); } if (mAttendeesCursor != null) { mAttendeesCursor.close(); } } private boolean canAddReminders() { return !mIsBusyFreeCalendar && mReminderItems.size() < MAX_REMINDERS; } private void addReminder() { // TODO: when adding a new reminder, make it different from the // last one in the list (if any). if (mDefaultReminderMinutes == 0) { EventViewUtils.addReminder(getActivity(), mRemindersContainer, this, mReminderItems, mReminderValues, mReminderLabels, 10 /* minutes */); } else { EventViewUtils.addReminder(getActivity(), mRemindersContainer, this, mReminderItems, mReminderValues, mReminderLabels, mDefaultReminderMinutes); } updateRemindersVisibility(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { MenuItem item; item = menu.add(MENU_GROUP_REMINDER, MENU_ADD_REMINDER, 0, R.string.add_new_reminder); item.setIcon(R.drawable.ic_menu_reminder); item.setAlphabeticShortcut('r'); item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); item = menu.add(MENU_GROUP_EDIT, MENU_EDIT, 0, R.string.edit_event_label); item.setIcon(android.R.drawable.ic_menu_edit); item.setAlphabeticShortcut('e'); item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); item = menu.add(MENU_GROUP_DELETE, MENU_DELETE, 0, R.string.delete_event_label); item.setIcon(android.R.drawable.ic_menu_delete); item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); super.onCreateOptionsMenu(menu, inflater); } @Override public void onPrepareOptionsMenu(Menu menu) { boolean canAddReminders = canAddReminders(); menu.setGroupVisible(MENU_GROUP_REMINDER, canAddReminders); menu.setGroupEnabled(MENU_GROUP_REMINDER, canAddReminders); menu.setGroupVisible(MENU_GROUP_EDIT, mCanModifyEvent); menu.setGroupEnabled(MENU_GROUP_EDIT, mCanModifyEvent); menu.setGroupVisible(MENU_GROUP_DELETE, mCanModifyCalendar); menu.setGroupEnabled(MENU_GROUP_DELETE, mCanModifyCalendar); super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case MENU_ADD_REMINDER: addReminder(); break; case MENU_EDIT: doEdit(); break; case MENU_DELETE: doDelete(); break; } return true; } // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // if (keyCode == KeyEvent.KEYCODE_DEL) { // doDelete(); // return true; // } // return super.onKeyDown(keyCode, event); // } private void updateRemindersVisibility() { if (mIsBusyFreeCalendar) { mRemindersContainer.setVisibility(View.GONE); } else { mRemindersContainer.setVisibility(View.VISIBLE); mReminderAdder.setVisibility(canAddReminders() ? View.VISIBLE : View.GONE); } } /** * Asynchronously saves the response to an invitation if the user changed * the response. Returns true if the database will be updated. * * @param cr the ContentResolver * @return true if the database will be changed */ private boolean saveResponse() { if (mAttendeesCursor == null || mEventCursor == null) { return false; } Spinner spinner = (Spinner) getView().findViewById(R.id.response_value); int position = spinner.getSelectedItemPosition() - mResponseOffset; if (position <= 0) { return false; } int status = ATTENDEE_VALUES[position]; // If the status has not changed, then don't update the database if (status == mOriginalAttendeeResponse) { return false; } // If we never got an owner attendee id we can't set the status if (mCalendarOwnerAttendeeId == ATTENDEE_ID_NONE) { return false; } if (!mIsRepeating) { // This is a non-repeating event updateResponse(mEventId, mCalendarOwnerAttendeeId, status); return true; } // This is a repeating event int whichEvents = mEditResponseHelper.getWhichEvents(); switch (whichEvents) { case -1: return false; case UPDATE_SINGLE: createExceptionResponse(mEventId, mCalendarOwnerAttendeeId, status); return true; case UPDATE_ALL: updateResponse(mEventId, mCalendarOwnerAttendeeId, status); return true; default: Log.e(TAG, "Unexpected choice for updating invitation response"); break; } return false; } private void updateResponse(long eventId, long attendeeId, int status) { // Update the attendee status in the attendees table. the provider // takes care of updating the self attendance status. ContentValues values = new ContentValues(); if (!TextUtils.isEmpty(mCalendarOwnerAccount)) { values.put(Attendees.ATTENDEE_EMAIL, mCalendarOwnerAccount); } values.put(Attendees.ATTENDEE_STATUS, status); values.put(Attendees.EVENT_ID, eventId); Uri uri = ContentUris.withAppendedId(Attendees.CONTENT_URI, attendeeId); mHandler.startUpdate(mHandler.getNextToken(), null, uri, values, null, null, Utils.UNDO_DELAY); } private void createExceptionResponse(long eventId, long attendeeId, int status) { if (mEventCursor == null || !mEventCursor.moveToFirst()) { return; } ContentValues values = new ContentValues(); String title = mEventCursor.getString(EVENT_INDEX_TITLE); String timezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE); int calendarId = mEventCursor.getInt(EVENT_INDEX_CALENDAR_ID); boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0; String syncId = mEventCursor.getString(EVENT_INDEX_SYNC_ID); values.put(Events.TITLE, title); values.put(Events.EVENT_TIMEZONE, timezone); values.put(Events.ALL_DAY, allDay ? 1 : 0); values.put(Events.CALENDAR_ID, calendarId); values.put(Events.DTSTART, mStartMillis); values.put(Events.DTEND, mEndMillis); values.put(Events.ORIGINAL_EVENT, syncId); values.put(Events.ORIGINAL_INSTANCE_TIME, mStartMillis); values.put(Events.ORIGINAL_ALL_DAY, allDay ? 1 : 0); values.put(Events.STATUS, Events.STATUS_CONFIRMED); values.put(Events.SELF_ATTENDEE_STATUS, status); // Create a recurrence exception mHandler.startInsert(mHandler.getNextToken(), null, Events.CONTENT_URI, values, Utils.UNDO_DELAY); } private int findResponseIndexFor(int response) { int size = ATTENDEE_VALUES.length; for (int index = 0; index < size; index++) { if (ATTENDEE_VALUES[index] == response) { return index; } } return 0; } private void doEdit() { CalendarController.getInstance(getActivity()).sendEventRelatedEvent( this, EventType.EDIT_EVENT, mEventId, mStartMillis, mEndMillis, 0, 0); } private void doDelete() { CalendarController.getInstance(getActivity()).sendEventRelatedEvent( this, EventType.DELETE_EVENT, mEventId, mStartMillis, mEndMillis, 0, 0); } private void updateEvent(View view) { if (mEventCursor == null) { return; } String eventName = mEventCursor.getString(EVENT_INDEX_TITLE); if (eventName == null || eventName.length() == 0) { eventName = getActivity().getString(R.string.no_title_label); } boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0; String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION); String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION); String rRule = mEventCursor.getString(EVENT_INDEX_RRULE); boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0; String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE); mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff; View calBackground = view.findViewById(R.id.cal_background); calBackground.setBackgroundColor(mColor); TextView title = (TextView) view.findViewById(R.id.title); title.setTextColor(mColor); View divider = view.findViewById(R.id.divider); divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN); // What if (eventName != null) { setTextCommon(view, R.id.title, eventName); } // When String when; int flags; if (allDay) { flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE; } else { flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE; if (DateFormat.is24HourFormat(getActivity())) { flags |= DateUtils.FORMAT_24HOUR; } } when = DateUtils.formatDateRange(getActivity(), mStartMillis, mEndMillis, flags); setTextCommon(view, R.id.when, when); // Show the event timezone if it is different from the local timezone Time time = new Time(); String localTimezone = time.timezone; if (allDay) { localTimezone = Time.TIMEZONE_UTC; } if (eventTimezone != null && !localTimezone.equals(eventTimezone) && !allDay) { String displayName; TimeZone tz = TimeZone.getTimeZone(localTimezone); if (tz == null || tz.getID().equals("GMT")) { displayName = localTimezone; } else { displayName = tz.getDisplayName(); } setTextCommon(view, R.id.timezone, displayName); + setVisibilityCommon(view, R.id.timezone_container, View.VISIBLE); } else { setVisibilityCommon(view, R.id.timezone_container, View.GONE); } // Repeat if (rRule != null) { EventRecurrence eventRecurrence = new EventRecurrence(); eventRecurrence.parse(rRule); Time date = new Time(); if (allDay) { date.timezone = Time.TIMEZONE_UTC; } date.set(mStartMillis); eventRecurrence.setStartDate(date); String repeatString = EventRecurrenceFormatter.getRepeatString( getActivity().getResources(), eventRecurrence); setTextCommon(view, R.id.repeat, repeatString); + setVisibilityCommon(view, R.id.repeat_container, View.VISIBLE); } else { setVisibilityCommon(view, R.id.repeat_container, View.GONE); } // Where if (location == null || location.length() == 0) { setVisibilityCommon(view, R.id.where, View.GONE); } else { final TextView textView = (TextView) view.findViewById(R.id.where); if (textView != null) { textView.setAutoLinkMask(0); textView.setText(location); Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q="); textView.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { try { return v.onTouchEvent(event); } catch (ActivityNotFoundException e) { // ignore return true; } } }); } } // Description if (description == null || description.length() == 0) { setVisibilityCommon(view, R.id.description, View.GONE); } else { setTextCommon(view, R.id.description, description); } } private void updateCalendar(View view) { mCalendarOwnerAccount = ""; if (mCalendarsCursor != null && mEventCursor != null) { mCalendarsCursor.moveToFirst(); String tempAccount = mCalendarsCursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT); mCalendarOwnerAccount = (tempAccount == null) ? "" : tempAccount; mOrganizerCanRespond = mCalendarsCursor.getInt(CALENDARS_INDEX_OWNER_CAN_RESPOND) != 0; String displayName = mCalendarsCursor.getString(CALENDARS_INDEX_DISPLAY_NAME); // start duplicate calendars query mHandler.startQuery(TOKEN_QUERY_DUPLICATE_CALENDARS, null, Calendars.CONTENT_URI, CALENDARS_PROJECTION, CALENDARS_DUPLICATE_NAME_WHERE, new String[] {displayName}, null); String eventOrganizer = mEventCursor.getString(EVENT_INDEX_ORGANIZER); mIsOrganizer = mCalendarOwnerAccount.equalsIgnoreCase(eventOrganizer); mHasAttendeeData = mEventCursor.getInt(EVENT_INDEX_HAS_ATTENDEE_DATA) != 0; mOrganizer = eventOrganizer; mCanModifyCalendar = mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) >= Calendars.CONTRIBUTOR_ACCESS; mIsBusyFreeCalendar = mEventCursor.getInt(EVENT_INDEX_ACCESS_LEVEL) == Calendars.FREEBUSY_ACCESS; mCanModifyEvent = mCanModifyCalendar && (mIsOrganizer || (mEventCursor.getInt(EVENT_INDEX_GUESTS_CAN_MODIFY) != 0)); } else { setVisibilityCommon(view, R.id.calendar_container, View.GONE); } } private void updateAttendees(View view) { LinearLayout attendeesLayout = (LinearLayout) view.findViewById(R.id.attendee_list); attendeesLayout.removeAllViewsInLayout(); ++mUpdateCounts; if(mAcceptedAttendees.size() == 0 && mDeclinedAttendees.size() == 0 && mTentativeAttendees.size() == mNoResponseAttendees.size()) { // If all guests have no response just list them as guests, CharSequence guestsLabel = getActivity().getResources().getText(R.string.attendees_label); addAttendeesToLayout(mNoResponseAttendees, attendeesLayout, guestsLabel); } else { // If we have any responses then divide them up by response CharSequence[] entries; entries = getActivity().getResources().getTextArray(R.array.response_labels2); addAttendeesToLayout(mAcceptedAttendees, attendeesLayout, entries[0]); addAttendeesToLayout(mDeclinedAttendees, attendeesLayout, entries[2]); addAttendeesToLayout(mTentativeAttendees, attendeesLayout, entries[1]); } } private void addAttendeesToLayout(ArrayList<Attendee> attendees, LinearLayout attendeeList, CharSequence sectionTitle) { if (attendees.size() == 0) { return; } // Yes/No/Maybe Title View titleView = mLayoutInflater.inflate(R.layout.contact_item, null); titleView.findViewById(R.id.badge).setVisibility(View.GONE); View divider = titleView.findViewById(R.id.separator); divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN); TextView title = (TextView) titleView.findViewById(R.id.name); title.setText(getActivity().getString(R.string.response_label, sectionTitle, attendees.size())); title.setTextAppearance(getActivity(), R.style.TextAppearance_EventInfo_Label); attendeeList.addView(titleView); // Attendees int numOfAttendees = attendees.size(); StringBuilder selection = new StringBuilder(Email.DATA + " IN ("); String[] selectionArgs = new String[numOfAttendees]; for (int i = 0; i < numOfAttendees; ++i) { Attendee attendee = attendees.get(i); selectionArgs[i] = attendee.mEmail; View v = mLayoutInflater.inflate(R.layout.contact_item, null); v.setTag(attendee); View separator = v.findViewById(R.id.separator); separator.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN); // Text TextView tv = (TextView) v.findViewById(R.id.name); String name = attendee.mName; if (name == null || name.length() == 0) { name = attendee.mEmail; } tv.setText(name); ViewHolder vh = new ViewHolder(); vh.badge = (QuickContactBadge) v.findViewById(R.id.badge); vh.badge.assignContactFromEmail(attendee.mEmail, true); vh.presence = (ImageView) v.findViewById(R.id.presence); mViewHolders.put(attendee.mEmail, vh); if (i == 0) { selection.append('?'); } else { selection.append(", ?"); } attendeeList.addView(v); } selection.append(')'); mPresenceQueryHandler.startQuery(mUpdateCounts, attendees, CONTACT_DATA_WITH_PRESENCE_URI, PRESENCE_PROJECTION, selection.toString(), selectionArgs, null); } private class PresenceQueryHandler extends AsyncQueryHandler { Context mContext; public PresenceQueryHandler(Context context, ContentResolver cr) { super(cr); mContext = context; } @Override protected void onQueryComplete(int queryIndex, Object cookie, Cursor cursor) { if (cursor == null) { if (DEBUG) { Log.e(TAG, "onQueryComplete: cursor == null"); } return; } try { cursor.moveToPosition(-1); while (cursor.moveToNext()) { String email = cursor.getString(PRESENCE_PROJECTION_EMAIL_INDEX); int contactId = cursor.getInt(PRESENCE_PROJECTION_CONTACT_ID_INDEX); ViewHolder vh = mViewHolders.get(email); int photoId = cursor.getInt(PRESENCE_PROJECTION_PHOTO_ID_INDEX); if (DEBUG) { Log.e(TAG, "onQueryComplete Id: " + contactId + " PhotoId: " + photoId + " Email: " + email); } if (vh == null) { continue; } ImageView presenceView = vh.presence; if (presenceView != null) { int status = cursor.getInt(PRESENCE_PROJECTION_PRESENCE_INDEX); presenceView.setImageResource(Presence.getPresenceIconResourceId(status)); presenceView.setVisibility(View.VISIBLE); } if (photoId > 0 && vh.updateCounts < queryIndex) { vh.updateCounts = queryIndex; Uri personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); // TODO, modify to batch queries together ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext, vh.badge, personUri, R.drawable.ic_contact_picture); } } } finally { cursor.close(); } } } void updateResponse(View view) { // we only let the user accept/reject/etc. a meeting if: // a) you can edit the event's containing calendar AND // b) you're not the organizer and only attendee AND // c) organizerCanRespond is enabled for the calendar // (if the attendee data has been hidden, the visible number of attendees // will be 1 -- the calendar owner's). // (there are more cases involved to be 100% accurate, such as // paying attention to whether or not an attendee status was // included in the feed, but we're currently omitting those corner cases // for simplicity). if (!mCanModifyCalendar || (mHasAttendeeData && mIsOrganizer && mNumOfAttendees <= 1) || (mIsOrganizer && !mOrganizerCanRespond)) { setVisibilityCommon(view, R.id.response_container, View.GONE); return; } setVisibilityCommon(view, R.id.response_container, View.VISIBLE); Spinner spinner = (Spinner) view.findViewById(R.id.response_value); mResponseOffset = 0; /* If the user has previously responded to this event * we should not allow them to select no response again. * Switch the entries to a set of entries without the * no response option. */ if ((mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_INVITED) && (mOriginalAttendeeResponse != ATTENDEE_NO_RESPONSE) && (mOriginalAttendeeResponse != Attendees.ATTENDEE_STATUS_NONE)) { CharSequence[] entries; entries = getActivity().getResources().getTextArray(R.array.response_labels2); mResponseOffset = -1; ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getActivity(), android.R.layout.simple_spinner_item, entries); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } int index; if (mAttendeeResponseFromIntent != ATTENDEE_NO_RESPONSE) { index = findResponseIndexFor(mAttendeeResponseFromIntent); } else { index = findResponseIndexFor(mOriginalAttendeeResponse); } spinner.setSelection(index + mResponseOffset); spinner.setOnItemSelectedListener(this); } private void setTextCommon(View view, int id, CharSequence text) { TextView textView = (TextView) view.findViewById(id); if (textView == null) return; textView.setText(text); } private void setVisibilityCommon(View view, int id, int visibility) { View v = view.findViewById(id); if (v != null) { v.setVisibility(visibility); } return; } /** * Taken from com.google.android.gm.HtmlConversationActivity * * Send the intent that shows the Contact info corresponding to the email address. */ public void showContactInfo(Attendee attendee, Rect rect) { // First perform lookup query to find existing contact final ContentResolver resolver = getActivity().getContentResolver(); final String address = attendee.mEmail; final Uri dataUri = Uri.withAppendedPath(CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(address)); final Uri lookupUri = ContactsContract.Data.getContactLookupUri(resolver, dataUri); if (lookupUri != null) { // Found matching contact, trigger QuickContact QuickContact.showQuickContact(getActivity(), rect, lookupUri, QuickContact.MODE_MEDIUM, null); } else { // No matching contact, ask user to create one final Uri mailUri = Uri.fromParts("mailto", address, null); final Intent intent = new Intent(Intents.SHOW_OR_CREATE_CONTACT, mailUri); // Pass along full E-mail string for possible create dialog Rfc822Token sender = new Rfc822Token(attendee.mName, attendee.mEmail, null); intent.putExtra(Intents.EXTRA_CREATE_DESCRIPTION, sender.toString()); // Only provide personal name hint if we have one final String senderPersonal = attendee.mName; if (!TextUtils.isEmpty(senderPersonal)) { intent.putExtra(Intents.Insert.NAME, senderPersonal); } startActivity(intent); } } }
false
true
private void updateEvent(View view) { if (mEventCursor == null) { return; } String eventName = mEventCursor.getString(EVENT_INDEX_TITLE); if (eventName == null || eventName.length() == 0) { eventName = getActivity().getString(R.string.no_title_label); } boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0; String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION); String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION); String rRule = mEventCursor.getString(EVENT_INDEX_RRULE); boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0; String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE); mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff; View calBackground = view.findViewById(R.id.cal_background); calBackground.setBackgroundColor(mColor); TextView title = (TextView) view.findViewById(R.id.title); title.setTextColor(mColor); View divider = view.findViewById(R.id.divider); divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN); // What if (eventName != null) { setTextCommon(view, R.id.title, eventName); } // When String when; int flags; if (allDay) { flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE; } else { flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE; if (DateFormat.is24HourFormat(getActivity())) { flags |= DateUtils.FORMAT_24HOUR; } } when = DateUtils.formatDateRange(getActivity(), mStartMillis, mEndMillis, flags); setTextCommon(view, R.id.when, when); // Show the event timezone if it is different from the local timezone Time time = new Time(); String localTimezone = time.timezone; if (allDay) { localTimezone = Time.TIMEZONE_UTC; } if (eventTimezone != null && !localTimezone.equals(eventTimezone) && !allDay) { String displayName; TimeZone tz = TimeZone.getTimeZone(localTimezone); if (tz == null || tz.getID().equals("GMT")) { displayName = localTimezone; } else { displayName = tz.getDisplayName(); } setTextCommon(view, R.id.timezone, displayName); } else { setVisibilityCommon(view, R.id.timezone_container, View.GONE); } // Repeat if (rRule != null) { EventRecurrence eventRecurrence = new EventRecurrence(); eventRecurrence.parse(rRule); Time date = new Time(); if (allDay) { date.timezone = Time.TIMEZONE_UTC; } date.set(mStartMillis); eventRecurrence.setStartDate(date); String repeatString = EventRecurrenceFormatter.getRepeatString( getActivity().getResources(), eventRecurrence); setTextCommon(view, R.id.repeat, repeatString); } else { setVisibilityCommon(view, R.id.repeat_container, View.GONE); } // Where if (location == null || location.length() == 0) { setVisibilityCommon(view, R.id.where, View.GONE); } else { final TextView textView = (TextView) view.findViewById(R.id.where); if (textView != null) { textView.setAutoLinkMask(0); textView.setText(location); Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q="); textView.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { try { return v.onTouchEvent(event); } catch (ActivityNotFoundException e) { // ignore return true; } } }); } } // Description if (description == null || description.length() == 0) { setVisibilityCommon(view, R.id.description, View.GONE); } else { setTextCommon(view, R.id.description, description); } }
private void updateEvent(View view) { if (mEventCursor == null) { return; } String eventName = mEventCursor.getString(EVENT_INDEX_TITLE); if (eventName == null || eventName.length() == 0) { eventName = getActivity().getString(R.string.no_title_label); } boolean allDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0; String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION); String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION); String rRule = mEventCursor.getString(EVENT_INDEX_RRULE); boolean hasAlarm = mEventCursor.getInt(EVENT_INDEX_HAS_ALARM) != 0; String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE); mColor = mEventCursor.getInt(EVENT_INDEX_COLOR) & 0xbbffffff; View calBackground = view.findViewById(R.id.cal_background); calBackground.setBackgroundColor(mColor); TextView title = (TextView) view.findViewById(R.id.title); title.setTextColor(mColor); View divider = view.findViewById(R.id.divider); divider.getBackground().setColorFilter(mColor, PorterDuff.Mode.SRC_IN); // What if (eventName != null) { setTextCommon(view, R.id.title, eventName); } // When String when; int flags; if (allDay) { flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE; } else { flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE; if (DateFormat.is24HourFormat(getActivity())) { flags |= DateUtils.FORMAT_24HOUR; } } when = DateUtils.formatDateRange(getActivity(), mStartMillis, mEndMillis, flags); setTextCommon(view, R.id.when, when); // Show the event timezone if it is different from the local timezone Time time = new Time(); String localTimezone = time.timezone; if (allDay) { localTimezone = Time.TIMEZONE_UTC; } if (eventTimezone != null && !localTimezone.equals(eventTimezone) && !allDay) { String displayName; TimeZone tz = TimeZone.getTimeZone(localTimezone); if (tz == null || tz.getID().equals("GMT")) { displayName = localTimezone; } else { displayName = tz.getDisplayName(); } setTextCommon(view, R.id.timezone, displayName); setVisibilityCommon(view, R.id.timezone_container, View.VISIBLE); } else { setVisibilityCommon(view, R.id.timezone_container, View.GONE); } // Repeat if (rRule != null) { EventRecurrence eventRecurrence = new EventRecurrence(); eventRecurrence.parse(rRule); Time date = new Time(); if (allDay) { date.timezone = Time.TIMEZONE_UTC; } date.set(mStartMillis); eventRecurrence.setStartDate(date); String repeatString = EventRecurrenceFormatter.getRepeatString( getActivity().getResources(), eventRecurrence); setTextCommon(view, R.id.repeat, repeatString); setVisibilityCommon(view, R.id.repeat_container, View.VISIBLE); } else { setVisibilityCommon(view, R.id.repeat_container, View.GONE); } // Where if (location == null || location.length() == 0) { setVisibilityCommon(view, R.id.where, View.GONE); } else { final TextView textView = (TextView) view.findViewById(R.id.where); if (textView != null) { textView.setAutoLinkMask(0); textView.setText(location); Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q="); textView.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { try { return v.onTouchEvent(event); } catch (ActivityNotFoundException e) { // ignore return true; } } }); } } // Description if (description == null || description.length() == 0) { setVisibilityCommon(view, R.id.description, View.GONE); } else { setTextCommon(view, R.id.description, description); } }
diff --git a/myPro/tool/FixNextLine.java b/myPro/tool/FixNextLine.java index 804d6be..24ea853 100755 --- a/myPro/tool/FixNextLine.java +++ b/myPro/tool/FixNextLine.java @@ -1,19 +1,19 @@ import java.util.Scanner; /** * 英語論文PDFからコピーしたテキストを * 適切な位置の改行に直す(ピリオドで改行)プログラム * (生成テキストは,Google翻訳で利用可能) * * @author (TAT)chaN * @since 2014/9/28 */ public class FixNextLine { public static void main(String[] args) { Scanner s = new Scanner(System.in); StringBuilder b = new StringBuilder(); while(s.hasNext()) - b.append(s.nextLine().replaceAll("\n", "")+" "); + b.append(s.nextLine().replace("\n", "")+" "); System.out.println(b.toString().replace(". ", ".\n")); } }
true
true
public static void main(String[] args) { Scanner s = new Scanner(System.in); StringBuilder b = new StringBuilder(); while(s.hasNext()) b.append(s.nextLine().replaceAll("\n", "")+" "); System.out.println(b.toString().replace(". ", ".\n")); }
public static void main(String[] args) { Scanner s = new Scanner(System.in); StringBuilder b = new StringBuilder(); while(s.hasNext()) b.append(s.nextLine().replace("\n", "")+" "); System.out.println(b.toString().replace(". ", ".\n")); }
diff --git a/src/org/geometerplus/fbreader/network/opds/OPDSLinkReader.java b/src/org/geometerplus/fbreader/network/opds/OPDSLinkReader.java index be8af8a..9a4b198 100644 --- a/src/org/geometerplus/fbreader/network/opds/OPDSLinkReader.java +++ b/src/org/geometerplus/fbreader/network/opds/OPDSLinkReader.java @@ -1,130 +1,129 @@ /* * Copyright (C) 2010 Geometer Plus <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.fbreader.network.opds; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; import org.geometerplus.zlibrary.core.network.ZLNetworkManager; import org.geometerplus.fbreader.Paths; import org.geometerplus.fbreader.network.*; import org.geometerplus.fbreader.network.atom.ATOMUpdated; public class OPDSLinkReader { static final String CATALOGS_URL = "http://data.fbreader.org/catalogs/generic-1.0.xml"; public static ICustomNetworkLink createCustomLink(int id, String siteName, String title, String summary, String icon, Map<String, String> links) { if (siteName == null || title == null || links.get(INetworkLink.URL_MAIN) == null) { return null; } return new OPDSCustomLink(id, siteName, title, summary, icon, links); } public static ICustomNetworkLink createCustomLinkWithoutInfo(String siteName, String url) { final HashMap<String, String> links = new HashMap<String, String>(); links.put(INetworkLink.URL_MAIN, url); return new OPDSCustomLink(ICustomNetworkLink.INVALID_ID, siteName, null, null, null, links); } public static final int CACHE_LOAD = 0; public static final int CACHE_UPDATE = 1; public static final int CACHE_CLEAR = 2; public static String loadOPDSLinks(int cacheMode, final NetworkLibrary.OnNewLinkListener listener) { final File dirFile = new File(Paths.networkCacheDirectory()); if (!dirFile.exists() && !dirFile.mkdirs()) { return NetworkErrors.errorMessage("cacheDirectoryError"); } final String fileName = "fbreader_catalogs-" + CATALOGS_URL.substring(CATALOGS_URL.lastIndexOf(File.separator) + 1); boolean goodCache = false; File oldCache = null; ATOMUpdated cacheUpdatedTime = null; final File catalogsFile = new File(dirFile, fileName); if (catalogsFile.exists()) { switch (cacheMode) { case CACHE_UPDATE: + final long diff = System.currentTimeMillis() - catalogsFile.lastModified(); + final long valid = 7 * 24 * 60 * 60 * 1000; // one week in milliseconds; FIXME: hardcoded const + if (diff >= 0 && diff <= valid) { + return null; + } + /* FALLTHROUGH */ + case CACHE_CLEAR: try { final OPDSLinkXMLReader reader = new OPDSLinkXMLReader(); reader.read(new FileInputStream(catalogsFile)); cacheUpdatedTime = reader.getUpdatedTime(); } catch (FileNotFoundException e) { throw new RuntimeException("That's impossible!!!", e); } - final long diff = System.currentTimeMillis() - catalogsFile.lastModified(); - final long valid = 7 * 24 * 60 * 60 * 1000; // one week in milliseconds; FIXME: hardcoded const - if (diff >= 0 && diff <= valid) { - goodCache = true; - break; - } - /* FALLTHROUGH */ - case CACHE_CLEAR: oldCache = new File(dirFile, "_" + fileName); oldCache.delete(); if (!catalogsFile.renameTo(oldCache)) { catalogsFile.delete(); oldCache = null; } break; case CACHE_LOAD: goodCache = true; break; default: throw new IllegalArgumentException("Invalid cacheMode value (" + cacheMode + ") in OPDSLinkReader.loadOPDSLinks method"); } } String error = null; if (!goodCache) { error = ZLNetworkManager.Instance().downloadToFile(CATALOGS_URL, catalogsFile); } if (error != null) { if (oldCache == null) { return error; } catalogsFile.delete(); if (!oldCache.renameTo(catalogsFile)) { oldCache.delete(); return error; } } else if (oldCache != null) { oldCache.delete(); oldCache = null; } try { new OPDSLinkXMLReader(listener, cacheUpdatedTime).read(new FileInputStream(catalogsFile)); } catch (FileNotFoundException e) { throw new RuntimeException("That's impossible!!!", e); } return null; } }
false
true
public static String loadOPDSLinks(int cacheMode, final NetworkLibrary.OnNewLinkListener listener) { final File dirFile = new File(Paths.networkCacheDirectory()); if (!dirFile.exists() && !dirFile.mkdirs()) { return NetworkErrors.errorMessage("cacheDirectoryError"); } final String fileName = "fbreader_catalogs-" + CATALOGS_URL.substring(CATALOGS_URL.lastIndexOf(File.separator) + 1); boolean goodCache = false; File oldCache = null; ATOMUpdated cacheUpdatedTime = null; final File catalogsFile = new File(dirFile, fileName); if (catalogsFile.exists()) { switch (cacheMode) { case CACHE_UPDATE: try { final OPDSLinkXMLReader reader = new OPDSLinkXMLReader(); reader.read(new FileInputStream(catalogsFile)); cacheUpdatedTime = reader.getUpdatedTime(); } catch (FileNotFoundException e) { throw new RuntimeException("That's impossible!!!", e); } final long diff = System.currentTimeMillis() - catalogsFile.lastModified(); final long valid = 7 * 24 * 60 * 60 * 1000; // one week in milliseconds; FIXME: hardcoded const if (diff >= 0 && diff <= valid) { goodCache = true; break; } /* FALLTHROUGH */ case CACHE_CLEAR: oldCache = new File(dirFile, "_" + fileName); oldCache.delete(); if (!catalogsFile.renameTo(oldCache)) { catalogsFile.delete(); oldCache = null; } break; case CACHE_LOAD: goodCache = true; break; default: throw new IllegalArgumentException("Invalid cacheMode value (" + cacheMode + ") in OPDSLinkReader.loadOPDSLinks method"); } } String error = null; if (!goodCache) { error = ZLNetworkManager.Instance().downloadToFile(CATALOGS_URL, catalogsFile); } if (error != null) { if (oldCache == null) { return error; } catalogsFile.delete(); if (!oldCache.renameTo(catalogsFile)) { oldCache.delete(); return error; } } else if (oldCache != null) { oldCache.delete(); oldCache = null; } try { new OPDSLinkXMLReader(listener, cacheUpdatedTime).read(new FileInputStream(catalogsFile)); } catch (FileNotFoundException e) { throw new RuntimeException("That's impossible!!!", e); } return null; }
public static String loadOPDSLinks(int cacheMode, final NetworkLibrary.OnNewLinkListener listener) { final File dirFile = new File(Paths.networkCacheDirectory()); if (!dirFile.exists() && !dirFile.mkdirs()) { return NetworkErrors.errorMessage("cacheDirectoryError"); } final String fileName = "fbreader_catalogs-" + CATALOGS_URL.substring(CATALOGS_URL.lastIndexOf(File.separator) + 1); boolean goodCache = false; File oldCache = null; ATOMUpdated cacheUpdatedTime = null; final File catalogsFile = new File(dirFile, fileName); if (catalogsFile.exists()) { switch (cacheMode) { case CACHE_UPDATE: final long diff = System.currentTimeMillis() - catalogsFile.lastModified(); final long valid = 7 * 24 * 60 * 60 * 1000; // one week in milliseconds; FIXME: hardcoded const if (diff >= 0 && diff <= valid) { return null; } /* FALLTHROUGH */ case CACHE_CLEAR: try { final OPDSLinkXMLReader reader = new OPDSLinkXMLReader(); reader.read(new FileInputStream(catalogsFile)); cacheUpdatedTime = reader.getUpdatedTime(); } catch (FileNotFoundException e) { throw new RuntimeException("That's impossible!!!", e); } oldCache = new File(dirFile, "_" + fileName); oldCache.delete(); if (!catalogsFile.renameTo(oldCache)) { catalogsFile.delete(); oldCache = null; } break; case CACHE_LOAD: goodCache = true; break; default: throw new IllegalArgumentException("Invalid cacheMode value (" + cacheMode + ") in OPDSLinkReader.loadOPDSLinks method"); } } String error = null; if (!goodCache) { error = ZLNetworkManager.Instance().downloadToFile(CATALOGS_URL, catalogsFile); } if (error != null) { if (oldCache == null) { return error; } catalogsFile.delete(); if (!oldCache.renameTo(catalogsFile)) { oldCache.delete(); return error; } } else if (oldCache != null) { oldCache.delete(); oldCache = null; } try { new OPDSLinkXMLReader(listener, cacheUpdatedTime).read(new FileInputStream(catalogsFile)); } catch (FileNotFoundException e) { throw new RuntimeException("That's impossible!!!", e); } return null; }
diff --git a/htroot/ConfigBasic.java b/htroot/ConfigBasic.java index a2857379e..c6cde30b4 100644 --- a/htroot/ConfigBasic.java +++ b/htroot/ConfigBasic.java @@ -1,224 +1,218 @@ // ConfigBasic_p.java // ----------------------- // part of YaCy // (C) by Michael Peter Christen; [email protected] // first published on http://www.anomic.de // Frankfurt, Germany, 2006 // Created 28.02.2006 // // $LastChangedDate: 2005-09-13 00:20:37 +0200 (Di, 13 Sep 2005) $ // $LastChangedRevision: 715 $ // $LastChangedBy: borg-0300 $ // // 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 // You must compile this file with // javac -classpath .:../classes ConfigBasic_p.java // if the shell's current path is HTROOT import java.util.regex.Pattern; import de.anomic.data.translator; import de.anomic.http.httpHeader; import de.anomic.http.httpd; import de.anomic.http.httpdFileHandler; import de.anomic.plasma.plasmaSwitchboard; import de.anomic.server.serverCore; import de.anomic.server.serverDomains; import de.anomic.server.serverInstantBusyThread; import de.anomic.server.serverObjects; import de.anomic.server.serverSwitch; import de.anomic.yacy.yacySeed; public class ConfigBasic { private static final int NEXTSTEP_FINISHED = 0; private static final int NEXTSTEP_PWD = 1; private static final int NEXTSTEP_PEERNAME = 2; private static final int NEXTSTEP_PEERPORT = 3; private static final int NEXTSTEP_RECONNECT = 4; public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) { // return variable that accumulates replacements plasmaSwitchboard sb = (plasmaSwitchboard) env; serverObjects prop = new serverObjects(); String langPath = env.getConfigPath("locale.work", "DATA/LOCALE/locales").getAbsolutePath(); String lang = env.getConfig("locale.language", "default"); int authentication = sb.adminAuthenticated(header); if (authentication < 2) { // must authenticate prop.put("AUTHENTICATE", "admin log-in"); return prop; } // starting a peer ping //boolean doPeerPing = false; if ((sb.webIndex.seedDB.mySeed().isVirgin()) || (sb.webIndex.seedDB.mySeed().isJunior())) { serverInstantBusyThread.oneTimeJob(sb.yc, "peerPing", null, 0); //doPeerPing = true; } // language settings if ((post != null) && (!(post.get("language", "default").equals(lang)))) { translator.changeLang(env, langPath, post.get("language", "default") + ".lng"); } // peer name settings String peerName = (post == null) ? env.getConfig("peerName","") : (String) post.get("peername", ""); // port settings String port = env.getConfig("port", "8080"); //this allows a low port, but it will only get one, if the user edits the config himself. if (post != null && Integer.parseInt(post.get("port")) > 1023) { port = post.get("port", "8080"); } // check if peer name already exists yacySeed oldSeed = sb.webIndex.seedDB.lookupByName(peerName); if ((oldSeed == null) && (!(env.getConfig("peerName", "").equals(peerName)))) { // the name is new boolean nameOK = Pattern.compile("[A-Za-z0-9\\-_]{3,80}").matcher(peerName).matches(); if (nameOK) env.setConfig("peerName", peerName); } // check port boolean reconnect = false; if (!env.getConfig("port", port).equals(port)) { // validate port serverCore theServerCore = (serverCore) env.getThread("10_httpd"); env.setConfig("port", port); // redirect the browser to the new port reconnect = true; String host = null; if (header.containsKey(httpHeader.HOST)) { host = header.get(httpHeader.HOST); int idx = host.indexOf(":"); if (idx != -1) host = host.substring(0,idx); } else { host = serverDomains.myPublicLocalIP().getHostAddress(); } prop.put("reconnect", "1"); prop.put("reconnect_host", host); prop.put("nextStep_host", host); prop.put("reconnect_port", port); prop.put("nextStep_port", port); prop.put("reconnect_sslSupport", theServerCore.withSSL() ? "1" : "0"); prop.put("nextStep_sslSupport", theServerCore.withSSL() ? "1" : "0"); // generate new shortcut (used for Windows) //yacyAccessible.setNewPortBat(Integer.parseInt(port)); //yacyAccessible.setNewPortLink(Integer.parseInt(port)); // force reconnection in 7 seconds theServerCore.reconnect(7000); } else { prop.put("reconnect", "0"); } // set a use case String networkName = sb.getConfig("network.unit.name", ""); if (post != null && post.containsKey("usecase")) { - if (post.get("usecase", "").equals("freeworld")) { - if (!networkName.equals("freeworld")) { - // switch to freeworld network - sb.switchNetwork("defaults/yacy.network.freeworld.unit"); - } + if (post.get("usecase", "").equals("freeworld") && !networkName.equals("freeworld")) { + // switch to freeworld network + sb.switchNetwork("defaults/yacy.network.freeworld.unit"); // switch to p2p mode sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, true); sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, true); } - if (post.get("usecase", "").equals("portal")) { - if (!networkName.equals("webportal")) { - // switch to webportal network - sb.switchNetwork("defaults/yacy.network.webportal.unit"); - } + if (post.get("usecase", "").equals("portal") && !networkName.equals("webportal")) { + // switch to webportal network + sb.switchNetwork("defaults/yacy.network.webportal.unit"); // switch to robinson mode sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, false); sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, false); } - if (post.get("usecase", "").equals("intranet")) { - if (!networkName.equals("intranet")) { - // switch to intranet network - sb.switchNetwork("defaults/yacy.network.intranet.unit"); - } + if (post.get("usecase", "").equals("intranet") && !networkName.equals("intranet")) { + // switch to intranet network + sb.switchNetwork("defaults/yacy.network.intranet.unit"); // switch to p2p mode: enable ad-hoc networks between intranet users sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, true); sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, true); } } networkName = sb.getConfig("network.unit.name", ""); if (networkName.equals("freeworld")) { prop.put("setUseCase", 1); prop.put("setUseCase_freeworldChecked", 1); } else if (networkName.equals("webportal")) { prop.put("setUseCase", 1); prop.put("setUseCase_portalChecked", 1); } else if (networkName.equals("intranet")) { prop.put("setUseCase", 1); prop.put("setUseCase_intranetChecked", 1); } else { prop.put("setUseCase", 0); } prop.put("setUseCase_port", port); // check if values are proper boolean properPassword = (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0) || sb.getConfigBool("adminAccountForLocalhost", false); boolean properName = (env.getConfig("peerName","").length() >= 3) && (!(yacySeed.isDefaultPeerName(env.getConfig("peerName","")))); boolean properPort = (sb.webIndex.seedDB.mySeed().isSenior()) || (sb.webIndex.seedDB.mySeed().isPrincipal()); if ((env.getConfig("defaultFiles", "").startsWith("ConfigBasic.html,"))) { env.setConfig("defaultFiles", env.getConfig("defaultFiles", "").substring(17)); env.setConfig("browserPopUpPage", "Status.html"); httpdFileHandler.initDefaultPath(); } prop.put("statusName", properName ? "1" : "0"); prop.put("statusPort", properPort ? "1" : "0"); if (reconnect) { prop.put("nextStep", NEXTSTEP_RECONNECT); } else if (!properName) { prop.put("nextStep", NEXTSTEP_PEERNAME); } else if (!properPassword) { prop.put("nextStep", NEXTSTEP_PWD); } else if (!properPort) { prop.put("nextStep", NEXTSTEP_PEERPORT); } else { prop.put("nextStep", NEXTSTEP_FINISHED); } // set default values prop.put("defaultName", env.getConfig("peerName", "")); prop.put("defaultPort", env.getConfig("port", "8080")); lang = env.getConfig("locale.language", "default"); // re-assign lang, may have changed if (lang.equals("default")) { prop.put("langDeutsch", "0"); prop.put("langEnglish", "1"); } else if (lang.equals("de")) { prop.put("langDeutsch", "1"); prop.put("langEnglish", "0"); } else { prop.put("langDeutsch", "0"); prop.put("langEnglish", "0"); } return prop; } }
false
true
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) { // return variable that accumulates replacements plasmaSwitchboard sb = (plasmaSwitchboard) env; serverObjects prop = new serverObjects(); String langPath = env.getConfigPath("locale.work", "DATA/LOCALE/locales").getAbsolutePath(); String lang = env.getConfig("locale.language", "default"); int authentication = sb.adminAuthenticated(header); if (authentication < 2) { // must authenticate prop.put("AUTHENTICATE", "admin log-in"); return prop; } // starting a peer ping //boolean doPeerPing = false; if ((sb.webIndex.seedDB.mySeed().isVirgin()) || (sb.webIndex.seedDB.mySeed().isJunior())) { serverInstantBusyThread.oneTimeJob(sb.yc, "peerPing", null, 0); //doPeerPing = true; } // language settings if ((post != null) && (!(post.get("language", "default").equals(lang)))) { translator.changeLang(env, langPath, post.get("language", "default") + ".lng"); } // peer name settings String peerName = (post == null) ? env.getConfig("peerName","") : (String) post.get("peername", ""); // port settings String port = env.getConfig("port", "8080"); //this allows a low port, but it will only get one, if the user edits the config himself. if (post != null && Integer.parseInt(post.get("port")) > 1023) { port = post.get("port", "8080"); } // check if peer name already exists yacySeed oldSeed = sb.webIndex.seedDB.lookupByName(peerName); if ((oldSeed == null) && (!(env.getConfig("peerName", "").equals(peerName)))) { // the name is new boolean nameOK = Pattern.compile("[A-Za-z0-9\\-_]{3,80}").matcher(peerName).matches(); if (nameOK) env.setConfig("peerName", peerName); } // check port boolean reconnect = false; if (!env.getConfig("port", port).equals(port)) { // validate port serverCore theServerCore = (serverCore) env.getThread("10_httpd"); env.setConfig("port", port); // redirect the browser to the new port reconnect = true; String host = null; if (header.containsKey(httpHeader.HOST)) { host = header.get(httpHeader.HOST); int idx = host.indexOf(":"); if (idx != -1) host = host.substring(0,idx); } else { host = serverDomains.myPublicLocalIP().getHostAddress(); } prop.put("reconnect", "1"); prop.put("reconnect_host", host); prop.put("nextStep_host", host); prop.put("reconnect_port", port); prop.put("nextStep_port", port); prop.put("reconnect_sslSupport", theServerCore.withSSL() ? "1" : "0"); prop.put("nextStep_sslSupport", theServerCore.withSSL() ? "1" : "0"); // generate new shortcut (used for Windows) //yacyAccessible.setNewPortBat(Integer.parseInt(port)); //yacyAccessible.setNewPortLink(Integer.parseInt(port)); // force reconnection in 7 seconds theServerCore.reconnect(7000); } else { prop.put("reconnect", "0"); } // set a use case String networkName = sb.getConfig("network.unit.name", ""); if (post != null && post.containsKey("usecase")) { if (post.get("usecase", "").equals("freeworld")) { if (!networkName.equals("freeworld")) { // switch to freeworld network sb.switchNetwork("defaults/yacy.network.freeworld.unit"); } // switch to p2p mode sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, true); sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, true); } if (post.get("usecase", "").equals("portal")) { if (!networkName.equals("webportal")) { // switch to webportal network sb.switchNetwork("defaults/yacy.network.webportal.unit"); } // switch to robinson mode sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, false); sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, false); } if (post.get("usecase", "").equals("intranet")) { if (!networkName.equals("intranet")) { // switch to intranet network sb.switchNetwork("defaults/yacy.network.intranet.unit"); } // switch to p2p mode: enable ad-hoc networks between intranet users sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, true); sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, true); } } networkName = sb.getConfig("network.unit.name", ""); if (networkName.equals("freeworld")) { prop.put("setUseCase", 1); prop.put("setUseCase_freeworldChecked", 1); } else if (networkName.equals("webportal")) { prop.put("setUseCase", 1); prop.put("setUseCase_portalChecked", 1); } else if (networkName.equals("intranet")) { prop.put("setUseCase", 1); prop.put("setUseCase_intranetChecked", 1); } else { prop.put("setUseCase", 0); } prop.put("setUseCase_port", port); // check if values are proper boolean properPassword = (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0) || sb.getConfigBool("adminAccountForLocalhost", false); boolean properName = (env.getConfig("peerName","").length() >= 3) && (!(yacySeed.isDefaultPeerName(env.getConfig("peerName","")))); boolean properPort = (sb.webIndex.seedDB.mySeed().isSenior()) || (sb.webIndex.seedDB.mySeed().isPrincipal()); if ((env.getConfig("defaultFiles", "").startsWith("ConfigBasic.html,"))) { env.setConfig("defaultFiles", env.getConfig("defaultFiles", "").substring(17)); env.setConfig("browserPopUpPage", "Status.html"); httpdFileHandler.initDefaultPath(); } prop.put("statusName", properName ? "1" : "0"); prop.put("statusPort", properPort ? "1" : "0"); if (reconnect) { prop.put("nextStep", NEXTSTEP_RECONNECT); } else if (!properName) { prop.put("nextStep", NEXTSTEP_PEERNAME); } else if (!properPassword) { prop.put("nextStep", NEXTSTEP_PWD); } else if (!properPort) { prop.put("nextStep", NEXTSTEP_PEERPORT); } else { prop.put("nextStep", NEXTSTEP_FINISHED); } // set default values prop.put("defaultName", env.getConfig("peerName", "")); prop.put("defaultPort", env.getConfig("port", "8080")); lang = env.getConfig("locale.language", "default"); // re-assign lang, may have changed if (lang.equals("default")) { prop.put("langDeutsch", "0"); prop.put("langEnglish", "1"); } else if (lang.equals("de")) { prop.put("langDeutsch", "1"); prop.put("langEnglish", "0"); } else { prop.put("langDeutsch", "0"); prop.put("langEnglish", "0"); } return prop; }
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) { // return variable that accumulates replacements plasmaSwitchboard sb = (plasmaSwitchboard) env; serverObjects prop = new serverObjects(); String langPath = env.getConfigPath("locale.work", "DATA/LOCALE/locales").getAbsolutePath(); String lang = env.getConfig("locale.language", "default"); int authentication = sb.adminAuthenticated(header); if (authentication < 2) { // must authenticate prop.put("AUTHENTICATE", "admin log-in"); return prop; } // starting a peer ping //boolean doPeerPing = false; if ((sb.webIndex.seedDB.mySeed().isVirgin()) || (sb.webIndex.seedDB.mySeed().isJunior())) { serverInstantBusyThread.oneTimeJob(sb.yc, "peerPing", null, 0); //doPeerPing = true; } // language settings if ((post != null) && (!(post.get("language", "default").equals(lang)))) { translator.changeLang(env, langPath, post.get("language", "default") + ".lng"); } // peer name settings String peerName = (post == null) ? env.getConfig("peerName","") : (String) post.get("peername", ""); // port settings String port = env.getConfig("port", "8080"); //this allows a low port, but it will only get one, if the user edits the config himself. if (post != null && Integer.parseInt(post.get("port")) > 1023) { port = post.get("port", "8080"); } // check if peer name already exists yacySeed oldSeed = sb.webIndex.seedDB.lookupByName(peerName); if ((oldSeed == null) && (!(env.getConfig("peerName", "").equals(peerName)))) { // the name is new boolean nameOK = Pattern.compile("[A-Za-z0-9\\-_]{3,80}").matcher(peerName).matches(); if (nameOK) env.setConfig("peerName", peerName); } // check port boolean reconnect = false; if (!env.getConfig("port", port).equals(port)) { // validate port serverCore theServerCore = (serverCore) env.getThread("10_httpd"); env.setConfig("port", port); // redirect the browser to the new port reconnect = true; String host = null; if (header.containsKey(httpHeader.HOST)) { host = header.get(httpHeader.HOST); int idx = host.indexOf(":"); if (idx != -1) host = host.substring(0,idx); } else { host = serverDomains.myPublicLocalIP().getHostAddress(); } prop.put("reconnect", "1"); prop.put("reconnect_host", host); prop.put("nextStep_host", host); prop.put("reconnect_port", port); prop.put("nextStep_port", port); prop.put("reconnect_sslSupport", theServerCore.withSSL() ? "1" : "0"); prop.put("nextStep_sslSupport", theServerCore.withSSL() ? "1" : "0"); // generate new shortcut (used for Windows) //yacyAccessible.setNewPortBat(Integer.parseInt(port)); //yacyAccessible.setNewPortLink(Integer.parseInt(port)); // force reconnection in 7 seconds theServerCore.reconnect(7000); } else { prop.put("reconnect", "0"); } // set a use case String networkName = sb.getConfig("network.unit.name", ""); if (post != null && post.containsKey("usecase")) { if (post.get("usecase", "").equals("freeworld") && !networkName.equals("freeworld")) { // switch to freeworld network sb.switchNetwork("defaults/yacy.network.freeworld.unit"); // switch to p2p mode sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, true); sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, true); } if (post.get("usecase", "").equals("portal") && !networkName.equals("webportal")) { // switch to webportal network sb.switchNetwork("defaults/yacy.network.webportal.unit"); // switch to robinson mode sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, false); sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, false); } if (post.get("usecase", "").equals("intranet") && !networkName.equals("intranet")) { // switch to intranet network sb.switchNetwork("defaults/yacy.network.intranet.unit"); // switch to p2p mode: enable ad-hoc networks between intranet users sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, true); sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, true); } } networkName = sb.getConfig("network.unit.name", ""); if (networkName.equals("freeworld")) { prop.put("setUseCase", 1); prop.put("setUseCase_freeworldChecked", 1); } else if (networkName.equals("webportal")) { prop.put("setUseCase", 1); prop.put("setUseCase_portalChecked", 1); } else if (networkName.equals("intranet")) { prop.put("setUseCase", 1); prop.put("setUseCase_intranetChecked", 1); } else { prop.put("setUseCase", 0); } prop.put("setUseCase_port", port); // check if values are proper boolean properPassword = (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0) || sb.getConfigBool("adminAccountForLocalhost", false); boolean properName = (env.getConfig("peerName","").length() >= 3) && (!(yacySeed.isDefaultPeerName(env.getConfig("peerName","")))); boolean properPort = (sb.webIndex.seedDB.mySeed().isSenior()) || (sb.webIndex.seedDB.mySeed().isPrincipal()); if ((env.getConfig("defaultFiles", "").startsWith("ConfigBasic.html,"))) { env.setConfig("defaultFiles", env.getConfig("defaultFiles", "").substring(17)); env.setConfig("browserPopUpPage", "Status.html"); httpdFileHandler.initDefaultPath(); } prop.put("statusName", properName ? "1" : "0"); prop.put("statusPort", properPort ? "1" : "0"); if (reconnect) { prop.put("nextStep", NEXTSTEP_RECONNECT); } else if (!properName) { prop.put("nextStep", NEXTSTEP_PEERNAME); } else if (!properPassword) { prop.put("nextStep", NEXTSTEP_PWD); } else if (!properPort) { prop.put("nextStep", NEXTSTEP_PEERPORT); } else { prop.put("nextStep", NEXTSTEP_FINISHED); } // set default values prop.put("defaultName", env.getConfig("peerName", "")); prop.put("defaultPort", env.getConfig("port", "8080")); lang = env.getConfig("locale.language", "default"); // re-assign lang, may have changed if (lang.equals("default")) { prop.put("langDeutsch", "0"); prop.put("langEnglish", "1"); } else if (lang.equals("de")) { prop.put("langDeutsch", "1"); prop.put("langEnglish", "0"); } else { prop.put("langDeutsch", "0"); prop.put("langEnglish", "0"); } return prop; }
diff --git a/src/main/java/net/codestory/http/filters/twitter/TwitterAuthFilter.java b/src/main/java/net/codestory/http/filters/twitter/TwitterAuthFilter.java index 99baa61..802c1ab 100644 --- a/src/main/java/net/codestory/http/filters/twitter/TwitterAuthFilter.java +++ b/src/main/java/net/codestory/http/filters/twitter/TwitterAuthFilter.java @@ -1,105 +1,105 @@ /** * Copyright (C) 2013 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package net.codestory.http.filters.twitter; import java.io.*; import java.net.*; import net.codestory.http.filters.*; import org.simpleframework.http.*; import org.simpleframework.http.Query; import twitter4j.*; import twitter4j.conf.*; public class TwitterAuthFilter implements Filter { private final String siteUri; private final String uriPrefix; private final Authenticator twitterAuthenticator; public TwitterAuthFilter(String siteUri, String uriPrefix, String oAuthKey, String oAuthSecret) { this.siteUri = siteUri; this.uriPrefix = validPrefix(uriPrefix); this.twitterAuthenticator = createAuthenticator(oAuthKey, oAuthSecret); } private static String validPrefix(String prefix) { return prefix.endsWith("/") ? prefix : prefix + "/"; } private static Authenticator createAuthenticator(String oAuthKey, String oAuthSecret) { Configuration config = new ConfigurationBuilder() .setOAuthConsumerKey(oAuthKey) .setOAuthConsumerSecret(oAuthSecret) .build(); TwitterFactory twitterFactory = new TwitterFactory(config); return new TwitterAuthenticator(twitterFactory); } @Override public boolean apply(String uri, Request request, Response response) throws IOException { if (!uri.startsWith(uriPrefix)) { return false; // Ignore } if (uri.equals(uriPrefix + "authenticate")) { User user; try { Query query = request.getQuery(); String oauth_token = query.get("oauth_token"); String oauth_verifier = query.get("oauth_verifier"); user = twitterAuthenticator.authenticate(oauth_token, oauth_verifier); } catch (Exception e) { response.setCode(403); return true; } response.setCookie(new Cookie("userId", user.getId().toString(), "/", true)); - response.setValue("Location", "/test/"); + response.setValue("Location", uriPrefix); response.setCode(303); response.setContentLength(0); return true; } - if (uri.equals("/test/logout")) { + if (uri.equals(uriPrefix + "logout")) { response.setCookie(new Cookie("userId", "", "/", false)); - response.setValue("Location", "/test/"); + response.setValue("Location", "/"); response.setCode(303); response.setContentLength(0); return true; } Cookie userId = request.getCookie("userId"); if ((userId != null) && !userId.getValue().isEmpty()) { return false; // Authenticated } String callbackUri = siteUri + uriPrefix + "authenticate"; URI authenticateURI = twitterAuthenticator.getAuthenticateURI(callbackUri); response.setValue("Location", authenticateURI.toString()); response.setCode(303); response.setContentLength(0); return true; } }
false
true
public boolean apply(String uri, Request request, Response response) throws IOException { if (!uri.startsWith(uriPrefix)) { return false; // Ignore } if (uri.equals(uriPrefix + "authenticate")) { User user; try { Query query = request.getQuery(); String oauth_token = query.get("oauth_token"); String oauth_verifier = query.get("oauth_verifier"); user = twitterAuthenticator.authenticate(oauth_token, oauth_verifier); } catch (Exception e) { response.setCode(403); return true; } response.setCookie(new Cookie("userId", user.getId().toString(), "/", true)); response.setValue("Location", "/test/"); response.setCode(303); response.setContentLength(0); return true; } if (uri.equals("/test/logout")) { response.setCookie(new Cookie("userId", "", "/", false)); response.setValue("Location", "/test/"); response.setCode(303); response.setContentLength(0); return true; } Cookie userId = request.getCookie("userId"); if ((userId != null) && !userId.getValue().isEmpty()) { return false; // Authenticated } String callbackUri = siteUri + uriPrefix + "authenticate"; URI authenticateURI = twitterAuthenticator.getAuthenticateURI(callbackUri); response.setValue("Location", authenticateURI.toString()); response.setCode(303); response.setContentLength(0); return true; }
public boolean apply(String uri, Request request, Response response) throws IOException { if (!uri.startsWith(uriPrefix)) { return false; // Ignore } if (uri.equals(uriPrefix + "authenticate")) { User user; try { Query query = request.getQuery(); String oauth_token = query.get("oauth_token"); String oauth_verifier = query.get("oauth_verifier"); user = twitterAuthenticator.authenticate(oauth_token, oauth_verifier); } catch (Exception e) { response.setCode(403); return true; } response.setCookie(new Cookie("userId", user.getId().toString(), "/", true)); response.setValue("Location", uriPrefix); response.setCode(303); response.setContentLength(0); return true; } if (uri.equals(uriPrefix + "logout")) { response.setCookie(new Cookie("userId", "", "/", false)); response.setValue("Location", "/"); response.setCode(303); response.setContentLength(0); return true; } Cookie userId = request.getCookie("userId"); if ((userId != null) && !userId.getValue().isEmpty()) { return false; // Authenticated } String callbackUri = siteUri + uriPrefix + "authenticate"; URI authenticateURI = twitterAuthenticator.getAuthenticateURI(callbackUri); response.setValue("Location", authenticateURI.toString()); response.setCode(303); response.setContentLength(0); return true; }
diff --git a/app/controllers/DisplayController.java b/app/controllers/DisplayController.java index 3327fbe..705ed7a 100644 --- a/app/controllers/DisplayController.java +++ b/app/controllers/DisplayController.java @@ -1,191 +1,193 @@ package controllers; import java.util.HashMap; import java.util.Map; import models.Display; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.node.ObjectNode; import play.Logger; import play.data.Form; import play.libs.F.Callback; import play.libs.F.Callback0; import play.mvc.BodyParser; import play.mvc.BodyParser.Json; import play.mvc.Controller; import play.mvc.Result; import play.mvc.WebSocket; public class DisplayController extends Controller { public static HashMap<String, WebSocket.Out<JsonNode>> activeDisplays = new HashMap<String, WebSocket.Out<JsonNode>>(); public static HashMap<WebSocket.Out<JsonNode>, String> outToID = new HashMap<WebSocket.Out<JsonNode>, String>(); /** * Prepare the display with the tiles selected during * the layout creation * @param displayID * @return */ public static Result setupDisplay(String displayID) { // if(!activeDisplays.containsKey(displayID)){ Display display = Display.get(new Long(displayID)); String name = display.name; activeDisplays.put(displayID, null); return ok(views.html.display.render(displayID,name)); // } else { // return ok("SORRY, DISPLAY ID " + displayID + " IS ALREADY ACTIVE"); // } } @BodyParser.Of(Json.class) public static Result updateDisplayInformations(){ JsonNode json = request().body().asJson(); if(json == null) { return badRequest("Expecting Json data"); } else { String kind = json.get("kind").asText(); ObjectNode result = play.libs.Json.newObject(); if(kind.equals("linking")){ Long layoutid = new Long(json.get("layoutid").asText()); Long currentSelected =new Long(json.get("currentSelected").asText()); Display.updateLayout(layoutid, currentSelected); result.put("layoutid", layoutid); result.put("currentSelected", currentSelected); return ok(result); } else if(kind.equals("update")){ Long displayid = json.get("displayid").asLong(); String name = json.get("name").asText(); Float latitude = new Float(json.get("latitude").asText()); Float longitude = new Float(json.get("longitude").asText()); Display clone = (Display) Display.find.byId(displayid)._ebean_createCopy(); clone.name = name; clone.latitude = latitude; clone.longitude = longitude; Display.delete(displayid); Display.addNew(clone); result.put("id", clone.id); result.put("name", clone.name); result.put("latitude", clone.latitude); result.put("longitude", clone.longitude); return ok(result); } } return badRequest(); } @BodyParser.Of(Json.class) public static Result removeDisplay(){ JsonNode json = request().body().asJson(); if(json == null) { return badRequest("Expecting Json data"); } else { Long currentSelected =new Long(json.get("currentSelected").asText()); Display.delete(currentSelected); ObjectNode result = play.libs.Json.newObject(); result.put("removedid", currentSelected); return ok(result); } } @BodyParser.Of(Json.class) public static Result newDisplay(){ JsonNode json = request().body().asJson(); if(json == null) { return badRequest("Expecting Json data"); } else { Logger.info(json.toString()); String name = json.get("name").asText(); String latitude = json.get("latitude").asText(); String longitude = json.get("longitude").asText(); Form<Display> filledForm = form(Display.class); Map<String,String> anyData = new HashMap<String, String>(); anyData.put("name", name); anyData.put("latitude", latitude); anyData.put("longitude", longitude); Logger.info(anyData.toString()); Display display = filledForm.bind(anyData).get(); Display res = Display.addNew(display); ObjectNode result = play.libs.Json.newObject(); result.put("id", res.id); result.put("name", name); result.put("latitude", latitude); result.put("longitude", longitude); return ok(result); } } public static WebSocket<JsonNode> webSocket() { return new WebSocket<JsonNode>() { @Override public void onReady(WebSocket.In<JsonNode> in, final WebSocket.Out<JsonNode> out) { in.onMessage(new Callback<JsonNode>() { public void invoke(JsonNode event) { Logger.info(event.toString()); String kind = event.get("kind").asText(); String displayID = event.get("displayID").asText(); if(kind.equals("newScreen")){ activeDisplays.put(displayID, out); outToID.put(out, displayID); Logger.info("Display " + displayID + " is now active."); } // Mobile wants to get what's on the screen else if(kind.equals("getRequest")){ Out<JsonNode> displayOut = activeDisplays.get(displayID); ObjectNode request = play.libs.Json.newObject(); request.put("kind", "actives"); displayOut.write(request); + } else if (kind.equals("actives")){ + Logger.info("ACTIVES!!!!!"); } } }); // When the socket is closed. in.onClose(new Callback0() { public void invoke() { String displayID = outToID.get(out); outToID.remove(out); activeDisplays.remove(displayID); Logger.info( "\n ******* MESSAGE RECIEVED *******" + "\n Display " + displayID + "is now disconnected." + "\n*********************************" ); } }); } }; } }
true
true
public static WebSocket<JsonNode> webSocket() { return new WebSocket<JsonNode>() { @Override public void onReady(WebSocket.In<JsonNode> in, final WebSocket.Out<JsonNode> out) { in.onMessage(new Callback<JsonNode>() { public void invoke(JsonNode event) { Logger.info(event.toString()); String kind = event.get("kind").asText(); String displayID = event.get("displayID").asText(); if(kind.equals("newScreen")){ activeDisplays.put(displayID, out); outToID.put(out, displayID); Logger.info("Display " + displayID + " is now active."); } // Mobile wants to get what's on the screen else if(kind.equals("getRequest")){ Out<JsonNode> displayOut = activeDisplays.get(displayID); ObjectNode request = play.libs.Json.newObject(); request.put("kind", "actives"); displayOut.write(request); } } }); // When the socket is closed. in.onClose(new Callback0() { public void invoke() { String displayID = outToID.get(out); outToID.remove(out); activeDisplays.remove(displayID); Logger.info( "\n ******* MESSAGE RECIEVED *******" + "\n Display " + displayID + "is now disconnected." + "\n*********************************" ); } }); } }; }
public static WebSocket<JsonNode> webSocket() { return new WebSocket<JsonNode>() { @Override public void onReady(WebSocket.In<JsonNode> in, final WebSocket.Out<JsonNode> out) { in.onMessage(new Callback<JsonNode>() { public void invoke(JsonNode event) { Logger.info(event.toString()); String kind = event.get("kind").asText(); String displayID = event.get("displayID").asText(); if(kind.equals("newScreen")){ activeDisplays.put(displayID, out); outToID.put(out, displayID); Logger.info("Display " + displayID + " is now active."); } // Mobile wants to get what's on the screen else if(kind.equals("getRequest")){ Out<JsonNode> displayOut = activeDisplays.get(displayID); ObjectNode request = play.libs.Json.newObject(); request.put("kind", "actives"); displayOut.write(request); } else if (kind.equals("actives")){ Logger.info("ACTIVES!!!!!"); } } }); // When the socket is closed. in.onClose(new Callback0() { public void invoke() { String displayID = outToID.get(out); outToID.remove(out); activeDisplays.remove(displayID); Logger.info( "\n ******* MESSAGE RECIEVED *******" + "\n Display " + displayID + "is now disconnected." + "\n*********************************" ); } }); } }; }
diff --git a/wagon-providers/wagon-webdav/src/main/java/org/apache/maven/wagon/providers/webdav/WebDavWagon.java b/wagon-providers/wagon-webdav/src/main/java/org/apache/maven/wagon/providers/webdav/WebDavWagon.java index 4f6133c1..9d2bbceb 100644 --- a/wagon-providers/wagon-webdav/src/main/java/org/apache/maven/wagon/providers/webdav/WebDavWagon.java +++ b/wagon-providers/wagon-webdav/src/main/java/org/apache/maven/wagon/providers/webdav/WebDavWagon.java @@ -1,552 +1,552 @@ package org.apache.maven.wagon.providers.webdav; /* * Copyright 2001-2006 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Properties; import java.util.TimeZone; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpURL; import org.apache.commons.httpclient.HttpsURL; import org.apache.commons.httpclient.URIException; import org.apache.maven.wagon.AbstractWagon; import org.apache.maven.wagon.ConnectionException; import org.apache.maven.wagon.LazyFileOutputStream; import org.apache.maven.wagon.PathUtils; import org.apache.maven.wagon.ResourceDoesNotExistException; import org.apache.maven.wagon.TransferFailedException; import org.apache.maven.wagon.authentication.AuthenticationException; import org.apache.maven.wagon.authorization.AuthorizationException; import org.apache.maven.wagon.events.TransferEvent; import org.apache.maven.wagon.repository.Repository; import org.apache.maven.wagon.resource.Resource; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.StringUtils; /** * <p>WebDavWagon</p> * * <p>Allows using a webdav remote repository for downloads and deployments</p> * * <p>TODO: webdav https server is not tested</p> * * @author <a href="mailto:[email protected]">Henry Isidro</a> * @author <a href="mailto:[email protected]">Joakim Erdfelt</a> */ public class WebDavWagon extends AbstractWagon { private static final TimeZone GMT_TIME_ZONE = TimeZone.getTimeZone( "GMT" ); private CorrectedWebdavResource wdresource; private static String WAGON_VERSION; public WebDavWagon() { if ( WAGON_VERSION == null ) { URL pomUrl = this.getClass() .getResource( "/META-INF/maven/org.apache.maven.wagon/wagon-webdav/pom.properties" ); if ( pomUrl == null ) { WAGON_VERSION = ""; } else { Properties props = new Properties(); try { props.load( pomUrl.openStream() ); WAGON_VERSION = props.getProperty( "version" ); System.out.println( "WAGON_VERSION: " + WAGON_VERSION ); } catch ( IOException e ) { WAGON_VERSION = ""; } } } } /** * Opens a connection via web-dav resource * * @throws AuthenticationException * @throws ConnectionException */ public void openConnection() throws AuthenticationException, ConnectionException { String url = getURL( repository ); repository.setUrl( url ); HttpURL httpURL = null; try { httpURL = urlToHttpURL( url ); if ( authenticationInfo != null ) { String userName = authenticationInfo.getUserName(); String password = authenticationInfo.getPassword(); if ( userName != null && password != null ) httpURL.setUserinfo( userName, password ); } CorrectedWebdavResource.setDefaultAction( CorrectedWebdavResource.NOACTION ); wdresource = new CorrectedWebdavResource( httpURL ); } catch ( HttpException he ) { throw new ConnectionException( "Connection Exception: " + url + " " + he.getReasonCode() + " " + HttpStatus.getStatusText( he.getReasonCode() ) ); } catch ( URIException urie ) { throw new ConnectionException( "Connection Exception: " + urie.getReason(), urie ); } catch ( IOException ioe ) { throw new ConnectionException( "Connection Exception: " + ioe.getMessage(), ioe ); } } /** * Closes the connection * * @throws ConnectionException */ public void closeConnection() throws ConnectionException { try { if ( wdresource != null ) { wdresource.close(); } } catch ( IOException ioe ) { throw new ConnectionException( "Connection Exception: " + ioe.getMessage() ); } finally { wdresource = null; } } /** * Puts a file into the remote repository * * @param source the file to transfer * @param resourceName the name of the resource * @throws TransferFailedException * @throws ResourceDoesNotExistException * @throws AuthorizationException */ public void put( File source, String resourceName ) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { Repository repository = getRepository(); String basedir = repository.getBasedir(); resourceName = StringUtils.replace( resourceName, "\\", "/" ); String dir = PathUtils.dirname( resourceName ); dir = StringUtils.replace( dir, "\\", "/" ); String dest = repository.getUrl(); Resource resource = new Resource( resourceName ); if ( dest.endsWith( "/" ) ) { dest = dest + resource.getName(); } else { dest = dest + "/" + resource.getName(); } firePutInitiated( resource, source ); String oldpath = wdresource.getPath(); String relpath = getPath( basedir, dir ); try { // Test if dest resource path exist. String cdpath = checkUri( relpath + "/" ); wdresource.setPath( cdpath ); if ( wdresource.exists() && !wdresource.isCollection() ) { throw new TransferFailedException( "Destination path exists and is not a WebDAV collection (directory): " + cdpath ); } wdresource.setPath( oldpath ); // if dest resource path does not exist, create it if ( !wdresource.exists() ) { - // mkcolMethod() cannot create a directory heirarchy at once, + // mkcolMethod() cannot create a directory hierarchy at once, // it has to create each directory one at a time try { String[] dirs = relpath.split( "/" ); String create_dir = ""; // start at 1 because first element of dirs[] from split() is "" for ( int count = 1; count < dirs.length; count++ ) { create_dir = create_dir + "/" + dirs[count]; wdresource.mkcolMethod( create_dir ); } wdresource.setPath( oldpath ); } catch ( IOException ioe ) { throw new TransferFailedException( "Failed to create destination WebDAV collection (directory): " + relpath ); } } } catch ( IOException e ) { throw new TransferFailedException( "Failed to create destination WebDAV collection (directory): " + relpath ); } try { // Put source into destination path. firePutStarted( resource, source ); InputStream is = new PutInputStream( source, resource, this, getTransferEventSupport() ); boolean success = wdresource.putMethod( dest, is, (int) source.length() ); int statusCode = wdresource.getStatusCode(); switch ( statusCode ) { case HttpStatus.SC_OK: break; case HttpStatus.SC_CREATED: break; case HttpStatus.SC_FORBIDDEN: throw new AuthorizationException( "Access denided to: " + dest ); case HttpStatus.SC_NOT_FOUND: throw new ResourceDoesNotExistException( "File: " + dest + " does not exist" ); case HttpStatus.SC_LENGTH_REQUIRED: throw new ResourceDoesNotExistException( "Transfer failed, server requires Content-Length." ); //add more entries here default: if ( !success ) { throw new TransferFailedException( "Failed to transfer file: " + dest + ". Return code is: " + statusCode + " " + HttpStatus.getStatusText( statusCode ) ); } } } catch ( FileNotFoundException e ) { throw new TransferFailedException( "Specified source file does not exist: " + source, e ); } catch ( IOException e ) { fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); String msg = "PUT request for: " + resource + " to " + source.getName() + " failed"; throw new TransferFailedException( msg, e ); } firePutCompleted( resource, source ); } /** * Converts a String url to an HttpURL * * @param url String url to conver to an HttpURL * @return an HttpURL object created from the String url * @throws URIException */ private HttpURL urlToHttpURL( String url ) throws URIException { return url.startsWith( "https" ) ? new HttpsURL( url ) : new HttpURL( url ); } /** * Determine which URI to use at the prompt. * * @param uri the path to be set. * @return the absolute path. */ private String checkUri( String uri ) throws IOException { if ( wdresource == null ) { throw new IOException( "Not connected yet." ); } if ( uri == null ) { uri = wdresource.getPath(); } return FileUtils.normalize( uri ); } public void get( String resourceName, File destination ) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { get( resourceName, destination, 0 ); } public boolean getIfNewer( String resourceName, File destination, long timestamp ) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { return get( resourceName, destination, timestamp ); } /** * Get a file from remote server * * @param resourceName * @param destination * @param timestamp the timestamp to check against, only downloading if newer. If <code>0</code>, always download * @return <code>true</code> if newer version was downloaded, <code>false</code> otherwise. * @throws TransferFailedException * @throws ResourceDoesNotExistException * @throws AuthorizationException */ public boolean get( String resourceName, File destination, long timestamp ) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { Resource resource = new Resource( resourceName ); fireGetInitiated( resource, destination ); String url = getRepository().getUrl() + "/" + resourceName; wdresource.addRequestHeader( "X-wagon-provider", "wagon-webdav" ); wdresource.addRequestHeader( "X-wagon-version", WAGON_VERSION ); wdresource.addRequestHeader( "Cache-control", "no-cache" ); wdresource.addRequestHeader( "Cache-store", "no-store" ); wdresource.addRequestHeader( "Pragma", "no-cache" ); wdresource.addRequestHeader( "Expires", "0" ); if ( timestamp > 0 ) { SimpleDateFormat fmt = new SimpleDateFormat( "EEE, dd-MMM-yy HH:mm:ss zzz", Locale.US ); fmt.setTimeZone( GMT_TIME_ZONE ); wdresource.addRequestHeader( "If-Modified-Since", fmt.format( new Date( timestamp ) ) ); } InputStream is = null; OutputStream output = new LazyFileOutputStream( destination ); try { is = wdresource.getMethodData( url ); getTransfer( resource, destination, is ); } catch ( HttpException e ) { fireTransferError( resource, e, TransferEvent.REQUEST_GET ); throw new TransferFailedException( "Failed to transfer file: " + url + ". Return code is: " + e.getReasonCode(), e ); } catch ( IOException e ) { fireTransferError( resource, e, TransferEvent.REQUEST_GET ); if ( destination.exists() ) { boolean deleted = destination.delete(); if ( !deleted ) { destination.deleteOnExit(); } } int statusCode = wdresource.getStatusCode(); switch ( statusCode ) { case HttpStatus.SC_NOT_MODIFIED: return false; case HttpStatus.SC_FORBIDDEN: throw new AuthorizationException( "Access denied to: " + url ); case HttpStatus.SC_UNAUTHORIZED: throw new AuthorizationException( "Not authorized." ); case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED: throw new AuthorizationException( "Not authorized by proxy." ); case HttpStatus.SC_NOT_FOUND: throw new ResourceDoesNotExistException( "File: " + url + " does not exist" ); default: throw new TransferFailedException( "Failed to transfer file: " + url + ". Return code is: " + statusCode ); } } finally { IOUtil.close( is ); IOUtil.close( output ); } int statusCode = wdresource.getStatusCode(); switch ( statusCode ) { case HttpStatus.SC_OK: return true; case HttpStatus.SC_NOT_MODIFIED: return false; case HttpStatus.SC_FORBIDDEN: throw new AuthorizationException( "Access denided to: " + url ); case HttpStatus.SC_UNAUTHORIZED: throw new AuthorizationException( "Not authorized." ); case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED: throw new AuthorizationException( "Not authorized by proxy." ); case HttpStatus.SC_NOT_FOUND: throw new ResourceDoesNotExistException( "File: " + url + " does not exist" ); default: throw new TransferFailedException( "Failed to transfer file: " + url + ". Return code is: " + statusCode ); } } private String getURL( Repository repository ) { String url = repository.getUrl(); if ( url.startsWith( "dav:" ) ) { return url.substring( 4 ); } else { return url; } } /** * This wagon supports directory copying * * @return <code>true</code> always */ public boolean supportsDirectoryCopy() { return true; } /** * Copy a directory from local system to remote webdav server * * @param sourceDirectory the local directory * @param destinationDirectory the remote destination * @throws TransferFailedException * @throws ResourceDoesNotExistException * @throws AuthorizationException */ public void putDirectory( File sourceDirectory, String destinationDirectory ) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { String createPath = repository.getBasedir() + "/" + destinationDirectory; try { wdresource.mkcolMethod( createPath ); } catch (IOException e) { throw new TransferFailedException( "Failed to create remote directory: " + createPath + " : " + e.getMessage(), e ); } try { wdresource.setPath( repository.getBasedir() ); } catch (IOException e) { throw new TransferFailedException( "An error occurred while preparing to copy to remote repository: " + e.getMessage(), e ); } File [] list_files = sourceDirectory.listFiles(); for(int i=0; i<list_files.length; i++) { if ( list_files[i].isDirectory() ) { putDirectory( list_files[i], destinationDirectory + "/" + list_files[i].getName() ); } else { String target = createPath + "/" + list_files[i].getName(); try { wdresource.putMethod( target, list_files[i] ); } catch( IOException e ) { throw new TransferFailedException( "Failed to upload to remote repository: " + target + " : " + e.getMessage(), e ); } } } } }
true
true
public void put( File source, String resourceName ) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { Repository repository = getRepository(); String basedir = repository.getBasedir(); resourceName = StringUtils.replace( resourceName, "\\", "/" ); String dir = PathUtils.dirname( resourceName ); dir = StringUtils.replace( dir, "\\", "/" ); String dest = repository.getUrl(); Resource resource = new Resource( resourceName ); if ( dest.endsWith( "/" ) ) { dest = dest + resource.getName(); } else { dest = dest + "/" + resource.getName(); } firePutInitiated( resource, source ); String oldpath = wdresource.getPath(); String relpath = getPath( basedir, dir ); try { // Test if dest resource path exist. String cdpath = checkUri( relpath + "/" ); wdresource.setPath( cdpath ); if ( wdresource.exists() && !wdresource.isCollection() ) { throw new TransferFailedException( "Destination path exists and is not a WebDAV collection (directory): " + cdpath ); } wdresource.setPath( oldpath ); // if dest resource path does not exist, create it if ( !wdresource.exists() ) { // mkcolMethod() cannot create a directory heirarchy at once, // it has to create each directory one at a time try { String[] dirs = relpath.split( "/" ); String create_dir = ""; // start at 1 because first element of dirs[] from split() is "" for ( int count = 1; count < dirs.length; count++ ) { create_dir = create_dir + "/" + dirs[count]; wdresource.mkcolMethod( create_dir ); } wdresource.setPath( oldpath ); } catch ( IOException ioe ) { throw new TransferFailedException( "Failed to create destination WebDAV collection (directory): " + relpath ); } } } catch ( IOException e ) { throw new TransferFailedException( "Failed to create destination WebDAV collection (directory): " + relpath ); } try { // Put source into destination path. firePutStarted( resource, source ); InputStream is = new PutInputStream( source, resource, this, getTransferEventSupport() ); boolean success = wdresource.putMethod( dest, is, (int) source.length() ); int statusCode = wdresource.getStatusCode(); switch ( statusCode ) { case HttpStatus.SC_OK: break; case HttpStatus.SC_CREATED: break; case HttpStatus.SC_FORBIDDEN: throw new AuthorizationException( "Access denided to: " + dest ); case HttpStatus.SC_NOT_FOUND: throw new ResourceDoesNotExistException( "File: " + dest + " does not exist" ); case HttpStatus.SC_LENGTH_REQUIRED: throw new ResourceDoesNotExistException( "Transfer failed, server requires Content-Length." ); //add more entries here default: if ( !success ) { throw new TransferFailedException( "Failed to transfer file: " + dest + ". Return code is: " + statusCode + " " + HttpStatus.getStatusText( statusCode ) ); } } } catch ( FileNotFoundException e ) { throw new TransferFailedException( "Specified source file does not exist: " + source, e ); } catch ( IOException e ) { fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); String msg = "PUT request for: " + resource + " to " + source.getName() + " failed"; throw new TransferFailedException( msg, e ); } firePutCompleted( resource, source ); }
public void put( File source, String resourceName ) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { Repository repository = getRepository(); String basedir = repository.getBasedir(); resourceName = StringUtils.replace( resourceName, "\\", "/" ); String dir = PathUtils.dirname( resourceName ); dir = StringUtils.replace( dir, "\\", "/" ); String dest = repository.getUrl(); Resource resource = new Resource( resourceName ); if ( dest.endsWith( "/" ) ) { dest = dest + resource.getName(); } else { dest = dest + "/" + resource.getName(); } firePutInitiated( resource, source ); String oldpath = wdresource.getPath(); String relpath = getPath( basedir, dir ); try { // Test if dest resource path exist. String cdpath = checkUri( relpath + "/" ); wdresource.setPath( cdpath ); if ( wdresource.exists() && !wdresource.isCollection() ) { throw new TransferFailedException( "Destination path exists and is not a WebDAV collection (directory): " + cdpath ); } wdresource.setPath( oldpath ); // if dest resource path does not exist, create it if ( !wdresource.exists() ) { // mkcolMethod() cannot create a directory hierarchy at once, // it has to create each directory one at a time try { String[] dirs = relpath.split( "/" ); String create_dir = ""; // start at 1 because first element of dirs[] from split() is "" for ( int count = 1; count < dirs.length; count++ ) { create_dir = create_dir + "/" + dirs[count]; wdresource.mkcolMethod( create_dir ); } wdresource.setPath( oldpath ); } catch ( IOException ioe ) { throw new TransferFailedException( "Failed to create destination WebDAV collection (directory): " + relpath ); } } } catch ( IOException e ) { throw new TransferFailedException( "Failed to create destination WebDAV collection (directory): " + relpath ); } try { // Put source into destination path. firePutStarted( resource, source ); InputStream is = new PutInputStream( source, resource, this, getTransferEventSupport() ); boolean success = wdresource.putMethod( dest, is, (int) source.length() ); int statusCode = wdresource.getStatusCode(); switch ( statusCode ) { case HttpStatus.SC_OK: break; case HttpStatus.SC_CREATED: break; case HttpStatus.SC_FORBIDDEN: throw new AuthorizationException( "Access denided to: " + dest ); case HttpStatus.SC_NOT_FOUND: throw new ResourceDoesNotExistException( "File: " + dest + " does not exist" ); case HttpStatus.SC_LENGTH_REQUIRED: throw new ResourceDoesNotExistException( "Transfer failed, server requires Content-Length." ); //add more entries here default: if ( !success ) { throw new TransferFailedException( "Failed to transfer file: " + dest + ". Return code is: " + statusCode + " " + HttpStatus.getStatusText( statusCode ) ); } } } catch ( FileNotFoundException e ) { throw new TransferFailedException( "Specified source file does not exist: " + source, e ); } catch ( IOException e ) { fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); String msg = "PUT request for: " + resource + " to " + source.getName() + " failed"; throw new TransferFailedException( msg, e ); } firePutCompleted( resource, source ); }
diff --git a/src/openmap/com/bbn/openmap/gui/time/TimelineLayer.java b/src/openmap/com/bbn/openmap/gui/time/TimelineLayer.java index 2b4a79a5..33c83f13 100644 --- a/src/openmap/com/bbn/openmap/gui/time/TimelineLayer.java +++ b/src/openmap/com/bbn/openmap/gui/time/TimelineLayer.java @@ -1,1522 +1,1522 @@ // ********************************************************************** // // <copyright> // // BBN Technologies, a Verizon Company // 10 Moulton Street // Cambridge, MA 02138 // (617) 873-8000 // // Copyright (C) BBNT Solutions LLC. All rights reserved. // // </copyright> package com.bbn.openmap.gui.time; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Polygon; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import com.bbn.openmap.Environment; import com.bbn.openmap.I18n; import com.bbn.openmap.MapBean; import com.bbn.openmap.MapHandler; import com.bbn.openmap.event.CenterListener; import com.bbn.openmap.event.CenterSupport; import com.bbn.openmap.event.MapMouseListener; import com.bbn.openmap.event.OMEvent; import com.bbn.openmap.event.OMEventSelectionCoordinator; import com.bbn.openmap.gui.event.EventPresenter; import com.bbn.openmap.gui.time.TimeSliderLayer.TimeDrape; import com.bbn.openmap.gui.time.TimelineLayer.SelectionArea.PlayFilterSection; import com.bbn.openmap.layer.OMGraphicHandlerLayer; import com.bbn.openmap.omGraphics.DrawingAttributes; import com.bbn.openmap.omGraphics.OMAction; import com.bbn.openmap.omGraphics.OMGraphic; import com.bbn.openmap.omGraphics.OMGraphicList; import com.bbn.openmap.omGraphics.OMLine; import com.bbn.openmap.omGraphics.OMRaster; import com.bbn.openmap.omGraphics.OMRect; import com.bbn.openmap.omGraphics.OMText; import com.bbn.openmap.proj.Cartesian; import com.bbn.openmap.proj.Projection; import com.bbn.openmap.time.Clock; import com.bbn.openmap.time.TimeBounds; import com.bbn.openmap.time.TimeBoundsEvent; import com.bbn.openmap.time.TimeBoundsListener; import com.bbn.openmap.time.TimeEvent; import com.bbn.openmap.time.TimeEventListener; import com.bbn.openmap.time.TimerStatus; import com.bbn.openmap.tools.drawing.DrawingToolRequestor; import com.bbn.openmap.tools.icon.BasicIconPart; import com.bbn.openmap.tools.icon.IconPart; import com.bbn.openmap.tools.icon.OMIconFactory; /** * Timeline layer * * Render events and allow for their selection on a variable-scale time line. */ public class TimelineLayer extends OMGraphicHandlerLayer implements ActionListener, DrawingToolRequestor, PropertyChangeListener, MapMouseListener, ComponentListener, TimeBoundsListener, TimeEventListener { /** * This property is used to signify whether any AAREvents have been * designated as play filterable, so GUI controls for the play filter can be * enabled/disabled. */ public final static String PlayFilterProperty = "playfilter"; /** * This property is used to send the current offset time where the mouse is * over the timeline. */ public final static String MouseTimeProperty = "mouseTime"; /** * This property is used to send event details that can be displayed when * the mouse is over an event in the timeline. */ public final static String EventDetailsProperty = "eventDetails"; /** * This property is used to notify listeners that the time projection * parameters have changed, and they need to contact this object to figure * out how to display those changes. */ public final static String TimeParametersProperty = "timeParameters"; public static Logger logger = Logger.getLogger("com.bbn.openmap.gui.time.TimelineLayer"); protected I18n i18n = Environment.getI18n(); protected OMGraphicList eventGraphicList = null; protected OMGraphicList timeLinesList = null; protected PlayFilter playFilter = new PlayFilter(); protected OMGraphicList ratingAreas = new OMGraphicList(); protected SelectionArea selectionRect; protected TimeSliderLayer.TimeDrape drape; protected CenterSupport centerDelegate; private TimeSliderLayer timeSliderLayer; long currentTime = 0; long gameStartTime = 0; long gameEndTime = 0; protected EventPresenter eventPresenter; protected OMEventSelectionCoordinator aesc; protected static Color tint = new Color(0x99000000, true); protected Clock clock; private boolean realTimeMode; /** * Construct the TimelineLayer. */ public TimelineLayer() { setName("Timeline"); // This is how to set the ProjectionChangePolicy, which // dictates how the layer behaves when a new projection is // received. setProjectionChangePolicy(new com.bbn.openmap.layer.policy.StandardPCPolicy(this, false)); // Making the setting so this layer receives events from the // SelectMouseMode, which has a modeID of "Gestures". Other // IDs can be added as needed. setMouseModeIDsForEvents(new String[] { "Gestures" }); centerDelegate = new CenterSupport(this); addComponentListener(this); drape = new TimeDrape(0, 0, -1, -1); drape.setFillPaint(Color.gray); drape.setVisible(true); } public void findAndInit(Object someObj) { if (someObj instanceof Clock) { clock = (Clock) someObj; // clock.addPropertyChangeListener(Clock.TIMER_STATUS_PROPERTY, // this); clock.addTimeEventListener(this); clock.addTimeBoundsListener(this); setTimeBounds(clock.getStartTime(), clock.getEndTime()); } if (someObj instanceof CenterListener) { centerDelegate.add((CenterListener) someObj); } if (someObj instanceof EventPresenter) { eventPresenter = (EventPresenter) someObj; selectionRect = null; eventPresenter.addPropertyChangeListener(this); } if (someObj instanceof OMEventSelectionCoordinator) { aesc = (OMEventSelectionCoordinator) someObj; aesc.addPropertyChangeListener(this); } if (someObj instanceof TimePanel.Wrapper) { TimePanel tp = ((TimePanel.Wrapper) someObj).getTimePanel(); tp.addPropertyChangeListener(this); addPropertyChangeListener(tp); timeSliderLayer = tp.getTimeSliderPanel().getTimeSliderLayer(); } } public void findAndUndo(Object someObj) { if (someObj == clock) { // clock.removePropertyChangeListener(Clock.TIMER_STATUS_PROPERTY, // this); clock.removeTimeEventListener(this); clock.removeTimeBoundsListener(this); } if (someObj instanceof CenterListener) { centerDelegate.remove((CenterListener) someObj); } if (someObj == eventPresenter) { eventPresenter.removePropertyChangeListener(this); eventPresenter = null; } if (someObj == aesc) { aesc.removePropertyChangeListener(this); aesc = null; } if (someObj instanceof TimePanel.Wrapper) { TimePanel tp = ((TimePanel.Wrapper) someObj).getTimePanel(); removePropertyChangeListener(tp); tp.removePropertyChangeListener(this); } } public static double forwardProjectMillis(long time) { return (double) time / 60000f; // 60000 millis per minute } public static long inverseProjectMillis(double timef) { return (long) (timef * 60000f); // 60000 millis per minute } /** * Creates the OMGraphic list with the time and event markings. */ public synchronized OMGraphicList prepare() { Projection proj = getProjection(); if (logger.isLoggable(Level.FINER)) { logger.finer("Updating projection with " + proj); } OMGraphicList graphicList = getList(); if (getHeight() > 0) { if (graphicList == null) { graphicList = new OMGraphicList(); } else { graphicList.clear(); } if (drape == null) { drape = new TimeDrape(0, 0, -1, -1); drape.setFillPaint(Color.gray); drape.setVisible(true); } drape.generate(proj); graphicList.add(drape); graphicList.add(constructTimeLines(proj)); graphicList.add(getCurrentTimeMarker(proj)); OMGraphicList eventGraphicList = getEventGraphicList(); // if new events are fetched, new rating areas and play filters are // created here. if (eventGraphicList == null || eventGraphicList.isEmpty()) { eventGraphicList = getEventList(proj); setEventGraphicList(eventGraphicList); } else { if (logger.isLoggable(Level.FINER)) { logger.finer("don't need to re-create event lines, haven't changed with (" + eventGraphicList.size() + ") events"); } eventGraphicList.generate(proj); } ratingAreas.generate(proj); playFilter.generate(proj); graphicList.add(playFilter); graphicList.add(eventGraphicList); graphicList.add(getSelectionRectangle(proj)); graphicList.add(ratingAreas); } return graphicList; } public synchronized OMGraphicList getEventGraphicList() { return eventGraphicList; } public synchronized void setEventGraphicList(OMGraphicList eventGraphicList) { this.eventGraphicList = eventGraphicList; } protected TimeHashFactory timeHashFactory; /** * * @return OMGraphicList new graphic list */ protected OMGraphicList constructTimeLines(Projection projection) { // if (timeLinesList == null) { OMGraphicList tll = new OMGraphicList(); if (timeHashFactory == null) { timeHashFactory = new TimeHashFactory(); } tll.add(timeHashFactory.getHashMarks(projection, realTimeMode, gameEndTime - gameStartTime)); if (preTime != null) { preTime.generate(projection); tll.add(preTime); } if (postTime != null) { postTime.generate(projection); tll.add(postTime); } timeLinesList = tll; return tll; } public SelectionArea getSelectionRectangle(Projection proj) { if (selectionRect == null) { selectionRect = new SelectionArea(); if (eventPresenter != null) { selectionRect.setFillPaint(eventPresenter.getSelectionDrawingAttributes() .getSelectPaint()); } } selectionRect.generate(proj); return selectionRect; } protected OMGraphicList currentTimeMarker; protected SelectionArea.PreTime preTime; protected SelectionArea.PostTime postTime; protected OMGraphic getCurrentTimeMarker(Projection proj) { if (currentTimeMarker == null) { currentTimeMarker = new CurrentTimeMarker(); } currentTimeMarker.generate(proj); return currentTimeMarker; } protected final static String ATT_KEY_EVENT = "att_key_event"; protected OMGraphicList getEventList(Projection projection) { OMGraphicList eventGraphicList; if (eventPresenter != null) { eventGraphicList = getEventList(eventPresenter.getActiveEvents(), projection); // As long as we feel the need to recreate the event markers, // let's re-evaluate the annotations. evaluateEventAttributes(); if (logger.isLoggable(Level.FINE)) { logger.fine("Creating event lines with (" + eventGraphicList.size() + ") events"); } } else { logger.fine("Can't create event list for timeline display, no event presenter"); eventGraphicList = new OMGraphicList(); } return eventGraphicList; } protected OMGraphicList getEventList(Iterator<OMEvent> it, Projection projection) { OMGraphicList eventGraphicList = new OMGraphicList(); if (projection != null) { BasicStroke symbolStroke = new BasicStroke(2); while (it.hasNext()) { OMEvent event = it.next(); long time = event.getTimeStamp() - gameStartTime; float lon = (float) forwardProjectMillis(time); EventMarkerLine currentLine = new EventMarkerLine(0f, lon, 6); currentLine.setLinePaint(Color.black); currentLine.setStroke(symbolStroke); currentLine.generate(projection); currentLine.putAttribute(ATT_KEY_EVENT, event); eventGraphicList.add(currentLine); } } return eventGraphicList; } public class EventMarkerLine extends OMLine { protected int heightRatioSetting; protected byte symbolHeight; public EventMarkerLine(double lat, double lon, int heightRatioSetting) { super(lat, lon, 0, 1, 0, -1); this.heightRatioSetting = heightRatioSetting; } public boolean generate(Projection proj) { byte testSH = (byte) (proj.getHeight() * 2 / heightRatioSetting); if (testSH != symbolHeight) { int[] pts = getPts(); int symbolHeight = proj.getHeight() / heightRatioSetting; pts[1] = symbolHeight; pts[3] = -symbolHeight; this.symbolHeight = (byte) symbolHeight; } return super.generate(proj); } } // ---------------------------------------------------------------------- // GUI // ---------------------------------------------------------------------- protected Box palette = null; public java.awt.Component getGUI() { if (palette == null) { logger.fine("creating Palette."); palette = Box.createVerticalBox(); JPanel subbox3 = new JPanel(new GridLayout(0, 1)); JButton setProperties = new JButton(i18n.get(TimelineLayer.class, "setProperties", "Preferences")); setProperties.setActionCommand(DisplayPropertiesCmd); setProperties.addActionListener(this); subbox3.add(setProperties); palette.add(subbox3); } return palette; } public void drawingComplete(OMGraphic omg, OMAction action) { if (!doAction(omg, action)) { // null OMGraphicList on failure, should only occur if // OMGraphic is added to layer before it's ever been // on the map. setList(new OMGraphicList()); doAction(omg, action); } repaint(); } public boolean isSelectable(OMGraphic omg) { return false; } // ---------------------------------------------------------------------- // ActionListener interface implementation // ---------------------------------------------------------------------- public String getName() { return "TimelineLayer"; } protected void setTimeBounds(long start, long end) { if (gameStartTime != start || gameEndTime != end) { gameStartTime = start; gameEndTime = end; preTime = new SelectionArea.PreTime(0); postTime = new SelectionArea.PostTime(end - start); if (logger.isLoggable(Level.FINE)) { logger.fine("gst: " + gameStartTime + ", get: " + gameEndTime + ", bounds of " + postTime); } if(!realTimeMode || !timeSliderLayer.getUserHasChangedScale()) { setMapBeanMaxScale(true); } } } public void updateTimeBounds(TimeBoundsEvent tbe) { TimeBounds tb = tbe.getNewTimeBounds(); if (tb != null) { setTimeBounds(tb.getStartTime(), tb.getEndTime()); } else { checkAndSetForNoTime(TimeEvent.NO_TIME); } } public void updateTime(TimeEvent te) { if (checkAndSetForNoTime(te)) { return; } Clock clock = (Clock) te.getSource(); setTimeBounds(clock.getStartTime(), clock.getEndTime()); TimerStatus timerStatus = te.getTimerStatus(); if (timerStatus.equals(TimerStatus.STEP_FORWARD) || timerStatus.equals(TimerStatus.STEP_BACKWARD) || timerStatus.equals(TimerStatus.UPDATE)) { // These TimerStatus updates reflect the current time being // specifically set to a value, as opposed to the clock running // normally. currentTime = te.getSystemTime() - gameStartTime; centerDelegate.fireCenter(0, forwardProjectMillis(currentTime)); timeLinesList = null; doPrepare(); } else if (timerStatus.equals(TimerStatus.FORWARD) || timerStatus.equals(TimerStatus.BACKWARD) || timerStatus.equals(TimerStatus.STOPPED)) { // Checking for a running clock prevents a time status // update after the clock is stopped. The // AudioFileHandlers don't care about the current time // if it isn't running. // This check might be avoided if just FORWARD and BACKWARD are sent // if the clock is running. Need to check the behavior of the clock // to make sure, and figure out what the state of the clock is when // it stops. if (clock.isRunning()) { long currentTime = te.getSystemTime() - gameStartTime; if (playFilter.reactToCurrentTime(currentTime, clock, gameStartTime)) { this.currentTime = currentTime; timeLinesList = null; centerDelegate.fireCenter(0, forwardProjectMillis(currentTime)); } } } else { logger.info("none of the above: " + timerStatus.toString()); } } /* * @seejava.beans.PropertyChangeListener#propertyChange(java.beans. * PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if (propertyName == EventPresenter.ActiveEventsProperty) { setEventGraphicList(null); logger.fine("EventPresenter updated event list, calling doPrepare() " + evt.getNewValue()); doPrepare(); } else if (propertyName == OMEventSelectionCoordinator.EventsSelectedProperty) { setSelectionRectangleToEvents(); } else if (propertyName == EventPresenter.EventAttributesUpdatedProperty) { evaluateEventAttributes(); doPrepare(); } else if (propertyName == TimePanel.PlayFilterProperty) { boolean inUse = ((Boolean) evt.getNewValue()).booleanValue(); playFilter.setInUse(inUse); firePropertyChange(PlayFilterProperty, null, new Boolean(playFilter.size() > 0 || !inUse)); } else { logger.finer("AAGGH: " + propertyName); } } protected boolean checkAndSetForNoTime(TimeEvent te) { boolean isNoTime = te == TimeEvent.NO_TIME; if (drape != null) { drape.setVisible(isNoTime); repaint(); } return isNoTime; } double snapToEvent(double lon) { double retVal = lon; double minDiff = Double.MAX_VALUE; if (eventPresenter != null) { for (Iterator<OMEvent> it = eventPresenter.getAllEvents(); it.hasNext();) { OMEvent event = it.next(); long time = event.getTimeStamp() - gameStartTime; float timeMinutes = (float) forwardProjectMillis(time); if (Math.abs(timeMinutes - lon) < minDiff) { minDiff = Math.abs(timeMinutes - lon); retVal = timeMinutes; } } } return retVal; } public MapMouseListener getMapMouseListener() { return this; } public String[] getMouseModeServiceList() { return getMouseModeIDsForEvents(); } public boolean mousePressed(MouseEvent e) { doubleClick = false; updateMouseTimeDisplay(e); // Use current projection to determine rect top and bottom Projection projection = getProjection(); // Get latLong from mouse, and then snap to nearest event... Point2D latLong = projection.inverse(e.getPoint()); Point2D ul = projection.getUpperLeft(); Point2D lr = projection.getLowerRight(); double lon = latLong.getX(); float up = (float) ul.getY(); float down = (float) lr.getY(); lon = snapToEvent(lon); selectionRect.setVisible(false); selectionRect.setLocation(up, (float) lon, down, (float) lon, OMGraphic.LINETYPE_STRAIGHT); selectionRect.generate(projection); downLon = lon; repaint(); return true; } protected void selectEventForMouseEvent(MouseEvent e) { // Handle a single click, select event if close OMGraphicList eventGraphicList = getEventGraphicList(); if (e != null && eventGraphicList != null) { OMGraphic omg = eventGraphicList.findClosest((int) e.getX(), (int) e.getY(), 4); if (omg != null) { OMEvent sourceEvent = (OMEvent) omg.getAttribute(ATT_KEY_EVENT); if (sourceEvent != null) { sourceEvent.putAttribute(OMEvent.ATT_KEY_SELECTED, OMEvent.ATT_VAL_SELECTED); Vector<OMEvent> eventList = new Vector<OMEvent>(); eventList.add(sourceEvent); aesc.eventsSelected(eventList); } } } doubleClick = false; } public boolean mouseReleased(MouseEvent e) { updateMouseTimeDisplay(e); handleEventSelection(); return true; } double downLon; boolean doubleClick = false; public boolean mouseClicked(MouseEvent e) { if (e.getClickCount() >= 2) { selectEventForMouseEvent(e); doubleClick = true; return true; } double lon = updateMouseTimeDisplay(e); if (clock != null) { clock.setTime(gameStartTime + inverseProjectMillis(lon)); } selectionRect.setLocation(lon, lon); selectionRect.setVisible(false); return true; } protected double updateMouseTimeDisplay(MouseEvent e) { Projection proj = getProjection(); Point2D latLong = proj.inverse(e.getPoint()); double lon = latLong.getX(); double endTime = forwardProjectMillis(gameEndTime - gameStartTime); if (lon < 0) { lon = 0; } else if (lon > endTime) { lon = endTime; } long offsetMillis = inverseProjectMillis(lon); if(realTimeMode) { offsetMillis = offsetMillis - (gameEndTime - gameStartTime); } updateMouseTimeDisplay(new Long(offsetMillis)); return lon; } public void updateMouseTimeDisplay(Long offsetMillis) { firePropertyChange(MouseTimeProperty, null, offsetMillis); } protected void updateEventDetails(MouseEvent e) { String details = ""; OMGraphicList eventGraphicList = getEventGraphicList(); if (e != null && eventGraphicList != null) { OMGraphic omg = eventGraphicList.findClosest((int) e.getX(), (int) e.getY(), 4); if (omg != null) { OMEvent sourceEvent = (OMEvent) omg.getAttribute(ATT_KEY_EVENT); if (sourceEvent != null) { details = sourceEvent.getDescription(); } } } firePropertyChange(EventDetailsProperty, null, details); } protected void updateEventDetails() { updateEventDetails(null); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) { firePropertyChange(MouseTimeProperty, null, new Long(-1)); updateEventDetails(); } public boolean mouseDragged(MouseEvent e) { updateMouseTimeDisplay(e); updateEventDetails(e); // Get latLong from mouse, and set E side of current select rect... Projection proj = getProjection(); Point2D latLong = proj.inverse(e.getPoint()); double lon = snapToEvent(latLong.getX()); float west = (float) Math.min(downLon, lon); float east = (float) Math.max(downLon, lon); selectionRect.setVisible(true); selectionRect.setLocation(west, east); selectionRect.generate(proj); repaint(); return true; } public boolean mouseMoved(MouseEvent e) { updateMouseTimeDisplay(e); updateEventDetails(e); return true; } public void mouseMoved() { updateEventDetails(); } protected List<OMEvent> handleEventSelection() { List<OMEvent> eventList = null; if (aesc != null && selectionRect != null) { // The thing to be careful about here is that the selection // Rectangle isn't where the user clicked and released. It's snapped // to the visible events. It makes some weird behavior below when // you try to highlight a single event, because the time for that // event is the closest snapped time event, not the invisible event // that may be clicked on. boolean goodDrag = selectionRect.isVisible(); double lowerTime = selectionRect.getWestLon(); double upperTime = selectionRect.getEastLon(); // Convert to millis long lowerTimeStamp = inverseProjectMillis((float) lowerTime); long upperTimeStamp = inverseProjectMillis((float) upperTime); boolean sameTime = lowerTimeStamp == upperTimeStamp; goodDrag = goodDrag && !sameTime; boolean labeledRangeStart = false; OMEvent lastEventLabeled = null; for (Iterator<OMEvent> it = eventPresenter.getAllEvents(); it.hasNext();) { if (eventList == null) { eventList = new Vector<OMEvent>(); } OMEvent event = (OMEvent) it.next(); double timeStamp = event.getTimeStamp() - gameStartTime; // Don't forget, need to go through all of the events, not just // the ones lower than the upper time stamp, because we need to // set the selected flag to null for all of them and then only // reset the ones that actually are selected. event.putAttribute(OMEvent.ATT_KEY_SELECTED, null); if (goodDrag && timeStamp >= lowerTimeStamp && timeStamp <= upperTimeStamp) { eventList.add(event); // Needs to be updated to put ATT_VAL_SELECTED_START_RANGE, // ATT_VAL_SELECTED_END_RANGE, or just ATT_VAL_SELECTED if (!labeledRangeStart && lowerTimeStamp != upperTimeStamp) { event.putAttribute(OMEvent.ATT_KEY_SELECTED, OMEvent.ATT_VAL_SELECTED_START_RANGE); labeledRangeStart = true; } else { event.putAttribute(OMEvent.ATT_KEY_SELECTED, OMEvent.ATT_VAL_SELECTED); } lastEventLabeled = event; } else if (sameTime && timeStamp == lowerTimeStamp) { // This code just returns the closest visible snapped time // event. // event.putAttribute(AAREvent.ATT_KEY_SELECTED, // AAREvent.ATT_VAL_SELECTED); // eventList.add(event); // I guess this is OK when a visible event is clicked on, // but it's not when a non-visible event is clicked on. } } if (labeledRangeStart && lastEventLabeled != null) { lastEventLabeled.putAttribute(OMEvent.ATT_KEY_SELECTED, OMEvent.ATT_VAL_SELECTED_END_RANGE); } aesc.eventsSelected(eventList); } return eventList; } protected void evaluateEventAttributes() { ratingAreas.clear(); playFilter.clear(); SelectionArea.RatingArea currentRatingArea = null; SelectionArea.PlayFilterSection currentPlayFilter = null; if (eventPresenter != null) { for (Iterator<OMEvent> it = eventPresenter.getAllEvents(); it.hasNext();) { OMEvent aare = it.next(); String rating = (String) aare.getAttribute(OMEvent.ATT_KEY_RATING); Object playFilterObj = aare.getAttribute(OMEvent.ATT_KEY_PLAY_FILTER); long timeStamp = aare.getTimeStamp() - gameStartTime; if (rating != null) { if (currentRatingArea != null && !currentRatingArea.isRating(rating)) { currentRatingArea = null; } if (currentRatingArea == null) { currentRatingArea = new SelectionArea.RatingArea(timeStamp, rating); ratingAreas.add(currentRatingArea); } currentRatingArea.addTime(timeStamp); } else if (currentRatingArea != null) { currentRatingArea = null; } if (playFilterObj != null) { if (currentPlayFilter != null) { currentPlayFilter.addTime(timeStamp); } else { currentPlayFilter = new SelectionArea.PlayFilterSection(timeStamp); // logger.info("adding play filter section to play // filter"); playFilter.add(currentPlayFilter); } } else { currentPlayFilter = null; } } OMGraphicList list = getList(); if (list != null && list.isVisible()) { firePropertyChange(PlayFilterProperty, null, new Boolean(!playFilter.isInUse() || playFilter.size() > 0)); } } } protected void setSelectionRectangleToEvents() { if (aesc != null) { selectionRect = getSelectionRectangle(getProjection()); double lowerTime = Double.POSITIVE_INFINITY; double upperTime = Double.NEGATIVE_INFINITY; for (Iterator<OMEvent> it = eventPresenter.getAllEvents(); it.hasNext();) { OMEvent event = it.next(); if (event.getAttribute(OMEvent.ATT_KEY_SELECTED) != null) { // Convert to minutes for selectRect bounds double timeStamp = (double) forwardProjectMillis(event.getTimeStamp() - gameStartTime); if (timeStamp < lowerTime) { lowerTime = timeStamp; } if (timeStamp > upperTime) { upperTime = timeStamp; } } } if (upperTime != Double.NEGATIVE_INFINITY && lowerTime != Double.POSITIVE_INFINITY) { selectionRect.setLocation((float) lowerTime, (float) upperTime); selectionRect.setVisible(true); selectionRect.generate(getProjection()); } else { selectionRect.setVisible(false); } } repaint(); } public static class SelectionArea extends com.bbn.openmap.omGraphics.OMRect { public SelectionArea() { setRenderType(OMRect.RENDERTYPE_LATLON); } public void setLocation(double left, double right) { super.setLocation(0f, left, 0f, right, OMRect.LINETYPE_STRAIGHT); } public boolean generate(Projection proj) { updateY(proj); return super.generate(proj); } protected void updateY(Projection proj) { // The difference here is that the upper and lower bounds are // determined by the projection. Point2D ul = proj.getUpperLeft(); Point2D lr = proj.getLowerRight(); lat1 = ul.getY(); lat2 = lr.getY(); } public static class PreTime extends SelectionArea { public PreTime(long time) { super(); lon2 = forwardProjectMillis(time); setFillPaint(tint); setLinePaint(tint); } public void setLocation() {} public boolean generate(Projection proj) { // The difference here is that the vertical bounds are // determined the starting time and all times before that. Point2D ul = proj.getUpperLeft(); double ulx = ul.getX(); if (ulx >= lon2) { lon1 = lon2; } else { lon1 = ulx; } return super.generate(proj); } } public static class PostTime extends SelectionArea { public PostTime(long time) { super(); lon1 = forwardProjectMillis(time); setFillPaint(tint); setLinePaint(tint); } public void setLocation() {} public boolean generate(Projection proj) { // The difference here is that the vertical bounds are // determined the end time and all times after that. Point2D lr = proj.getLowerRight(); double lrx = lr.getX(); if (lrx <= lon1) { lon2 = lon1; } else { lon2 = lrx; } return super.generate(proj); } } public static class RatingArea extends SelectionArea { protected String rating; protected static Color goodColor = new Color(0x9900ff00, true); protected static Color badColor = new Color(0x99ff0000, true); public RatingArea(long time, String rating) { super(); this.rating = rating; double timef = forwardProjectMillis(time); setLocation(timef, timef); Color ratingColor = badColor; if (rating.equals(OMEvent.ATT_VAL_GOOD_RATING)) { ratingColor = goodColor; } setLinePaint(ratingColor); setFillPaint(ratingColor); } public boolean isRating(String rating) { return this.rating == rating || this.rating.equalsIgnoreCase(rating); } public void addTime(long timeToAdd) { double time = forwardProjectMillis(timeToAdd); double east = getEastLon(); double west = getWestLon(); boolean updated = false; if (time < west) { west = time; updated = true; } if (time > east) { east = time; updated = true; } if (updated) { setLocation(west, east); } } } public static class PlayFilterSection extends SelectionArea { protected static Color color = new Color(0x99000000, true); protected String idString; public PlayFilterSection(long time) { super(); double timef = forwardProjectMillis(time); setLocation(timef, timef); setLinePaint(color); setFillPaint(color); } /** * Checks time in relation to held times. * * @param timel time in unprojected milliseconds, offset from game * start time. * @return 0 if time is within bounds, -1 if time is before bounds, * 1 if time is after bounds. */ public int isWithin(long timel) { double time = forwardProjectMillis(timel); int ret = -1; if (time >= getWestLon()) { ret++; } if (time > getEastLon()) { ret++; } return ret; } protected void updateY(Projection proj) { Point2D ul = proj.getUpperLeft(); lat1 = ul.getY(); Point2D lrpt = proj.inverse(0, proj.getHeight() / 8); lat2 = lrpt.getY(); idString = null; } public void addTime(long timeToAdd) { double time = forwardProjectMillis(timeToAdd); double east = getEastLon(); double west = getWestLon(); boolean updated = false; if (time < west) { west = time; updated = true; } if (time > east) { east = time; updated = true; } if (updated) { setLocation(west, east); idString = null; } } public String toString() { if (idString == null) { idString = "PlayFilterSection[" + getWestLon() + "," + getEastLon() + "]"; } return idString; } } } public static class CurrentTimeMarker extends OMGraphicList { protected OMRaster upperMark; protected OMRaster lowerMark; protected OMLine startingLine; int iconSize = 16; int lastHeight = 0; int lastWidth = 0; public CurrentTimeMarker() { DrawingAttributes da = new DrawingAttributes(); da.setFillPaint(tint); da.setLinePaint(tint); IconPart ip = new BasicIconPart(new Polygon(new int[] { 50, 90, 10, 50 }, new int[] { 10, 90, 90, 10 }, 4), da); ImageIcon thumbsUpImage = OMIconFactory.getIcon(iconSize, iconSize, ip); lowerMark = new OMRaster(0, 0, thumbsUpImage); ip = new BasicIconPart(new Polygon(new int[] { 10, 90, 50, 10 }, new int[] { 10, 10, 90, 10 }, 4), da); ImageIcon thumbsDownImage = OMIconFactory.getIcon(iconSize, iconSize, ip); upperMark = new OMRaster(0, 0, thumbsDownImage); startingLine = new OMLine(0, 0, 0, 0); da.setTo(startingLine); add(startingLine); add(lowerMark); add(upperMark); } public boolean generate(Projection proj) { int height = proj.getHeight(); int width = proj.getWidth(); if (height != lastHeight || width != lastWidth) { lastHeight = height; lastWidth = width; int halfX = (int) (width / 2); upperMark.setX(halfX - iconSize / 2); upperMark.setY(0); lowerMark.setX(halfX - iconSize / 2); lowerMark.setY(height - iconSize); int[] pts = startingLine.getPts(); pts[0] = halfX; pts[1] = 0 + iconSize; pts[2] = halfX; pts[3] = height - iconSize; } return super.generate(proj); } } public static class TimeHashFactory { List<TimeHashMarks> hashMarks = new ArrayList<TimeHashMarks>(5); TimeHashMarks current; public TimeHashFactory() { hashMarks.add(new TimeHashMarks.Seconds()); hashMarks.add(new TimeHashMarks.Minutes()); hashMarks.add(new TimeHashMarks.Hours()); hashMarks.add(new TimeHashMarks.Days()); hashMarks.add(new TimeHashMarks.Years()); } public OMGraphicList getHashMarks(Projection proj, boolean realTimeMode, long gameDuration) { Point2D ul = proj.getUpperLeft(); Point2D lr = proj.getLowerRight(); // timeSpan in minutes double timeSpan = lr.getX() - ul.getX(); TimeHashMarks thm = null; for (Iterator<TimeHashMarks> it = hashMarks.iterator(); it.hasNext();) { TimeHashMarks cthm = it.next(); if (cthm.passesThreshold(timeSpan)) { thm = cthm; } else { break; } } if (current != null) { current.clear(); } if (thm != current) { current = thm; } current.generate(proj, timeSpan, realTimeMode, gameDuration); return current; } } public static class PlayFilter extends OMGraphicList { protected boolean inUse = false; String currentlyPlaying = null; public PlayFilter() {} public boolean reactToCurrentTime(long currentTime, Clock clock, long gameStartTime) { boolean ret = !inUse; if (inUse) { // logger.info("checking " + size() + " sections"); for (Iterator<OMGraphic> it = iterator(); it.hasNext();) { PlayFilterSection pfs = (PlayFilterSection) it.next(); int where = pfs.isWithin(currentTime); if (where == 0) { ret = true; currentlyPlaying = pfs.toString(); // logger.info("where == 0, setting pfs " + // currentlyPlaying); break; } else if (where > 0) { if ((currentlyPlaying != null && (currentlyPlaying.equals(pfs.toString()))) || !it.hasNext()) { // logger.info("where > 0, same pfs, stopping clock // " + pfs); clock.setTime(gameStartTime + inverseProjectMillis(pfs.getEastLon())); clock.stopClock(); currentlyPlaying = null; break; } else { // logger.info("where > 0, not the same pfs " + pfs // + ", " + currentlyPlaying); } continue; } else { // logger.info("where < 0, jumping clock " + pfs); clock.setTime(gameStartTime + inverseProjectMillis(pfs.getWestLon())); break; } } } return ret; } public boolean isInUse() { return inUse; } public void setInUse(boolean inUse) { this.inUse = inUse; } } public abstract static class TimeHashMarks extends OMGraphicList { protected String annotation; protected double unitPerMinute; protected TimeHashMarks(String annotation, double unitPerMinute) { this.annotation = annotation; this.unitPerMinute = unitPerMinute; } public abstract boolean passesThreshold(double minVisibleOnTimeLine); public boolean generate(Projection proj, double minSpan, boolean realTimeMode, long gameDuration) { Point2D ul = proj.getUpperLeft(); Point2D lr = proj.getLowerRight(); double left = ul.getX() * unitPerMinute; double right = lr.getX() * unitPerMinute; minSpan = minSpan * unitPerMinute; double num = Math.floor(minSpan); double heightStepSize = 1; double stepSize = 1; if (num < 2) { stepSize = .25; } else if (num < 5) { stepSize = .5; } else if (num > 30) { stepSize = 10; heightStepSize = 10; } else if (num > 15) { heightStepSize = 10; } if (logger.isLoggable(Level.FINER)) { logger.finer("figure on needing " + num + annotation + ", " + stepSize + " stepsize for " + (minSpan / stepSize) + " lines"); } int height = (int) (proj.getHeight() * .2); double anchory = lr.getY(); if(realTimeMode) { // Now, we need to baseline marks on gameEndTime (i.e. 'now'), not on the right most value. double durationUnits = gameDuration * (1.0 / (1000.0*60.0)) * unitPerMinute; double start = durationUnits; // need to do future times. if (right > start) { while (start < right) { start += stepSize; } } while (start > right) { start -= stepSize; } double stepStart = start; double stepEnd = Math.floor(left); for (double i = stepStart; i > stepEnd; i -= stepSize) { double anchorx = i / unitPerMinute; int thisHeight = height; boolean doLabel = true; - // KM TODO fix this up -// if (i % heightStepSize != 0) { -// thisHeight /= 2; -// doLabel = false; -// } + // As always in real-time mode, the origin is at 'durationUnits' (in local time space) + if ((durationUnits-i) % heightStepSize != 0) { + thisHeight /= 2; + doLabel = false; + } OMLine currentLine = new OMLine(anchory, anchorx, 0, 0, 0, -thisHeight); currentLine.setLinePaint(tint); currentLine.setStroke(new BasicStroke(2)); add(currentLine); if (doLabel) { OMText label = new OMText((float) anchory, (float) anchorx, 2, -5, (int) (i-durationUnits) + annotation, OMText.JUSTIFY_LEFT); label.setLinePaint(tint); add(label); } } } else { // Now, we need to baseline marks on 0, not on the left most value. double start = 0; // need to do negative times. if (left < 0) { while (start > left) { start -= stepSize; } } while (start < left) { start += stepSize; } double stepStart = Math.floor(start); double stepEnd = Math.ceil(right); for (double i = stepStart; i < stepEnd; i += stepSize) { double anchorx = i / unitPerMinute; int thisHeight = height; boolean doLabel = true; if (i % heightStepSize != 0) { thisHeight /= 2; doLabel = false; } OMLine currentLine = new OMLine(anchory, anchorx, 0, 0, 0, -thisHeight); currentLine.setLinePaint(tint); currentLine.setStroke(new BasicStroke(2)); add(currentLine); if (doLabel) { OMText label = new OMText((float) anchory, (float) anchorx, 2, -5, (int) i + annotation, OMText.JUSTIFY_LEFT); label.setLinePaint(tint); add(label); } } } return super.generate(proj); } public static class Seconds extends TimeHashMarks { public Seconds() { super("s", 60); } public boolean passesThreshold(double minVisibleOnTimeLine) { return true; } } public static class Minutes extends TimeHashMarks { public Minutes() { super("m", 1); } public boolean passesThreshold(double minVisibleOnTimeLine) { return minVisibleOnTimeLine > 2; } } public static class Hours extends TimeHashMarks { public Hours() { super("h", (1d / 60d)); } public boolean passesThreshold(double minVisibleOnTimeLine) { return minVisibleOnTimeLine / 60 > 3; } } public static class Days extends TimeHashMarks { public Days() { super("d", (1d / 60d / 24d)); } public boolean passesThreshold(double minVisibleOnTimeLine) { return minVisibleOnTimeLine / 60 / 24 > 2; } } public static class Years extends TimeHashMarks { public Years() { super("y", (1d / 60d / 24d / 365d)); } public boolean passesThreshold(double minVisibleOnTimeLine) { return minVisibleOnTimeLine / 60 / 24 / 365 > 1; } } } protected void setMapBeanMaxScale(boolean setScaleToMax) { float scale = (float) (TimeSliderLayer.magicScaleFactor * (double) forwardProjectMillis(gameEndTime - gameStartTime) / getProjection().getWidth()); MapBean mb = (MapBean) ((MapHandler) getBeanContext()).get(com.bbn.openmap.MapBean.class); ((Cartesian) mb.getProjection()).setMaxScale(scale); if (setScaleToMax) { mb.setScale(scale); } } public void componentHidden(ComponentEvent e) {} public void componentMoved(ComponentEvent e) {} public void componentResized(ComponentEvent e) { setMapBeanMaxScale(false); } public void componentShown(ComponentEvent e) {} public void paint(Graphics g) { try { super.paint(g); } catch (Exception e) { if (logger.isLoggable(Level.FINE)) { logger.warning(e.getMessage()); e.printStackTrace(); } } } public void setRealTimeMode(boolean realTimeMode) { this.realTimeMode = realTimeMode; } }
true
true
public boolean generate(Projection proj, double minSpan, boolean realTimeMode, long gameDuration) { Point2D ul = proj.getUpperLeft(); Point2D lr = proj.getLowerRight(); double left = ul.getX() * unitPerMinute; double right = lr.getX() * unitPerMinute; minSpan = minSpan * unitPerMinute; double num = Math.floor(minSpan); double heightStepSize = 1; double stepSize = 1; if (num < 2) { stepSize = .25; } else if (num < 5) { stepSize = .5; } else if (num > 30) { stepSize = 10; heightStepSize = 10; } else if (num > 15) { heightStepSize = 10; } if (logger.isLoggable(Level.FINER)) { logger.finer("figure on needing " + num + annotation + ", " + stepSize + " stepsize for " + (minSpan / stepSize) + " lines"); } int height = (int) (proj.getHeight() * .2); double anchory = lr.getY(); if(realTimeMode) { // Now, we need to baseline marks on gameEndTime (i.e. 'now'), not on the right most value. double durationUnits = gameDuration * (1.0 / (1000.0*60.0)) * unitPerMinute; double start = durationUnits; // need to do future times. if (right > start) { while (start < right) { start += stepSize; } } while (start > right) { start -= stepSize; } double stepStart = start; double stepEnd = Math.floor(left); for (double i = stepStart; i > stepEnd; i -= stepSize) { double anchorx = i / unitPerMinute; int thisHeight = height; boolean doLabel = true; // KM TODO fix this up // if (i % heightStepSize != 0) { // thisHeight /= 2; // doLabel = false; // } OMLine currentLine = new OMLine(anchory, anchorx, 0, 0, 0, -thisHeight); currentLine.setLinePaint(tint); currentLine.setStroke(new BasicStroke(2)); add(currentLine); if (doLabel) { OMText label = new OMText((float) anchory, (float) anchorx, 2, -5, (int) (i-durationUnits) + annotation, OMText.JUSTIFY_LEFT); label.setLinePaint(tint); add(label); } } } else { // Now, we need to baseline marks on 0, not on the left most value. double start = 0; // need to do negative times. if (left < 0) { while (start > left) { start -= stepSize; } } while (start < left) { start += stepSize; } double stepStart = Math.floor(start); double stepEnd = Math.ceil(right); for (double i = stepStart; i < stepEnd; i += stepSize) { double anchorx = i / unitPerMinute; int thisHeight = height; boolean doLabel = true; if (i % heightStepSize != 0) { thisHeight /= 2; doLabel = false; } OMLine currentLine = new OMLine(anchory, anchorx, 0, 0, 0, -thisHeight); currentLine.setLinePaint(tint); currentLine.setStroke(new BasicStroke(2)); add(currentLine); if (doLabel) { OMText label = new OMText((float) anchory, (float) anchorx, 2, -5, (int) i + annotation, OMText.JUSTIFY_LEFT); label.setLinePaint(tint); add(label); } } } return super.generate(proj); }
public boolean generate(Projection proj, double minSpan, boolean realTimeMode, long gameDuration) { Point2D ul = proj.getUpperLeft(); Point2D lr = proj.getLowerRight(); double left = ul.getX() * unitPerMinute; double right = lr.getX() * unitPerMinute; minSpan = minSpan * unitPerMinute; double num = Math.floor(minSpan); double heightStepSize = 1; double stepSize = 1; if (num < 2) { stepSize = .25; } else if (num < 5) { stepSize = .5; } else if (num > 30) { stepSize = 10; heightStepSize = 10; } else if (num > 15) { heightStepSize = 10; } if (logger.isLoggable(Level.FINER)) { logger.finer("figure on needing " + num + annotation + ", " + stepSize + " stepsize for " + (minSpan / stepSize) + " lines"); } int height = (int) (proj.getHeight() * .2); double anchory = lr.getY(); if(realTimeMode) { // Now, we need to baseline marks on gameEndTime (i.e. 'now'), not on the right most value. double durationUnits = gameDuration * (1.0 / (1000.0*60.0)) * unitPerMinute; double start = durationUnits; // need to do future times. if (right > start) { while (start < right) { start += stepSize; } } while (start > right) { start -= stepSize; } double stepStart = start; double stepEnd = Math.floor(left); for (double i = stepStart; i > stepEnd; i -= stepSize) { double anchorx = i / unitPerMinute; int thisHeight = height; boolean doLabel = true; // As always in real-time mode, the origin is at 'durationUnits' (in local time space) if ((durationUnits-i) % heightStepSize != 0) { thisHeight /= 2; doLabel = false; } OMLine currentLine = new OMLine(anchory, anchorx, 0, 0, 0, -thisHeight); currentLine.setLinePaint(tint); currentLine.setStroke(new BasicStroke(2)); add(currentLine); if (doLabel) { OMText label = new OMText((float) anchory, (float) anchorx, 2, -5, (int) (i-durationUnits) + annotation, OMText.JUSTIFY_LEFT); label.setLinePaint(tint); add(label); } } } else { // Now, we need to baseline marks on 0, not on the left most value. double start = 0; // need to do negative times. if (left < 0) { while (start > left) { start -= stepSize; } } while (start < left) { start += stepSize; } double stepStart = Math.floor(start); double stepEnd = Math.ceil(right); for (double i = stepStart; i < stepEnd; i += stepSize) { double anchorx = i / unitPerMinute; int thisHeight = height; boolean doLabel = true; if (i % heightStepSize != 0) { thisHeight /= 2; doLabel = false; } OMLine currentLine = new OMLine(anchory, anchorx, 0, 0, 0, -thisHeight); currentLine.setLinePaint(tint); currentLine.setStroke(new BasicStroke(2)); add(currentLine); if (doLabel) { OMText label = new OMText((float) anchory, (float) anchorx, 2, -5, (int) i + annotation, OMText.JUSTIFY_LEFT); label.setLinePaint(tint); add(label); } } } return super.generate(proj); }
diff --git a/src/main/java/grisu/control/EnunciateServiceInterfaceImpl.java b/src/main/java/grisu/control/EnunciateServiceInterfaceImpl.java index 3ac5ae5..ffff9c4 100644 --- a/src/main/java/grisu/control/EnunciateServiceInterfaceImpl.java +++ b/src/main/java/grisu/control/EnunciateServiceInterfaceImpl.java @@ -1,237 +1,237 @@ package grisu.control; import grisu.backend.model.User; import grisu.control.exceptions.NoSuchTemplateException; import grisu.control.serviceInterfaces.AbstractServiceInterface; import grisu.control.serviceInterfaces.LocalServiceInterface; import grisu.settings.Environment; import grisu.settings.ServiceTemplateManagement; import grith.jgrith.credential.Credential; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import javax.jws.WebService; import javax.ws.rs.Path; import javax.xml.ws.soap.MTOM; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; /** * This abstract class implements most of the methods of the * {@link ServiceInterface} interface. This way developers don't have to waste * time to implement the whole interface just for some things that are site/grid * specific. Currently there are two classes that extend this abstract class: * {@link LocalServiceInterface} and WsServiceInterface (which can be found in * the grisu-ws module). * * The {@link LocalServiceInterface} is used to work with a small local database * like hsqldb so a user has got the whole grisu framework on his desktop. Of * course, all required ports have to be open from the desktop to the grid. On * the other hand no web service server is required. * * The WsServiceInterface is the main one and it is used to set up a web service * somewhere. So light-weight clients can talk to it. * * @author Markus Binsteiner * */ @Path("/grisu") @WebService(endpointInterface = "grisu.control.ServiceInterface") @MTOM(enabled = true) // @StreamingAttachment(parseEagerly = true, memoryThreshold = 40000L) public class EnunciateServiceInterfaceImpl extends AbstractServiceInterface implements ServiceInterface { static { // System.out.println("INHERITABLETHREAD"); SecurityContextHolder .setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL); } static final Logger myLogger = LoggerFactory .getLogger(EnunciateServiceInterfaceImpl.class.getName()); private String username; private char[] password; private static String hostname = null; protected synchronized Credential getCredential() { final GrisuUserDetails gud = getSpringUserDetails(); if (gud != null) { // myLogger.debug("Found user: " + gud.getUsername()); return gud.fetchCredential(); } else { myLogger.error("Couldn't find user..."); return null; } } // protected final ProxyCredential getCredential(String fqan, // int lifetimeInSeconds) { // // final String myProxyServer = MyProxyServerParams.getMyProxyServer(); // final int myProxyPort = MyProxyServerParams.getMyProxyPort(); // // ProxyCredential temp; // try { // myLogger.debug("Getting delegated proxy from MyProxy..."); // temp = new ProxyCredential(MyProxy_light.getDelegation( // myProxyServer, myProxyPort, username, password, // lifetimeInSeconds)); // myLogger.debug("Finished getting delegated proxy from MyProxy. DN: " // + temp.getDn()); // // if (StringUtils.isNotBlank(fqan)) { // // final VO vo = getUser().getFqans().get(fqan); // myLogger.debug(temp.getDn() + ":Creating voms proxy for fqan: " // + fqan); // final ProxyCredential credToUse = CertHelpers // .getVOProxyCredential(vo, fqan, temp); // return credToUse; // } else { // return temp; // } // // } catch (final Exception e) { // throw new RuntimeException(e); // } // // } public long getCredentialEndTime() { final GrisuUserDetails gud = getSpringUserDetails(); if (gud == null) { return -1L; } else { return getSpringUserDetails().getCredentialEndTime(); } } @Override public String getInterfaceInfo(String key) { if ("HOSTNAME".equalsIgnoreCase(key)) { if (hostname == null) { try { final InetAddress addr = InetAddress.getLocalHost(); final byte[] ipAddr = addr.getAddress(); hostname = addr.getHostName(); if (StringUtils.isBlank(hostname)) { hostname = ""; } else { hostname = hostname + " / "; } hostname = hostname + addr.getHostAddress(); } catch (final UnknownHostException e) { hostname = "Unavailable"; } } return hostname; } else if ("VERSION".equalsIgnoreCase(key)) { return Integer.toString(ServiceInterface.API_VERSION); } else if ("NAME".equalsIgnoreCase(key)) { - return "Local serviceinterface"; + return "Webservice (REST/SOAP) interface"; } else if ("BACKEND_VERSION".equalsIgnoreCase(key)) { return BACKEND_VERSION; } return null; } private GrisuUserDetails getSpringUserDetails() { final SecurityContext securityContext = SecurityContextHolder .getContext(); final Authentication authentication = securityContext .getAuthentication(); if (authentication != null) { final Object principal = authentication.getPrincipal(); if (principal instanceof GrisuUserDetails) { return (GrisuUserDetails) principal; } else { return null; } } else { return null; } } public String getTemplate(String name) throws NoSuchTemplateException { final File file = new File( Environment.getAvailableTemplatesDirectory(), name + ".template"); String temp; try { temp = FileUtils.readFileToString(file); } catch (final IOException e) { throw new RuntimeException(e); } return temp; } @Override protected synchronized User getUser() { final GrisuUserDetails gud = getSpringUserDetails(); if (gud != null) { // myLogger.debug("Found user: "+gud.getUsername()); return gud.getUser(this); } else { myLogger.error("Couldn't find user..."); throw new RuntimeException("Can't get user for session."); } } public String[] listHostedApplicationTemplates() { return ServiceTemplateManagement.getAllAvailableApplications(); } public void login(String username, String password) { this.username = username; if (StringUtils.isNotBlank(password)) { this.password = password.toCharArray(); } getCredential(); // // load archived jobs in background // new Thread() { // @Override // public void run() { // getArchivedJobs(null); // } // }.start(); } public String logout() { myLogger.debug("Logging out user: " + getDN()); // HttpServletRequest req = HTTPRequestContext.get().getRequest(); // req.getSession().setAttribute("credential", null); return "Logged out."; } }
true
true
public String getInterfaceInfo(String key) { if ("HOSTNAME".equalsIgnoreCase(key)) { if (hostname == null) { try { final InetAddress addr = InetAddress.getLocalHost(); final byte[] ipAddr = addr.getAddress(); hostname = addr.getHostName(); if (StringUtils.isBlank(hostname)) { hostname = ""; } else { hostname = hostname + " / "; } hostname = hostname + addr.getHostAddress(); } catch (final UnknownHostException e) { hostname = "Unavailable"; } } return hostname; } else if ("VERSION".equalsIgnoreCase(key)) { return Integer.toString(ServiceInterface.API_VERSION); } else if ("NAME".equalsIgnoreCase(key)) { return "Local serviceinterface"; } else if ("BACKEND_VERSION".equalsIgnoreCase(key)) { return BACKEND_VERSION; } return null; }
public String getInterfaceInfo(String key) { if ("HOSTNAME".equalsIgnoreCase(key)) { if (hostname == null) { try { final InetAddress addr = InetAddress.getLocalHost(); final byte[] ipAddr = addr.getAddress(); hostname = addr.getHostName(); if (StringUtils.isBlank(hostname)) { hostname = ""; } else { hostname = hostname + " / "; } hostname = hostname + addr.getHostAddress(); } catch (final UnknownHostException e) { hostname = "Unavailable"; } } return hostname; } else if ("VERSION".equalsIgnoreCase(key)) { return Integer.toString(ServiceInterface.API_VERSION); } else if ("NAME".equalsIgnoreCase(key)) { return "Webservice (REST/SOAP) interface"; } else if ("BACKEND_VERSION".equalsIgnoreCase(key)) { return BACKEND_VERSION; } return null; }
diff --git a/svnkit/src/test/java/org/tmatesoft/svn/test/WorkingCopy.java b/svnkit/src/test/java/org/tmatesoft/svn/test/WorkingCopy.java index c27faeab6..801439146 100644 --- a/svnkit/src/test/java/org/tmatesoft/svn/test/WorkingCopy.java +++ b/svnkit/src/test/java/org/tmatesoft/svn/test/WorkingCopy.java @@ -1,380 +1,380 @@ package org.tmatesoft.svn.test; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.wc.SVNFileListUtil; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.internal.wc17.db.ISVNWCDb; import org.tmatesoft.svn.core.wc.SVNClientManager; import org.tmatesoft.svn.core.wc.SVNCommitClient; import org.tmatesoft.svn.core.wc.SVNCopyClient; import org.tmatesoft.svn.core.wc.SVNCopySource; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNUpdateClient; import org.tmatesoft.svn.core.wc.SVNWCClient; public class WorkingCopy { private final TestOptions testOptions; private final File workingCopyDirectory; private SVNClientManager clientManager; private long currentRevision; private PrintWriter logger; private SVNURL repositoryUrl; public WorkingCopy(String testName, File workingCopyDirectory) { this(TestOptions.getInstance(), workingCopyDirectory); } public WorkingCopy(TestOptions testOptions, File workingCopyDirectory) { this.testOptions = testOptions; this.workingCopyDirectory = workingCopyDirectory; this.currentRevision = -1; } public long checkoutLatestRevision(SVNURL repositoryUrl) throws SVNException { beforeOperation(); - delete(getLogFile()); + SVNFileUtil.deleteFile(getLogFile()); log("Checking out " + repositoryUrl); final SVNUpdateClient updateClient = getClientManager().getUpdateClient(); this.repositoryUrl = repositoryUrl; final boolean isWcExists = getWorkingCopyDirectory().isDirectory(); try { currentRevision = updateClient.doCheckout(repositoryUrl, getWorkingCopyDirectory(), SVNRevision.HEAD, SVNRevision.HEAD, SVNDepth.INFINITY, true); } catch (SVNException e) { if (isWcExists) { SVNFileUtil.deleteAll(getWorkingCopyDirectory(), true); currentRevision = updateClient.doCheckout(repositoryUrl, getWorkingCopyDirectory(), SVNRevision.HEAD, SVNRevision.HEAD, SVNDepth.INFINITY, true); } else { throw e; } } log("Checked out " + repositoryUrl); afterOperation(); return currentRevision; } public void updateToRevision(long revision) throws SVNException { beforeOperation(); log("Updating to revision " + revision); final SVNUpdateClient updateClient = getClientManager().getUpdateClient(); currentRevision = updateClient.doUpdate(getWorkingCopyDirectory(), SVNRevision.create(revision), SVNDepth.INFINITY, true, true); log("Updated to revision " + currentRevision); afterOperation(); } public File findAnyDirectory() { final File workingCopyDirectory = getWorkingCopyDirectory(); final File[] files = SVNFileListUtil.listFiles(workingCopyDirectory); if (files != null) { for (File file : files) { if (file.isDirectory() && !file.getName().equals(SVNFileUtil.getAdminDirectoryName())) { return file; } } } throw new RuntimeException("The repository contains no directories, run the tests with another repository"); } public File findAnotherDirectory(File directory) { final File workingCopyDirectory = getWorkingCopyDirectory(); final File[] files = SVNFileListUtil.listFiles(workingCopyDirectory); if (files != null) { for (File file : files) { if (file.isDirectory() && !file.getName().equals(SVNFileUtil.getAdminDirectoryName()) && !file.getAbsolutePath().equals(directory.getAbsolutePath())) { return file; } } } throw new RuntimeException("The repository root should contain at least two directories, please run the tests with another repository"); } public void copyAsChild(File directory, File anotherDirectory) throws SVNException { beforeOperation(); log("Copying " + directory + " as a child of " + anotherDirectory); final SVNCopyClient copyClient = getClientManager().getCopyClient(); copyClient.doCopy(new SVNCopySource[]{ new SVNCopySource(SVNRevision.WORKING, SVNRevision.WORKING, directory)}, anotherDirectory, false, false, false); log("Copyied " + directory + " as a child of " + anotherDirectory); afterOperation(); } public long commit(String commitMessage) throws SVNException { beforeOperation(); log("Committing "); final SVNCommitClient commitClient = getClientManager().getCommitClient(); final SVNCommitInfo commitInfo = commitClient.doCommit(new File[]{getWorkingCopyDirectory()}, false, commitMessage, null, null, false, true, SVNDepth.INFINITY); log("Committed revision " + commitInfo.getNewRevision()); afterOperation(); return commitInfo.getNewRevision(); } public void add(File file) throws SVNException { beforeOperation(); log("Adding " + file); final SVNWCClient wcClient = getClientManager().getWCClient(); wcClient.doAdd(file, false, false, false, SVNDepth.INFINITY, true, true, true); log("Added " + file); afterOperation(); } public void revert() throws SVNException { beforeOperation(); log("Reverting working copy"); final SVNWCClient wcClient = getClientManager().getWCClient(); wcClient.doRevert(new File[]{getWorkingCopyDirectory()}, SVNDepth.INFINITY, null); log("Reverted working copy"); afterOperation(); } public List<File> getChildren() { final List<File> childrenList = new ArrayList<File>(); final File[] children = SVNFileListUtil.listFiles(getWorkingCopyDirectory()); if (children != null) { for (File child : children) { if (!child.getName().equals(SVNFileUtil.getAdminDirectoryName())) { childrenList.add(child); } } } return childrenList; } public void setProperty(File file, String propertyName, SVNPropertyValue propertyValue) throws SVNException { beforeOperation(); log("Setting property " + propertyName + " on " + file); final SVNWCClient wcClient = getClientManager().getWCClient(); wcClient.doSetProperty(file, propertyName, propertyValue, true, SVNDepth.INFINITY, null, null); log("Set property " + propertyName + " on " + file); afterOperation(); } public void delete(File file) throws SVNException { beforeOperation(); log("Deleting " + file); final SVNWCClient wcClient = getClientManager().getWCClient(); wcClient.doDelete(file, true, false); log("Deleted " + file); afterOperation(); } public long getCurrentRevision() { return currentRevision; } public SVNURL getRepositoryUrl() { return repositoryUrl; } private void backupWcDbFile() throws SVNException { final File wcDbFile = getWCDbFile(); if (!wcDbFile.exists()) { return; } final File wcDbBackupFile = new File(getWCDbFile().getAbsolutePath() + ".backup"); SVNFileUtil.copy(wcDbFile, wcDbBackupFile, false, false); log("Backed up wc.db"); } private void checkWorkingCopyConsistency() { final String wcDbPath = getWCDbFile().getAbsolutePath().replace('/', File.separatorChar); final ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.command(getSqlite3Command(), wcDbPath, "pragma integrity_check;"); BufferedReader bufferedReader = null; try { final Process process = processBuilder.start(); if (process != null) { bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); final String line = bufferedReader.readLine(); if (line == null || !"ok".equals(line.trim())) { final String notConsistentMessage = "SVN working copy database is not consistent."; log(notConsistentMessage); throw new RuntimeException(notConsistentMessage); } process.waitFor(); } } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { SVNFileUtil.closeFile(bufferedReader); } } public File getWCDbFile() { return new File(getAdminDirectory(), ISVNWCDb.SDB_FILE); } private File getAdminDirectory() { return new File(getWorkingCopyDirectory(), SVNFileUtil.getAdminDirectoryName()); } public void dispose() { if (clientManager != null) { clientManager.dispose(); clientManager = null; } SVNFileUtil.closeFile(logger); logger = null; } private SVNClientManager getClientManager() { if (clientManager == null) { clientManager = SVNClientManager.newInstance(); } return clientManager; } private TestOptions getTestOptions() { return testOptions; } public File getWorkingCopyDirectory() { return workingCopyDirectory; } private String getSqlite3Command() { return getTestOptions().getSqlite3Command(); } public PrintWriter getLogger() { if (logger == null) { final File adminDirectory = getAdminDirectory(); if (!adminDirectory.exists()) { //not checked out yet return null; } final File testLogFile = getLogFile(); FileWriter fileWriter = null; try { fileWriter = new FileWriter(testLogFile, true); } catch (IOException e) { SVNFileUtil.closeFile(fileWriter); throw new RuntimeException(e); } logger = new PrintWriter(fileWriter); } return logger; } private File getLogFile() { return new File(getAdminDirectory(), "test.log"); } private void log(String message) { final PrintWriter logger = getLogger(); if (logger != null) { logger.println("[" + new Date() + "]" + message); logger.flush(); } } private void beforeOperation() throws SVNException { log(""); backupWcDbFile(); } private void afterOperation() { checkWorkingCopyConsistency(); log("Checked for consistency"); } }
true
true
public long checkoutLatestRevision(SVNURL repositoryUrl) throws SVNException { beforeOperation(); delete(getLogFile()); log("Checking out " + repositoryUrl); final SVNUpdateClient updateClient = getClientManager().getUpdateClient(); this.repositoryUrl = repositoryUrl; final boolean isWcExists = getWorkingCopyDirectory().isDirectory(); try { currentRevision = updateClient.doCheckout(repositoryUrl, getWorkingCopyDirectory(), SVNRevision.HEAD, SVNRevision.HEAD, SVNDepth.INFINITY, true); } catch (SVNException e) { if (isWcExists) { SVNFileUtil.deleteAll(getWorkingCopyDirectory(), true); currentRevision = updateClient.doCheckout(repositoryUrl, getWorkingCopyDirectory(), SVNRevision.HEAD, SVNRevision.HEAD, SVNDepth.INFINITY, true); } else { throw e; } } log("Checked out " + repositoryUrl); afterOperation(); return currentRevision; }
public long checkoutLatestRevision(SVNURL repositoryUrl) throws SVNException { beforeOperation(); SVNFileUtil.deleteFile(getLogFile()); log("Checking out " + repositoryUrl); final SVNUpdateClient updateClient = getClientManager().getUpdateClient(); this.repositoryUrl = repositoryUrl; final boolean isWcExists = getWorkingCopyDirectory().isDirectory(); try { currentRevision = updateClient.doCheckout(repositoryUrl, getWorkingCopyDirectory(), SVNRevision.HEAD, SVNRevision.HEAD, SVNDepth.INFINITY, true); } catch (SVNException e) { if (isWcExists) { SVNFileUtil.deleteAll(getWorkingCopyDirectory(), true); currentRevision = updateClient.doCheckout(repositoryUrl, getWorkingCopyDirectory(), SVNRevision.HEAD, SVNRevision.HEAD, SVNDepth.INFINITY, true); } else { throw e; } } log("Checked out " + repositoryUrl); afterOperation(); return currentRevision; }
diff --git a/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest11b.java b/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest11b.java index 30e4151..c54830d 100644 --- a/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest11b.java +++ b/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest11b.java @@ -1,145 +1,145 @@ package org.akquinet.audit.bsi.httpd; import java.util.LinkedList; import java.util.List; import org.akquinet.audit.FormattedConsole; import org.akquinet.audit.YesNoQuestion; import org.akquinet.httpd.ConfigFile; import org.akquinet.httpd.syntax.Context; import org.akquinet.httpd.syntax.Directive; import org.akquinet.httpd.syntax.Statement; public class Quest11b implements YesNoQuestion { private static final String _id = "Quest11b"; private ConfigFile _conf; private static final FormattedConsole _console = FormattedConsole.getDefault(); private static final FormattedConsole.OutputLevel _level = FormattedConsole.OutputLevel.Q2; public Quest11b(ConfigFile conf) { _conf = conf; } /** * checks whether there are any Include-directives in the config file */ @Override public boolean answer() { - //TODO check whether all cases are handled (correctly) + // TODO check whether all cases are handled (correctly) List<Statement> statList = _conf.getHeadExpression().getStatements()._statements; List<Context> dirList = createDirectoryRoot_List(statList); boolean ret = false; for (Context dir : dirList) { if (!dir.getDirectiveIgnoreCase("allow").isEmpty()) { _console.printAnswer(_level, false, "Nobody should be able to access \"/\". Remove the following \"Allow\" directives:"); List<Directive> allowList = dir.getDirectiveIgnoreCase("allow"); for (Directive directive : allowList) { _console.println(_level, directive.getLinenumber() + ": " + directive.getName() + " " + directive.getValue()); } return false; } if (dir.getSurroundingContexts().get(0) != null) { continue; } List<Directive> orderList = dir.getDirectiveIgnoreCase("order"); List<Directive> denyList = dir.getDirectiveIgnoreCase("deny"); if (orderList.size() == 1 && denyList.size() == 1 && orderList.get(0).getLinenumber() > denyList.get(0).getLinenumber()) { Directive order = orderList.get(0); Directive deny = denyList.get(0); // fast evaluation ensures, that only one of these methods can // output an answer-message if (orderIsNotOK(order) || denyIsNotOK(deny)) { return false; } else { _console.printAnswer(_level, true, "Access to \"/\" correctly blocked via mod_access."); ret = true; } } else { _console.printAnswer(_level, false, "I found multiple and/or incorrectly sorted \"Order\" and \"Deny\" directives betwenn lines " - + "-" + dir.getEndLineNumber() + ". Please make them unique, sort them and run me again."); + + dir.getBeginLineNumber() + " and " + dir.getEndLineNumber() + ". Please make them unique, sort them and run me again."); return false; } } return ret; } private static boolean denyIsNotOK(Directive deny) { if (deny.getValue().matches("( |\t)*from all( |\t)*")) { return true; } else { _console.printAnswer(_level, false, "Nobody should be able to access \"/\". Correct the following directive to \"Deny from all\"."); _console.println(_level, deny.getLinenumber() + ": " + deny.getName() + " " + deny.getValue()); return false; } } private static boolean orderIsNotOK(Directive order) { if (order.getValue().matches("( |\t)*from all( |\t)*")) { return true; } else { _console.printAnswer(_level, false, "Nobody should be able to access \"/\". Correct the following directive to \"Order Deny,Allow\"."); _console.println(_level, order.getLinenumber() + ": " + order.getName() + " " + order.getValue()); return false; } } protected static List<Context> createDirectoryRoot_List(List<Statement> statList) { List<Context> conList = new LinkedList<Context>(); for (Statement stat : statList) { if (stat instanceof Context) { Context con = (Context) stat; if (con.getName().equalsIgnoreCase("directory")) { if (con.getSurroundingContexts().size() == 1) { if (con.getValue().matches("( |\t)*/( |\t)*")) { conList.add(con); } } } } } return conList; } @Override public boolean isCritical() { return false; } @Override public String getID() { return _id; } }
false
true
public boolean answer() { //TODO check whether all cases are handled (correctly) List<Statement> statList = _conf.getHeadExpression().getStatements()._statements; List<Context> dirList = createDirectoryRoot_List(statList); boolean ret = false; for (Context dir : dirList) { if (!dir.getDirectiveIgnoreCase("allow").isEmpty()) { _console.printAnswer(_level, false, "Nobody should be able to access \"/\". Remove the following \"Allow\" directives:"); List<Directive> allowList = dir.getDirectiveIgnoreCase("allow"); for (Directive directive : allowList) { _console.println(_level, directive.getLinenumber() + ": " + directive.getName() + " " + directive.getValue()); } return false; } if (dir.getSurroundingContexts().get(0) != null) { continue; } List<Directive> orderList = dir.getDirectiveIgnoreCase("order"); List<Directive> denyList = dir.getDirectiveIgnoreCase("deny"); if (orderList.size() == 1 && denyList.size() == 1 && orderList.get(0).getLinenumber() > denyList.get(0).getLinenumber()) { Directive order = orderList.get(0); Directive deny = denyList.get(0); // fast evaluation ensures, that only one of these methods can // output an answer-message if (orderIsNotOK(order) || denyIsNotOK(deny)) { return false; } else { _console.printAnswer(_level, true, "Access to \"/\" correctly blocked via mod_access."); ret = true; } } else { _console.printAnswer(_level, false, "I found multiple and/or incorrectly sorted \"Order\" and \"Deny\" directives betwenn lines " + "-" + dir.getEndLineNumber() + ". Please make them unique, sort them and run me again."); return false; } } return ret; }
public boolean answer() { // TODO check whether all cases are handled (correctly) List<Statement> statList = _conf.getHeadExpression().getStatements()._statements; List<Context> dirList = createDirectoryRoot_List(statList); boolean ret = false; for (Context dir : dirList) { if (!dir.getDirectiveIgnoreCase("allow").isEmpty()) { _console.printAnswer(_level, false, "Nobody should be able to access \"/\". Remove the following \"Allow\" directives:"); List<Directive> allowList = dir.getDirectiveIgnoreCase("allow"); for (Directive directive : allowList) { _console.println(_level, directive.getLinenumber() + ": " + directive.getName() + " " + directive.getValue()); } return false; } if (dir.getSurroundingContexts().get(0) != null) { continue; } List<Directive> orderList = dir.getDirectiveIgnoreCase("order"); List<Directive> denyList = dir.getDirectiveIgnoreCase("deny"); if (orderList.size() == 1 && denyList.size() == 1 && orderList.get(0).getLinenumber() > denyList.get(0).getLinenumber()) { Directive order = orderList.get(0); Directive deny = denyList.get(0); // fast evaluation ensures, that only one of these methods can // output an answer-message if (orderIsNotOK(order) || denyIsNotOK(deny)) { return false; } else { _console.printAnswer(_level, true, "Access to \"/\" correctly blocked via mod_access."); ret = true; } } else { _console.printAnswer(_level, false, "I found multiple and/or incorrectly sorted \"Order\" and \"Deny\" directives betwenn lines " + dir.getBeginLineNumber() + " and " + dir.getEndLineNumber() + ". Please make them unique, sort them and run me again."); return false; } } return ret; }
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCommit.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCommit.java index 27478425d..d6daa5e9b 100644 --- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCommit.java +++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCommit.java @@ -1,364 +1,365 @@ package org.tmatesoft.svn.core.internal.wc2.ng; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.TreeMap; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNSkel; import org.tmatesoft.svn.core.internal.wc.SVNCommitUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNEventFactory; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.internal.wc.SVNPropertiesManager; import org.tmatesoft.svn.core.internal.wc17.SVNCommitMediator17; import org.tmatesoft.svn.core.internal.wc17.SVNCommitter17; import org.tmatesoft.svn.core.internal.wc17.SVNWCContext; import org.tmatesoft.svn.core.internal.wc17.db.ISVNWCDb.SVNWCDbKind; import org.tmatesoft.svn.core.internal.wc17.db.ISVNWCDb.SVNWCDbStatus; import org.tmatesoft.svn.core.internal.wc17.db.Structure; import org.tmatesoft.svn.core.internal.wc17.db.StructureFields.NodeInfo; import org.tmatesoft.svn.core.internal.wc2.ISvnCommitRunner; import org.tmatesoft.svn.core.internal.wc2.ng.SvnNgCommitUtil.ISvnUrlKindCallback; import org.tmatesoft.svn.core.io.ISVNEditor; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.ISVNEventHandler; import org.tmatesoft.svn.core.wc.SVNEventAction; import org.tmatesoft.svn.core.wc2.SvnChecksum; import org.tmatesoft.svn.core.wc2.SvnCommit; import org.tmatesoft.svn.core.wc2.SvnCommitItem; import org.tmatesoft.svn.core.wc2.SvnCommitPacket; import org.tmatesoft.svn.core.wc2.SvnTarget; import org.tmatesoft.svn.util.SVNLogType; public class SvnNgCommit extends SvnNgOperationRunner<SVNCommitInfo, SvnCommit> implements ISvnCommitRunner, ISvnUrlKindCallback { public SvnCommitPacket collectCommitItems(SvnCommit operation) throws SVNException { setOperation(operation); SvnCommitPacket packet = new SvnCommitPacket(); Collection<String> targets = new ArrayList<String>(); String[] validatedPaths = new String[getOperation().getTargets().size()]; int i = 0; for(SvnTarget target : getOperation().getTargets()) { validatedPaths[i] = target.getFile().getAbsolutePath(); validatedPaths[i] = validatedPaths[i].replace(File.separatorChar, '/'); i++; } String rootPath = SVNPathUtil.condencePaths(validatedPaths, targets, false); if (rootPath == null) { return packet; } File baseDir = new File(rootPath).getAbsoluteFile(); if (targets.isEmpty()) { targets.add(""); } Collection<File> lockTargets = determineLockTargets(baseDir, targets); Collection<File> lockedRoots = new HashSet<File>(); try { for (File lockTarget : lockTargets) { File lockRoot = getWcContext().acquireWriteLock(lockTarget, false, true); lockedRoots.add(lockRoot); } packet.setLockingContext(this, lockedRoots); Map<SVNURL, String> lockTokens = new HashMap<SVNURL, String>(); SvnNgCommitUtil.harversCommittables(getWcContext(), packet, lockTokens, baseDir, targets, getOperation().getDepth(), !getOperation().isKeepLocks(), getOperation().getApplicableChangelists(), this, getOperation().getCommitParameters(), null); packet.setLockTokens(lockTokens); if (packet.getRepositoryRoots().size() > 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Commit can only commit to a single repository at a time.\n" + "Are all targets part of the same working copy?"); SVNErrorManager.error(err, SVNLogType.WC); } if (!packet.isEmpty()) { return packet; } else { packet.dispose(); return new SvnCommitPacket(); } } catch (SVNException e) { packet.dispose(); SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); SVNErrorManager.error(err, SVNLogType.WC); } return null; } @Override protected SVNCommitInfo run(SVNWCContext context) throws SVNException { SVNCommitInfo info = doRun(context); if (info != null) { getOperation().receive(getOperation().getFirstTarget(), info); } return info; } protected SVNCommitInfo doRun(SVNWCContext context) throws SVNException { SvnCommitPacket packet = getOperation().collectCommitItems(); if (packet == null || packet.isEmpty()) { return null; } SVNProperties revisionProperties = getOperation().getRevisionProperties(); SVNPropertiesManager.validateRevisionProperties(revisionProperties); String commitMessage = getOperation().getCommitMessage(); if (getOperation().getCommitHandler() != null) { Collection<SvnCommitItem> items = new ArrayList<SvnCommitItem>(); for (SVNURL rootUrl : packet.getRepositoryRoots()) { items.addAll(packet.getItems(rootUrl)); } SvnCommitItem[] itemsArray = items.toArray(new SvnCommitItem[items.size()]); commitMessage = getOperation().getCommitHandler().getCommitMessage(commitMessage, itemsArray); revisionProperties = getOperation().getCommitHandler().getRevisionProperties(commitMessage, itemsArray, revisionProperties); } boolean keepLocks = getOperation().isKeepLocks(); SVNException bumpError = null; SVNCommitInfo info = null; try { SVNURL repositoryRootUrl = packet.getRepositoryRoots().iterator().next(); if (packet.isEmpty(repositoryRootUrl)) { return SVNCommitInfo.NULL; } Map<String, SvnCommitItem> committables = new TreeMap<String, SvnCommitItem>(); Map<File, SvnChecksum> md5Checksums = new HashMap<File, SvnChecksum>(); Map<File, SvnChecksum> sha1Checksums = new HashMap<File, SvnChecksum>(); SVNURL baseURL = SvnNgCommitUtil.translateCommitables(packet.getItems(repositoryRootUrl), committables); Map<String, String> lockTokens = SvnNgCommitUtil.translateLockTokens(packet.getLockTokens(), baseURL); SvnCommitItem firstItem = packet.getItems(repositoryRootUrl).iterator().next(); SVNRepository repository = getRepositoryAccess().createRepository(baseURL, firstItem.getPath()); SVNCommitMediator17 mediator = new SVNCommitMediator17(context, committables); - ISVNEditor commitEditor = repository.getCommitEditor(commitMessage, lockTokens, keepLocks, revisionProperties, mediator); + ISVNEditor commitEditor = null; try { + commitEditor = repository.getCommitEditor(commitMessage, lockTokens, keepLocks, revisionProperties, mediator); SVNCommitter17 committer = new SVNCommitter17(context, committables, repositoryRootUrl, mediator.getTmpFiles(), md5Checksums, sha1Checksums); SVNCommitUtil.driveCommitEditor(committer, committables.keySet(), commitEditor, -1); committer.sendTextDeltas(commitEditor); info = commitEditor.closeEdit(); commitEditor = null; if (info.getErrorMessage() == null || info.getErrorMessage().getErrorCode() == SVNErrorCode.REPOS_POST_COMMIT_HOOK_FAILED) { // do some post processing, make sure not to unlock wc (to dipose packet) in case there // is an error on post processing. SvnCommittedQueue queue = new SvnCommittedQueue(); try { for (SvnCommitItem item : packet.getItems(repositoryRootUrl)) { postProcessCommitItem(queue, item, getOperation().isKeepChangelists(), getOperation().isKeepLocks(), sha1Checksums.get(item.getPath())); } processCommittedQueue(queue, info.getNewRevision(), info.getDate(), info.getAuthor()); deleteDeleteFiles(committer, getOperation().getCommitParameters()); } catch (SVNException e) { // this is bump error. bumpError = e; throw e; } finally { sleepForTimestamp(); } } handleEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, info.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, SVNEventAction.COMMIT_COMPLETED, null, null, -1, -1)); } catch (SVNException e) { if (e instanceof SVNCancelException) { throw e; } SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); info = new SVNCommitInfo(-1, null, null, err); handleEvent(SVNEventFactory.createErrorEvent(err, SVNEventAction.COMMIT_COMPLETED), ISVNEventHandler.UNKNOWN); if (packet.getRepositoryRoots().size() == 1) { SVNErrorManager.error(err, SVNLogType.WC); } } finally { if (commitEditor != null) { commitEditor.abortEdit(); } for (File tmpFile : mediator.getTmpFiles()) { SVNFileUtil.deleteFile(tmpFile); } } } finally { if (bumpError == null) { packet.dispose(); } } return info; } private void postProcessCommitItem(SvnCommittedQueue queue, SvnCommitItem item, boolean keepChangelists, boolean keepLocks, SvnChecksum sha1Checksum) { boolean removeLock = !keepLocks && item.hasFlag(SvnCommitItem.LOCK); queueCommitted(queue, item.getPath(), false, null /*item.getIncomingProperties()*/, removeLock, !keepChangelists, sha1Checksum); } public SVNNodeKind getUrlKind(SVNURL url, long revision) throws SVNException { return getRepositoryAccess().createRepository(url, null).checkPath("", revision); } private Collection<File> determineLockTargets(File baseDirectory, Collection<String> targets) throws SVNException { Map<File, Collection<File>> wcItems = new HashMap<File, Collection<File>>(); for (String t: targets) { File target = SVNFileUtil.createFilePath(baseDirectory, t); File wcRoot = null; try { wcRoot = getWcContext().getDb().getWCRoot(target); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_PATH_NOT_FOUND) { continue; } throw e; } Collection<File> wcTargets = wcItems.get(wcRoot); if (wcTargets == null) { wcTargets = new HashSet<File>(); wcItems.put(wcRoot, wcTargets); } wcTargets.add(target); } Collection<File> lockTargets = new HashSet<File>(); for (File wcRoot : wcItems.keySet()) { Collection<File> wcTargets = wcItems.get(wcRoot); if (wcTargets.size() == 1) { if (wcRoot.equals(wcTargets.iterator().next())) { lockTargets.add(wcRoot); } else { lockTargets.add(SVNFileUtil.getParentFile(wcTargets.iterator().next())); } } else if (wcTargets.size() > 1) { lockTargets.add(wcRoot); } } return lockTargets; } public void disposeCommitPacket(Object lockingContext) throws SVNException { if (!(lockingContext instanceof Collection)) { return; } @SuppressWarnings("unchecked") Collection<File> lockedPaths = (Collection<File>) lockingContext; for (File lockedPath : lockedPaths) { try { getWcContext().releaseWriteLock(lockedPath); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() != SVNErrorCode.WC_NOT_LOCKED) { throw e; } } } getWcContext().close(); } private void queueCommitted(SvnCommittedQueue queue, File localAbsPath, boolean recurse, SVNProperties wcPropChanges, boolean removeLock, boolean removeChangelist, SvnChecksum sha1Checksum) { SvnCommittedQueueItem cqi = new SvnCommittedQueueItem(); cqi.localAbspath = localAbsPath; cqi.recurse = recurse; cqi.noUnlock = !removeLock; cqi.keepChangelist = !removeChangelist; cqi.sha1Checksum = sha1Checksum; cqi.newDavCache = wcPropChanges; queue.queue.put(localAbsPath, cqi); } private void processCommittedQueue(SvnCommittedQueue queue, long newRevision, Date revDate, String revAuthor) throws SVNException { Collection<File> roots = new HashSet<File>(); for (SvnCommittedQueueItem cqi : queue.queue.values()) { processCommittedInternal(cqi.localAbspath, cqi.recurse, true, newRevision, new SVNDate(revDate.getTime(), 0), revAuthor, cqi.newDavCache, cqi.noUnlock, cqi.keepChangelist, cqi.sha1Checksum, queue); File root = getWcContext().getDb().getWCRoot(cqi.localAbspath); roots.add(root); } for (File root : roots) { getWcContext().wqRun(root); } queue.queue.clear(); } private void processCommittedInternal(File localAbspath, boolean recurse, boolean topOfRecurse, long newRevision, SVNDate revDate, String revAuthor, SVNProperties newDavCache, boolean noUnlock, boolean keepChangelist, SvnChecksum sha1Checksum, SvnCommittedQueue queue) throws SVNException { processCommittedLeaf(localAbspath, !topOfRecurse, newRevision, revDate, revAuthor, newDavCache, noUnlock, keepChangelist, sha1Checksum); } private void processCommittedLeaf(File localAbspath, boolean viaRecurse, long newRevnum, SVNDate newChangedDate, String newChangedAuthor, SVNProperties newDavCache, boolean noUnlock, boolean keepChangelist, SvnChecksum checksum) throws SVNException { long newChangedRev = newRevnum; assert (SVNFileUtil.isAbsolute(localAbspath)); Structure<NodeInfo> nodeInfo = getWcContext().getDb().readInfo(localAbspath, NodeInfo.status, NodeInfo.kind, NodeInfo.checksum, NodeInfo.hadProps, NodeInfo.propsMod, NodeInfo.haveBase, NodeInfo.haveWork); File admAbspath; if (nodeInfo.get(NodeInfo.kind) == SVNWCDbKind.Dir) { admAbspath = localAbspath; } else { admAbspath = SVNFileUtil.getFileDir(localAbspath); } getWcContext().writeCheck(admAbspath); if (nodeInfo.get(NodeInfo.status) == SVNWCDbStatus.Deleted) { getWcContext().getDb().opRemoveNode(localAbspath, nodeInfo.is(NodeInfo.haveBase) && !viaRecurse ? newRevnum : -1, nodeInfo.<SVNWCDbKind>get(NodeInfo.kind)); nodeInfo.release(); return; } else if (nodeInfo.get(NodeInfo.status) == SVNWCDbStatus.NotPresent) { nodeInfo.release(); return; } SVNSkel workItem = null; SVNWCDbKind kind = nodeInfo.get(NodeInfo.kind); if (kind != SVNWCDbKind.Dir) { if (checksum == null) { checksum = nodeInfo.get(NodeInfo.checksum); if (viaRecurse && !nodeInfo.is(NodeInfo.propsMod)) { Structure<NodeInfo> moreInfo = getWcContext().getDb(). readInfo(localAbspath, NodeInfo.changedRev, NodeInfo.changedDate, NodeInfo.changedAuthor); newChangedRev = moreInfo.lng(NodeInfo.changedRev); newChangedDate = moreInfo.get(NodeInfo.changedDate); newChangedAuthor = moreInfo.get(NodeInfo.changedAuthor); moreInfo.release(); } } workItem = getWcContext().wqBuildFileCommit(localAbspath, nodeInfo.is(NodeInfo.propsMod)); } getWcContext().getDb().globalCommit(localAbspath, newRevnum, newChangedRev, newChangedDate, newChangedAuthor, checksum, null, newDavCache, keepChangelist, noUnlock, workItem); } private static class SvnCommittedQueue { @SuppressWarnings("unchecked") public Map<File, SvnCommittedQueueItem> queue = new TreeMap<File, SvnCommittedQueueItem>(SVNCommitUtil.FILE_COMPARATOR); }; private static class SvnCommittedQueueItem { public File localAbspath; public boolean recurse; public boolean noUnlock; public boolean keepChangelist; public SvnChecksum sha1Checksum; public SVNProperties newDavCache; }; }
false
true
protected SVNCommitInfo doRun(SVNWCContext context) throws SVNException { SvnCommitPacket packet = getOperation().collectCommitItems(); if (packet == null || packet.isEmpty()) { return null; } SVNProperties revisionProperties = getOperation().getRevisionProperties(); SVNPropertiesManager.validateRevisionProperties(revisionProperties); String commitMessage = getOperation().getCommitMessage(); if (getOperation().getCommitHandler() != null) { Collection<SvnCommitItem> items = new ArrayList<SvnCommitItem>(); for (SVNURL rootUrl : packet.getRepositoryRoots()) { items.addAll(packet.getItems(rootUrl)); } SvnCommitItem[] itemsArray = items.toArray(new SvnCommitItem[items.size()]); commitMessage = getOperation().getCommitHandler().getCommitMessage(commitMessage, itemsArray); revisionProperties = getOperation().getCommitHandler().getRevisionProperties(commitMessage, itemsArray, revisionProperties); } boolean keepLocks = getOperation().isKeepLocks(); SVNException bumpError = null; SVNCommitInfo info = null; try { SVNURL repositoryRootUrl = packet.getRepositoryRoots().iterator().next(); if (packet.isEmpty(repositoryRootUrl)) { return SVNCommitInfo.NULL; } Map<String, SvnCommitItem> committables = new TreeMap<String, SvnCommitItem>(); Map<File, SvnChecksum> md5Checksums = new HashMap<File, SvnChecksum>(); Map<File, SvnChecksum> sha1Checksums = new HashMap<File, SvnChecksum>(); SVNURL baseURL = SvnNgCommitUtil.translateCommitables(packet.getItems(repositoryRootUrl), committables); Map<String, String> lockTokens = SvnNgCommitUtil.translateLockTokens(packet.getLockTokens(), baseURL); SvnCommitItem firstItem = packet.getItems(repositoryRootUrl).iterator().next(); SVNRepository repository = getRepositoryAccess().createRepository(baseURL, firstItem.getPath()); SVNCommitMediator17 mediator = new SVNCommitMediator17(context, committables); ISVNEditor commitEditor = repository.getCommitEditor(commitMessage, lockTokens, keepLocks, revisionProperties, mediator); try { SVNCommitter17 committer = new SVNCommitter17(context, committables, repositoryRootUrl, mediator.getTmpFiles(), md5Checksums, sha1Checksums); SVNCommitUtil.driveCommitEditor(committer, committables.keySet(), commitEditor, -1); committer.sendTextDeltas(commitEditor); info = commitEditor.closeEdit(); commitEditor = null; if (info.getErrorMessage() == null || info.getErrorMessage().getErrorCode() == SVNErrorCode.REPOS_POST_COMMIT_HOOK_FAILED) { // do some post processing, make sure not to unlock wc (to dipose packet) in case there // is an error on post processing. SvnCommittedQueue queue = new SvnCommittedQueue(); try { for (SvnCommitItem item : packet.getItems(repositoryRootUrl)) { postProcessCommitItem(queue, item, getOperation().isKeepChangelists(), getOperation().isKeepLocks(), sha1Checksums.get(item.getPath())); } processCommittedQueue(queue, info.getNewRevision(), info.getDate(), info.getAuthor()); deleteDeleteFiles(committer, getOperation().getCommitParameters()); } catch (SVNException e) { // this is bump error. bumpError = e; throw e; } finally { sleepForTimestamp(); } } handleEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, info.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, SVNEventAction.COMMIT_COMPLETED, null, null, -1, -1)); } catch (SVNException e) { if (e instanceof SVNCancelException) { throw e; } SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); info = new SVNCommitInfo(-1, null, null, err); handleEvent(SVNEventFactory.createErrorEvent(err, SVNEventAction.COMMIT_COMPLETED), ISVNEventHandler.UNKNOWN); if (packet.getRepositoryRoots().size() == 1) { SVNErrorManager.error(err, SVNLogType.WC); } } finally { if (commitEditor != null) { commitEditor.abortEdit(); } for (File tmpFile : mediator.getTmpFiles()) { SVNFileUtil.deleteFile(tmpFile); } } } finally { if (bumpError == null) { packet.dispose(); } } return info; }
protected SVNCommitInfo doRun(SVNWCContext context) throws SVNException { SvnCommitPacket packet = getOperation().collectCommitItems(); if (packet == null || packet.isEmpty()) { return null; } SVNProperties revisionProperties = getOperation().getRevisionProperties(); SVNPropertiesManager.validateRevisionProperties(revisionProperties); String commitMessage = getOperation().getCommitMessage(); if (getOperation().getCommitHandler() != null) { Collection<SvnCommitItem> items = new ArrayList<SvnCommitItem>(); for (SVNURL rootUrl : packet.getRepositoryRoots()) { items.addAll(packet.getItems(rootUrl)); } SvnCommitItem[] itemsArray = items.toArray(new SvnCommitItem[items.size()]); commitMessage = getOperation().getCommitHandler().getCommitMessage(commitMessage, itemsArray); revisionProperties = getOperation().getCommitHandler().getRevisionProperties(commitMessage, itemsArray, revisionProperties); } boolean keepLocks = getOperation().isKeepLocks(); SVNException bumpError = null; SVNCommitInfo info = null; try { SVNURL repositoryRootUrl = packet.getRepositoryRoots().iterator().next(); if (packet.isEmpty(repositoryRootUrl)) { return SVNCommitInfo.NULL; } Map<String, SvnCommitItem> committables = new TreeMap<String, SvnCommitItem>(); Map<File, SvnChecksum> md5Checksums = new HashMap<File, SvnChecksum>(); Map<File, SvnChecksum> sha1Checksums = new HashMap<File, SvnChecksum>(); SVNURL baseURL = SvnNgCommitUtil.translateCommitables(packet.getItems(repositoryRootUrl), committables); Map<String, String> lockTokens = SvnNgCommitUtil.translateLockTokens(packet.getLockTokens(), baseURL); SvnCommitItem firstItem = packet.getItems(repositoryRootUrl).iterator().next(); SVNRepository repository = getRepositoryAccess().createRepository(baseURL, firstItem.getPath()); SVNCommitMediator17 mediator = new SVNCommitMediator17(context, committables); ISVNEditor commitEditor = null; try { commitEditor = repository.getCommitEditor(commitMessage, lockTokens, keepLocks, revisionProperties, mediator); SVNCommitter17 committer = new SVNCommitter17(context, committables, repositoryRootUrl, mediator.getTmpFiles(), md5Checksums, sha1Checksums); SVNCommitUtil.driveCommitEditor(committer, committables.keySet(), commitEditor, -1); committer.sendTextDeltas(commitEditor); info = commitEditor.closeEdit(); commitEditor = null; if (info.getErrorMessage() == null || info.getErrorMessage().getErrorCode() == SVNErrorCode.REPOS_POST_COMMIT_HOOK_FAILED) { // do some post processing, make sure not to unlock wc (to dipose packet) in case there // is an error on post processing. SvnCommittedQueue queue = new SvnCommittedQueue(); try { for (SvnCommitItem item : packet.getItems(repositoryRootUrl)) { postProcessCommitItem(queue, item, getOperation().isKeepChangelists(), getOperation().isKeepLocks(), sha1Checksums.get(item.getPath())); } processCommittedQueue(queue, info.getNewRevision(), info.getDate(), info.getAuthor()); deleteDeleteFiles(committer, getOperation().getCommitParameters()); } catch (SVNException e) { // this is bump error. bumpError = e; throw e; } finally { sleepForTimestamp(); } } handleEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, info.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, SVNEventAction.COMMIT_COMPLETED, null, null, -1, -1)); } catch (SVNException e) { if (e instanceof SVNCancelException) { throw e; } SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); info = new SVNCommitInfo(-1, null, null, err); handleEvent(SVNEventFactory.createErrorEvent(err, SVNEventAction.COMMIT_COMPLETED), ISVNEventHandler.UNKNOWN); if (packet.getRepositoryRoots().size() == 1) { SVNErrorManager.error(err, SVNLogType.WC); } } finally { if (commitEditor != null) { commitEditor.abortEdit(); } for (File tmpFile : mediator.getTmpFiles()) { SVNFileUtil.deleteFile(tmpFile); } } } finally { if (bumpError == null) { packet.dispose(); } } return info; }
diff --git a/src/org/basex/core/proc/AQuery.java b/src/org/basex/core/proc/AQuery.java index 1addbc08e..1e07e862c 100644 --- a/src/org/basex/core/proc/AQuery.java +++ b/src/org/basex/core/proc/AQuery.java @@ -1,146 +1,147 @@ package org.basex.core.proc; import static org.basex.Text.*; import java.io.IOException; import org.basex.BaseX; import org.basex.core.Process; import org.basex.core.ProgressException; import org.basex.core.Prop; import org.basex.data.DOTSerializer; import org.basex.data.XMLSerializer; import org.basex.io.CachedOutput; import org.basex.io.IO; import org.basex.io.NullOutput; import org.basex.io.PrintOutput; import org.basex.query.QueryException; import org.basex.query.QueryProcessor; import org.basex.util.Performance; /** * Abstract class for database queries. * @author Workgroup DBIS, University of Konstanz 2005-09, ISC License * @author Christian Gruen */ abstract class AQuery extends Process { /** Performance measurements. */ protected final Performance per = new Performance(); /** Performance measurements. */ protected QueryProcessor qp; /** * Constructor. * @param p command properties * @param a arguments */ protected AQuery(final int p, final String... a) { super(p, a); } /** * Returns a new query instance. * @param query query * @return query instance */ protected final boolean query(final String query) { long pars = 0; long comp = 0; long eval = 0; try { for(int i = 0; i < Prop.runs; i++) { qp = new QueryProcessor(query == null ? "" : query, context.current()); progress(qp); qp.parse(); pars += per.getTime(); if(i == 0) plan(qp, false); qp.compile(); if(i == 0) plan(qp, true); comp += per.getTime(); result = qp.query(); eval += per.getTime(); + if(i + 1 < Prop.runs) qp.close(); } // dump some query info if(Prop.info) { info(NL + qp.info()); info(QUERYPARSE + Performance.getTimer(pars, Prop.runs) + NL); info(QUERYCOMPILE + Performance.getTimer(comp, Prop.runs) + NL); info(QUERYEVALUATE + Performance.getTimer(eval, Prop.runs) + NL); } return true; } catch(final QueryException ex) { BaseX.debug(ex); return error(ex.getMessage()); } catch(final ProgressException ex) { if(Prop.server) return error(TIMEOUTERR); return error(""); } catch(final Exception ex) { ex.printStackTrace(); return error(BaseX.bug(ex.getClass().getSimpleName())); } } /** * Outputs the result. * @param o output stream * @param p pretty printing * @throws IOException exception */ protected void out(final PrintOutput o, final boolean p) throws IOException { XMLSerializer ser = new XMLSerializer(Prop.serialize ? o : new NullOutput(), Prop.xmloutput, p); for(int i = 0; i < Prop.runs; i++) { if(i != 0) ser = new XMLSerializer(new NullOutput(!Prop.serialize), Prop.xmloutput, Prop.xqformat); result.serialize(ser); ser.close(); } if(Prop.info) outInfo(o, result.size()); qp.close(); } /** * Adds query information to the information string. * @param out output stream * @param hits information */ protected final void outInfo(final PrintOutput out, final long hits) { info(QUERYPRINT + per.getTimer(Prop.runs) + NL); info(QUERYTOTAL + perf.getTimer(Prop.runs) + NL); info(QUERYHITS + hits + " " + (hits == 1 ? VALHIT : VALHITS) + NL); info(QUERYPRINTED + Performance.format(out.size())); //info(QUERYMEM, Performance.getMem()); } /** * Creates query plans. * @param qu query reference * @param c compiled flag * @throws Exception exception */ private void plan(final QueryProcessor qu, final boolean c) throws Exception { if(c != Prop.compplan) return; // show dot plan if(Prop.dotplan) { final CachedOutput out = new CachedOutput(); final DOTSerializer ser = new DOTSerializer(out); qu.plan(ser); ser.close(); IO.get(PLANDOT).write(out.finish()); new ProcessBuilder(Prop.dotty, PLANDOT).start().waitFor(); //f.delete(); } // dump query plan if(Prop.xmlplan) { final CachedOutput out = new CachedOutput(); qu.plan(new XMLSerializer(out, false, true)); info(NL + QUERYPLAN + NL); info(out.toString() + NL); } // reset timer per.getTime(); } }
true
true
protected final boolean query(final String query) { long pars = 0; long comp = 0; long eval = 0; try { for(int i = 0; i < Prop.runs; i++) { qp = new QueryProcessor(query == null ? "" : query, context.current()); progress(qp); qp.parse(); pars += per.getTime(); if(i == 0) plan(qp, false); qp.compile(); if(i == 0) plan(qp, true); comp += per.getTime(); result = qp.query(); eval += per.getTime(); } // dump some query info if(Prop.info) { info(NL + qp.info()); info(QUERYPARSE + Performance.getTimer(pars, Prop.runs) + NL); info(QUERYCOMPILE + Performance.getTimer(comp, Prop.runs) + NL); info(QUERYEVALUATE + Performance.getTimer(eval, Prop.runs) + NL); } return true; } catch(final QueryException ex) { BaseX.debug(ex); return error(ex.getMessage()); } catch(final ProgressException ex) { if(Prop.server) return error(TIMEOUTERR); return error(""); } catch(final Exception ex) { ex.printStackTrace(); return error(BaseX.bug(ex.getClass().getSimpleName())); } }
protected final boolean query(final String query) { long pars = 0; long comp = 0; long eval = 0; try { for(int i = 0; i < Prop.runs; i++) { qp = new QueryProcessor(query == null ? "" : query, context.current()); progress(qp); qp.parse(); pars += per.getTime(); if(i == 0) plan(qp, false); qp.compile(); if(i == 0) plan(qp, true); comp += per.getTime(); result = qp.query(); eval += per.getTime(); if(i + 1 < Prop.runs) qp.close(); } // dump some query info if(Prop.info) { info(NL + qp.info()); info(QUERYPARSE + Performance.getTimer(pars, Prop.runs) + NL); info(QUERYCOMPILE + Performance.getTimer(comp, Prop.runs) + NL); info(QUERYEVALUATE + Performance.getTimer(eval, Prop.runs) + NL); } return true; } catch(final QueryException ex) { BaseX.debug(ex); return error(ex.getMessage()); } catch(final ProgressException ex) { if(Prop.server) return error(TIMEOUTERR); return error(""); } catch(final Exception ex) { ex.printStackTrace(); return error(BaseX.bug(ex.getClass().getSimpleName())); } }
diff --git a/src/org/wfp/vam/intermap/kernel/TempFiles.java b/src/org/wfp/vam/intermap/kernel/TempFiles.java index f8c8b5961e..6281f2f53f 100644 --- a/src/org/wfp/vam/intermap/kernel/TempFiles.java +++ b/src/org/wfp/vam/intermap/kernel/TempFiles.java @@ -1,111 +1,111 @@ //============================================================================= //=== Copyright (C) 2001-2007 Food and Agriculture Organization of the //=== United Nations (FAO-UN), United Nations World Food Programme (WFP) //=== and United Nations Environment Programme (UNEP) //=== //=== This program is free software; you can redistribute it and/or modify //=== it under the terms of the GNU General Public License as published by //=== the Free Software Foundation; either version 2 of the License, or (at //=== your option) any later version. //=== //=== This program is distributed in the hope that it will be useful, but //=== WITHOUT ANY WARRANTY; without even the implied warranty of //=== MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //=== General Public License for more details. //=== //=== You should have received a copy of the GNU General Public License //=== along with this program; if not, write to the Free Software //=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA //=== //=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, //=== Rome - Italy. email: [email protected] //============================================================================== package org.wfp.vam.intermap.kernel; import java.io.*; import java.util.*; public class TempFiles { protected File _dir; private int minutes; private Timer timer; /** * Periodically starts a process that cleans up the temporary files * every n minutes * */ public TempFiles(String servletEnginePath, String path, int minutes) throws Exception { File p = new File(path); String finalPath; if (p.isAbsolute()) finalPath = path; else finalPath = servletEnginePath + path; _dir = new File(finalPath); if (!_dir.isDirectory()) throw new Exception("Invalid temp directory '" + finalPath + "'"); - timer = new Timer(); + timer = new Timer(true); timer.schedule(new RemindTask(), 0, minutes * 60 * 1000); } public void end() { timer.cancel(); } public File getDir() { return _dir; } /** * Creates a temporary File * * @return a temporary File * * @throws If a file could not be created * */ public File getFile() throws IOException { return getFile(".tmp"); } public File getFile(String extension) throws IOException { if( ! extension.startsWith(".")) extension = "."+extension; File tf = File.createTempFile("temp", extension, getDir()); tf.deleteOnExit(); return tf; } // Delete all the files in the temp directory class RemindTask extends TimerTask { public void run() { for (File f: getDir().listFiles()) { Calendar last = Calendar.getInstance(); last.add(Calendar.MINUTE, -minutes); // Only files whose name start with ".temp" are deleted if (f.getName().startsWith("temp") && last.getTime().after( new Date(f.lastModified())) ) f.delete(); } } } }
true
true
public TempFiles(String servletEnginePath, String path, int minutes) throws Exception { File p = new File(path); String finalPath; if (p.isAbsolute()) finalPath = path; else finalPath = servletEnginePath + path; _dir = new File(finalPath); if (!_dir.isDirectory()) throw new Exception("Invalid temp directory '" + finalPath + "'"); timer = new Timer(); timer.schedule(new RemindTask(), 0, minutes * 60 * 1000); }
public TempFiles(String servletEnginePath, String path, int minutes) throws Exception { File p = new File(path); String finalPath; if (p.isAbsolute()) finalPath = path; else finalPath = servletEnginePath + path; _dir = new File(finalPath); if (!_dir.isDirectory()) throw new Exception("Invalid temp directory '" + finalPath + "'"); timer = new Timer(true); timer.schedule(new RemindTask(), 0, minutes * 60 * 1000); }
diff --git a/src/main/java/org/dasein/cloud/aws/platform/CloudWatch.java b/src/main/java/org/dasein/cloud/aws/platform/CloudWatch.java index 56e11b5..57c2b80 100644 --- a/src/main/java/org/dasein/cloud/aws/platform/CloudWatch.java +++ b/src/main/java/org/dasein/cloud/aws/platform/CloudWatch.java @@ -1,506 +1,506 @@ package org.dasein.cloud.aws.platform; import org.apache.log4j.Logger; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.ProviderContext; import org.dasein.cloud.aws.AWSCloud; import org.dasein.cloud.aws.compute.EC2Exception; import org.dasein.cloud.aws.compute.EC2Method; import org.dasein.cloud.identity.ServiceAction; import org.dasein.cloud.platform.*; import org.dasein.cloud.util.APITrace; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.annotation.Nonnull; import java.util.*; /** * CloudWatch specific implementation of AbstractMonitoringSupport. * * @author Cameron Stokes (http://github.com/clstokes) * @since 2013-02-18 */ public class CloudWatch extends AbstractMonitoringSupport { static private final Logger logger = Logger.getLogger( CloudWatch.class ); public static final String STATE_OK = "OK"; public static final String STATE_ALARM = "ALARM"; public static final String STATE_INSUFFICIENT_DATA = "INSUFFICIENT_DATA"; private AWSCloud provider = null; CloudWatch( AWSCloud provider ) { super( provider ); this.provider = provider; } @Override public void updateAlarm( @Nonnull AlarmUpdateOptions options ) throws InternalException, CloudException { APITrace.begin( provider, "CloudWatch.addAlarm" ); try { ProviderContext ctx = provider.getContext(); if ( ctx == null ) { throw new CloudException( "No context was set for this request" ); } Map<String, String> parameters = provider.getStandardCloudWatchParameters( provider.getContext(), EC2Method.PUT_METRIC_ALARM ); // all required parameters per CloudWatch API Version 2010-08-01 parameters.put( "AlarmName", options.getAlarmName() ); parameters.put( "Namespace", options.getMetricNamespace() ); parameters.put( "MetricName", options.getMetric() ); parameters.put( "Statistic", options.getStatistic() ); parameters.put( "ComparisonOperator", options.getComparisonOperator() ); parameters.put( "Threshold", String.valueOf( options.getThreshold() ) ); parameters.put( "Period", String.valueOf( options.getPeriod() ) ); parameters.put( "EvaluationPeriods", String.valueOf( options.getEvaluationPeriods() ) ); // optional parameters per CloudWatch API Version 2010-08-01 parameters.put( "ActionsEnabled", String.valueOf( options.isEnabled() ) ); provider.putValueIfNotNull( parameters, "AlarmDescription", options.getAlarmDescription() ); provider.putIndexedParameters( parameters, "OKActions.member.", options.getProviderOKActionIds() ); provider.putIndexedParameters( parameters, "AlarmActions.member.", options.getProviderAlarmActionIds() ); provider.putIndexedParameters( parameters, "InsufficientDataActions.member.", options.getProviderInsufficentDataActionIds() ); provider.putIndexedMapParameters( parameters, "Dimensions.member.", options.getMetadata() ); EC2Method method; method = new EC2Method( provider, getCloudWatchUrl(), parameters ); try { method.invoke(); } catch ( EC2Exception e ) { logger.error( e.getSummary() ); throw new CloudException( e ); } } finally { APITrace.end(); } } @Override public void removeAlarms( @Nonnull String[] alarmNames ) throws InternalException, CloudException { APITrace.begin( provider, "CloudWatch.removeAlarms" ); try { updateAlarmAction( alarmNames, EC2Method.DELETE_ALARMS ); } finally { APITrace.end(); } } @Override public void enableAlarmActions( @Nonnull String[] alarmNames ) throws InternalException, CloudException { APITrace.begin( provider, "CloudWatch.enableAlarmActions" ); try { updateAlarmAction( alarmNames, EC2Method.ENABLE_ALARM_ACTIONS ); } finally { APITrace.end(); } } @Override public void disableAlarmActions( @Nonnull String[] alarmNames ) throws InternalException, CloudException { APITrace.begin( provider, "CloudWatch.disableAlarmActions" ); try { updateAlarmAction( alarmNames, EC2Method.DISABLE_ALARM_ACTIONS ); } finally { APITrace.end(); } } private void updateAlarmAction( @Nonnull String[] alarmNames, @Nonnull String action ) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if ( ctx == null ) { throw new CloudException( "No context was set for this request" ); } Map<String, String> parameters = provider.getStandardCloudWatchParameters( provider.getContext(), action ); provider.putIndexedParameters( parameters, "AlarmNames.member.", alarmNames ); EC2Method method; method = new EC2Method( provider, getCloudWatchUrl(), parameters ); try { method.invoke(); } catch ( EC2Exception e ) { logger.error( e.getSummary() ); throw new CloudException( e ); } } @Override public @Nonnull Collection<Alarm> listAlarms( AlarmFilterOptions options ) throws InternalException, CloudException { APITrace.begin( provider, "CloudWatch.listAlarms" ); try { ProviderContext ctx = provider.getContext(); if ( ctx == null ) { throw new CloudException( "No context was set for this request" ); } Map<String, String> parameters = provider.getStandardCloudWatchParameters( provider.getContext(), EC2Method.DESCRIBE_ALARMS ); provider.putExtraParameters( parameters, getAlarmFilterParameters( options ) ); List<Alarm> list = new ArrayList<Alarm>(); NodeList blocks; EC2Method method; Document doc; method = new EC2Method( provider, getCloudWatchUrl(), parameters ); try { doc = method.invoke(); } catch ( EC2Exception e ) { logger.error( e.getSummary() ); throw new CloudException( e ); } blocks = doc.getElementsByTagName( "MetricAlarms" ); for ( int i = 0; i < blocks.getLength(); i++ ) { NodeList metrics = blocks.item( i ).getChildNodes(); for ( int j = 0; j < metrics.getLength(); j++ ) { Node metricNode = metrics.item( j ); if ( metricNode.getNodeName().equals( "member" ) ) { Alarm alarm = toAlarm( metricNode ); if ( alarm != null ) { list.add( alarm ); } } } } return list; } finally { APITrace.end(); } } private Alarm toAlarm( Node node ) throws CloudException, InternalException { if ( node == null ) { return null; } Alarm alarm = new Alarm(); alarm.setFunction( false ); // CloudWatch doesn't use a DSL or function for it's alarms. It uses statistic, comparisonOperator, and threshold. NodeList attributes = node.getChildNodes(); for ( int i = 0; i < attributes.getLength(); i++ ) { Node attribute = attributes.item( i ); String name = attribute.getNodeName(); if ( name.equals( "AlarmName" ) ) { alarm.setName( provider.getTextValue( attribute ) ); } else if ( name.equals( "AlarmDescription" ) ) { alarm.setDescription( provider.getTextValue( attribute ) ); } else if ( name.equals( "Namespace" ) ) { alarm.setMetricNamespace( provider.getTextValue( attribute ) ); } else if ( name.equals( "MetricName" ) ) { alarm.setMetric( provider.getTextValue( attribute ) ); } else if ( name.equals( "Dimensions" ) ) { Map<String, String> dimensions = toMetadata( attribute.getChildNodes() ); if ( dimensions != null ) { alarm.addMetricMetadata( dimensions ); } } else if ( name.equals( "ActionsEnabled" ) ) { alarm.setEnabled( "true".equals( provider.getTextValue( attribute ) ) ); } else if ( name.equals( "AlarmArn" ) ) { alarm.setProviderAlarmId( provider.getTextValue( attribute ) ); } else if ( name.equals( "AlarmActions" ) ) { alarm.setProviderAlarmActionIds( getMembersValues( attribute ) ); } else if ( name.equals( "InsufficientDataActions" ) ) { - alarm.setProviderInsufficentDataActionIds( getMembersValues( attribute ) ); + alarm.setProviderInsufficientDataActionIds( getMembersValues( attribute ) ); } else if ( name.equals( "OKActions" ) ) { alarm.setProviderOKActionIds( getMembersValues( attribute ) ); } else if ( name.equals( "Statistic" ) ) { alarm.setStatistic( provider.getTextValue( attribute ) ); } else if ( name.equals( "Period" ) ) { alarm.setPeriod( provider.getIntValue( attribute ) ); } else if ( name.equals( "EvaluationPeriods" ) ) { alarm.setEvaluationPeriods( provider.getIntValue( attribute ) ); } else if ( name.equals( "ComparisonOperator" ) ) { alarm.setComparisonOperator( provider.getTextValue( attribute ) ); } else if ( name.equals( "Threshold" ) ) { alarm.setThreshold( provider.getDoubleValue( attribute ) ); } else if ( name.equals( "StateReason" ) ) { alarm.setStateReason( provider.getTextValue( attribute ) ); } else if ( name.equals( "StateReasonData" ) ) { alarm.setStateReasonData( provider.getTextValue( attribute ) ); } else if ( name.equals( "StateUpdatedTimestamp" ) ) { alarm.setStateUpdatedTimestamp( provider.getTimestampValue( attribute ) ); } else if ( name.equals( "StateValue" ) ) { String stateValue = provider.getTextValue( attribute ); if ( STATE_OK.equals( stateValue ) ) { alarm.setStateValue( AlarmState.OK ); } else if ( STATE_ALARM.equals( stateValue ) ) { alarm.setStateValue( AlarmState.ALARM ); } else if ( STATE_INSUFFICIENT_DATA.equals( stateValue ) ) { alarm.setStateValue( AlarmState.INSUFFICIENT_DATA ); } } } return alarm; } /** * Gets single text values from a "member" set. * * @param attribute the node to start at * @return array of member string values */ private String[] getMembersValues( Node attribute ) { List<String> actions = new ArrayList<String>(); NodeList actionNodes = attribute.getChildNodes(); for ( int j = 0; j < actionNodes.getLength(); j++ ) { Node actionNode = actionNodes.item( j ); if ( actionNode.getNodeName().equals( "member" ) ) { actions.add( provider.getTextValue( actionNode ) ); } } if ( actions.size() == 0 ) { return null; } return actions.toArray( new String[] {} ); } @Override public @Nonnull Collection<Metric> listMetrics( MetricFilterOptions options ) throws InternalException, CloudException { APITrace.begin( provider, "CloudWatch.listMetrics" ); try { ProviderContext ctx = provider.getContext(); if ( ctx == null ) { throw new CloudException( "No context was set for this request" ); } Map<String, String> parameters = provider.getStandardCloudWatchParameters( provider.getContext(), EC2Method.LIST_METRICS ); provider.putExtraParameters( parameters, getMetricFilterParameters( options ) ); List<Metric> list = new ArrayList<Metric>(); NodeList blocks; EC2Method method; Document doc; method = new EC2Method( provider, getCloudWatchUrl(), parameters ); try { doc = method.invoke(); } catch ( EC2Exception e ) { logger.error( e.getSummary() ); throw new CloudException( e ); } blocks = doc.getElementsByTagName( "Metrics" ); for ( int i = 0; i < blocks.getLength(); i++ ) { NodeList metrics = blocks.item( i ).getChildNodes(); for ( int j = 0; j < metrics.getLength(); j++ ) { Node metricNode = metrics.item( j ); if ( metricNode.getNodeName().equals( "member" ) ) { Metric metric = toMetric( metricNode ); if ( metric != null ) { list.add( metric ); } } } } return list; } finally { APITrace.end(); } } /** * Converts the given node to a Metric object. * * @param node the node to convert * @return a Metric object */ private Metric toMetric( Node node ) { if ( node == null ) { return null; } Metric metric = new Metric(); NodeList attributes = node.getChildNodes(); for ( int i = 0; i < attributes.getLength(); i++ ) { Node attribute = attributes.item( i ); String name = attribute.getNodeName(); if ( name.equals( "MetricName" ) ) { metric.setName( provider.getTextValue( attribute ) ); } else if ( name.equals( "Namespace" ) ) { metric.setNamespace( provider.getTextValue( attribute ) ); } else if ( name.equals( "Dimensions" ) ) { Map<String, String> dimensions = toMetadata( attribute.getChildNodes() ); if ( dimensions != null ) { metric.addMetadata( dimensions ); } } } return metric; } /** * Converts the given NodeList to a metadata map. * * @param blocks the NodeList to convert * @return metadata map */ private Map<String, String> toMetadata( NodeList blocks ) { Map<String, String> dimensions = new HashMap<String, String>(); for ( int i = 0; i < blocks.getLength(); i++ ) { Node dimensionNode = blocks.item( i ); if ( dimensionNode.getNodeName().equals( "member" ) ) { String dimensionName = null; String dimensionValue = null; NodeList dimensionAttributes = dimensionNode.getChildNodes(); for ( int j = 0; j < dimensionAttributes.getLength(); j++ ) { Node attribute = dimensionAttributes.item( j ); String name = attribute.getNodeName(); if ( name.equals( "Name" ) ) { dimensionName = provider.getTextValue( attribute ); } else if ( name.equals( "Value" ) ) { dimensionValue = provider.getTextValue( attribute ); } } if ( dimensionName != null ) { dimensions.put( dimensionName, dimensionValue ); } } } if ( dimensions.size() == 0 ) { return null; } return dimensions; } /** * Creates map of parameters based on the MetricFilterOptions. * * @param options options to convert to a parameter map * @return parameter map */ private Map<String, String> getMetricFilterParameters( MetricFilterOptions options ) { if ( options == null ) { return null; } Map<String, String> parameters = new HashMap<String, String>(); provider.putValueIfNotNull( parameters, "MetricName", options.getMetricName() ); provider.putValueIfNotNull( parameters, "Namespace", options.getMetricNamespace() ); provider.putIndexedMapParameters( parameters, "Dimensions.member.", options.getMetricMetadata() ); if ( parameters.size() == 0 ) { return null; } return parameters; } /** * Creates map of parameters based on the AlarmFilterOptions. * * @param options options to convert to a parameter map * @return parameter map */ private Map<String, String> getAlarmFilterParameters( AlarmFilterOptions options ) { if ( options == null ) { return null; } Map<String, String> parameters = new HashMap<String, String>(); String stateValue = null; if ( options.getStateValue() != null ) { if ( options.getStateValue() == AlarmState.OK ) { stateValue = STATE_OK; } else if ( options.getStateValue() == AlarmState.OK ) { stateValue = STATE_ALARM; } else if ( options.getStateValue() == AlarmState.OK ) { stateValue = STATE_INSUFFICIENT_DATA; } } provider.putValueIfNotNull( parameters, "StateValue", stateValue ); provider.putIndexedParameters( parameters, "AlarmNames.member.", options.getAlarmNames() ); if ( parameters.size() == 0 ) { return null; } return parameters; } @Override public boolean isSubscribed() throws CloudException, InternalException { return true; } /** * Returns the cloudwatch endpoint url. * * @return the cloudwatch endpoint url */ private String getCloudWatchUrl() { return ("https://monitoring." + provider.getContext().getRegionId() + ".amazonaws.com"); } @Override public @Nonnull String[] mapServiceAction( @Nonnull ServiceAction action ) { if ( action.equals( MonitoringSupport.ANY ) ) { return new String[] {EC2Method.CW_PREFIX + "*"}; } if ( action.equals( MonitoringSupport.LIST_METRICS ) ) { return new String[] {EC2Method.CW_PREFIX + EC2Method.LIST_METRICS}; } if ( action.equals( MonitoringSupport.DESCRIBE_ALARMS ) ) { return new String[] {EC2Method.CW_PREFIX + EC2Method.DESCRIBE_ALARMS}; } return new String[0]; } }
true
true
private Alarm toAlarm( Node node ) throws CloudException, InternalException { if ( node == null ) { return null; } Alarm alarm = new Alarm(); alarm.setFunction( false ); // CloudWatch doesn't use a DSL or function for it's alarms. It uses statistic, comparisonOperator, and threshold. NodeList attributes = node.getChildNodes(); for ( int i = 0; i < attributes.getLength(); i++ ) { Node attribute = attributes.item( i ); String name = attribute.getNodeName(); if ( name.equals( "AlarmName" ) ) { alarm.setName( provider.getTextValue( attribute ) ); } else if ( name.equals( "AlarmDescription" ) ) { alarm.setDescription( provider.getTextValue( attribute ) ); } else if ( name.equals( "Namespace" ) ) { alarm.setMetricNamespace( provider.getTextValue( attribute ) ); } else if ( name.equals( "MetricName" ) ) { alarm.setMetric( provider.getTextValue( attribute ) ); } else if ( name.equals( "Dimensions" ) ) { Map<String, String> dimensions = toMetadata( attribute.getChildNodes() ); if ( dimensions != null ) { alarm.addMetricMetadata( dimensions ); } } else if ( name.equals( "ActionsEnabled" ) ) { alarm.setEnabled( "true".equals( provider.getTextValue( attribute ) ) ); } else if ( name.equals( "AlarmArn" ) ) { alarm.setProviderAlarmId( provider.getTextValue( attribute ) ); } else if ( name.equals( "AlarmActions" ) ) { alarm.setProviderAlarmActionIds( getMembersValues( attribute ) ); } else if ( name.equals( "InsufficientDataActions" ) ) { alarm.setProviderInsufficentDataActionIds( getMembersValues( attribute ) ); } else if ( name.equals( "OKActions" ) ) { alarm.setProviderOKActionIds( getMembersValues( attribute ) ); } else if ( name.equals( "Statistic" ) ) { alarm.setStatistic( provider.getTextValue( attribute ) ); } else if ( name.equals( "Period" ) ) { alarm.setPeriod( provider.getIntValue( attribute ) ); } else if ( name.equals( "EvaluationPeriods" ) ) { alarm.setEvaluationPeriods( provider.getIntValue( attribute ) ); } else if ( name.equals( "ComparisonOperator" ) ) { alarm.setComparisonOperator( provider.getTextValue( attribute ) ); } else if ( name.equals( "Threshold" ) ) { alarm.setThreshold( provider.getDoubleValue( attribute ) ); } else if ( name.equals( "StateReason" ) ) { alarm.setStateReason( provider.getTextValue( attribute ) ); } else if ( name.equals( "StateReasonData" ) ) { alarm.setStateReasonData( provider.getTextValue( attribute ) ); } else if ( name.equals( "StateUpdatedTimestamp" ) ) { alarm.setStateUpdatedTimestamp( provider.getTimestampValue( attribute ) ); } else if ( name.equals( "StateValue" ) ) { String stateValue = provider.getTextValue( attribute ); if ( STATE_OK.equals( stateValue ) ) { alarm.setStateValue( AlarmState.OK ); } else if ( STATE_ALARM.equals( stateValue ) ) { alarm.setStateValue( AlarmState.ALARM ); } else if ( STATE_INSUFFICIENT_DATA.equals( stateValue ) ) { alarm.setStateValue( AlarmState.INSUFFICIENT_DATA ); } } } return alarm; }
private Alarm toAlarm( Node node ) throws CloudException, InternalException { if ( node == null ) { return null; } Alarm alarm = new Alarm(); alarm.setFunction( false ); // CloudWatch doesn't use a DSL or function for it's alarms. It uses statistic, comparisonOperator, and threshold. NodeList attributes = node.getChildNodes(); for ( int i = 0; i < attributes.getLength(); i++ ) { Node attribute = attributes.item( i ); String name = attribute.getNodeName(); if ( name.equals( "AlarmName" ) ) { alarm.setName( provider.getTextValue( attribute ) ); } else if ( name.equals( "AlarmDescription" ) ) { alarm.setDescription( provider.getTextValue( attribute ) ); } else if ( name.equals( "Namespace" ) ) { alarm.setMetricNamespace( provider.getTextValue( attribute ) ); } else if ( name.equals( "MetricName" ) ) { alarm.setMetric( provider.getTextValue( attribute ) ); } else if ( name.equals( "Dimensions" ) ) { Map<String, String> dimensions = toMetadata( attribute.getChildNodes() ); if ( dimensions != null ) { alarm.addMetricMetadata( dimensions ); } } else if ( name.equals( "ActionsEnabled" ) ) { alarm.setEnabled( "true".equals( provider.getTextValue( attribute ) ) ); } else if ( name.equals( "AlarmArn" ) ) { alarm.setProviderAlarmId( provider.getTextValue( attribute ) ); } else if ( name.equals( "AlarmActions" ) ) { alarm.setProviderAlarmActionIds( getMembersValues( attribute ) ); } else if ( name.equals( "InsufficientDataActions" ) ) { alarm.setProviderInsufficientDataActionIds( getMembersValues( attribute ) ); } else if ( name.equals( "OKActions" ) ) { alarm.setProviderOKActionIds( getMembersValues( attribute ) ); } else if ( name.equals( "Statistic" ) ) { alarm.setStatistic( provider.getTextValue( attribute ) ); } else if ( name.equals( "Period" ) ) { alarm.setPeriod( provider.getIntValue( attribute ) ); } else if ( name.equals( "EvaluationPeriods" ) ) { alarm.setEvaluationPeriods( provider.getIntValue( attribute ) ); } else if ( name.equals( "ComparisonOperator" ) ) { alarm.setComparisonOperator( provider.getTextValue( attribute ) ); } else if ( name.equals( "Threshold" ) ) { alarm.setThreshold( provider.getDoubleValue( attribute ) ); } else if ( name.equals( "StateReason" ) ) { alarm.setStateReason( provider.getTextValue( attribute ) ); } else if ( name.equals( "StateReasonData" ) ) { alarm.setStateReasonData( provider.getTextValue( attribute ) ); } else if ( name.equals( "StateUpdatedTimestamp" ) ) { alarm.setStateUpdatedTimestamp( provider.getTimestampValue( attribute ) ); } else if ( name.equals( "StateValue" ) ) { String stateValue = provider.getTextValue( attribute ); if ( STATE_OK.equals( stateValue ) ) { alarm.setStateValue( AlarmState.OK ); } else if ( STATE_ALARM.equals( stateValue ) ) { alarm.setStateValue( AlarmState.ALARM ); } else if ( STATE_INSUFFICIENT_DATA.equals( stateValue ) ) { alarm.setStateValue( AlarmState.INSUFFICIENT_DATA ); } } } return alarm; }
diff --git a/src/minecraft/co/uk/flansmods/client/model/ModelVehicle.java b/src/minecraft/co/uk/flansmods/client/model/ModelVehicle.java index 9ebd419e..f5a79029 100644 --- a/src/minecraft/co/uk/flansmods/client/model/ModelVehicle.java +++ b/src/minecraft/co/uk/flansmods/client/model/ModelVehicle.java @@ -1,310 +1,310 @@ package co.uk.flansmods.client.model; import net.minecraft.client.model.ModelBase; import co.uk.flansmods.client.tmt.ModelRendererTurbo; import co.uk.flansmods.common.driveables.EntityDriveable; import co.uk.flansmods.common.driveables.EntityPlane; import co.uk.flansmods.common.driveables.EntitySeat; import co.uk.flansmods.common.driveables.EntityVehicle; import co.uk.flansmods.common.driveables.EnumDriveablePart; //Extensible ModelVehicle class for rendering vehicle models public class ModelVehicle extends ModelDriveable { @Override public void render(EntityDriveable driveable, float f1) { render(0.0625F, (EntityVehicle)driveable, f1); } @Override /** GUI render method */ public void render() { super.render(); renderPart(leftBackWheelModel); renderPart(rightBackWheelModel); renderPart(leftFrontWheelModel); renderPart(rightFrontWheelModel); renderPart(bodyDoorCloseModel); renderPart(trailerModel); renderPart(turretModel); renderPart(barrelModel); renderPart(steeringWheelModel); } public void render(float f5, EntityVehicle vehicle, float f) { boolean rotateWheels = vehicle.getVehicleType().rotateWheels; //Rendering the body if(vehicle.isPartIntact(EnumDriveablePart.core)) { for(int i = 0; i < bodyModel.length; i++) { bodyModel[i].render(f5); } for(int i = 0; i < bodyDoorOpenModel.length; i++) { if(vehicle.varDoor == true) bodyDoorOpenModel[i].render(f5); } for(int i = 0; i < bodyDoorCloseModel.length; i++) { if(vehicle.varDoor == false) bodyDoorCloseModel[i].render(f5); } for(int i = 0; i < steeringWheelModel.length; i++) { steeringWheelModel[i].rotateAngleX = vehicle.wheelsYaw * 3.14159265F / 180F * 3F; steeringWheelModel[i].render(f5); } } //Wheels if(vehicle.isPartIntact(EnumDriveablePart.backLeftWheel)) { for(int i = 0; i < leftBackWheelModel.length; i++) { leftBackWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; leftBackWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.backRightWheel)) { for(int i = 0; i < rightBackWheelModel.length; i++) { rightBackWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; rightBackWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.frontLeftWheel)) { for(int i = 0; i < leftFrontWheelModel.length; i++) { leftFrontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; leftFrontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; leftFrontWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.frontRightWheel)) { for(int i = 0; i < rightFrontWheelModel.length; i++) { rightFrontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; rightFrontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; rightFrontWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.frontWheel)) { for(int i = 0; i < frontWheelModel.length; i++) { frontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; frontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; frontWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.backWheel)) { for(int i = 0; i < backWheelModel.length; i++) { - backWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; + backWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; backWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.leftTrack)) { for(int i = 0; i < leftTrackModel.length; i++) { leftTrackModel[i].render(f5); } for(int i = 0; i < leftTrackWheelModels.length; i++) { - leftTrackModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; + leftTrackModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; leftTrackModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.rightTrack)) { for(int i = 0; i < rightTrackModel.length; i++) { rightTrackModel[i].render(f5); } for(int i = 0; i < rightTrackWheelModels.length; i++) { - rightTrackWheelModels[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; + rightTrackWheelModels[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; rightTrackWheelModels[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.trailer)) { for(int i = 0; i < trailerModel.length; i++) { trailerModel[i].render(f5); } } //Render guns for(EntitySeat seat : vehicle.seats) { //If the seat has a gun model attached if(seat != null && seat.seatInfo != null && seat.seatInfo.gunName != null && gunModels.get(seat.seatInfo.gunName) != null && vehicle.isPartIntact(seat.seatInfo.part))// && !vehicle.rotateWithTurret(seat.seatInfo)) { float yaw = seat.prevLooking.getYaw() + (seat.looking.getYaw() - seat.prevLooking.getYaw()) * f; float pitch = seat.prevLooking.getPitch() + (seat.looking.getPitch() - seat.prevLooking.getPitch()) * f; //Iterate over the parts of that model ModelRendererTurbo[][] gunModel = gunModels.get(seat.seatInfo.gunName); //Yaw only parts for(ModelRendererTurbo gunModelPart : gunModel[0]) { //Yaw and render gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F; gunModelPart.render(f5); } //Yaw and pitch, no recoil parts for(ModelRendererTurbo gunModelPart : gunModel[1]) { //Yaw, pitch and render gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F; gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F; gunModelPart.render(f5); } //Yaw, pitch and recoil parts for(ModelRendererTurbo gunModelPart : gunModel[2]) { //Yaw, pitch, recoil and render gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F; gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F; gunModelPart.render(f5); } } } } /** Render the tank turret */ public void renderTurret(float f, float f1, float f2, float f3, float f4, float f5, EntityVehicle vehicle) { //Render main turret barrel { float yaw = vehicle.seats[0].looking.getYaw(); float pitch = vehicle.seats[0].looking.getPitch(); for(int i = 0; i < turretModel.length; i++) { turretModel[i].render(f5); } for(int i = 0; i < barrelModel.length; i++) { barrelModel[i].rotateAngleZ = -pitch * 3.14159265F / 180F; barrelModel[i].render(f5); } } //Render turret guns /*for(EntitySeat seat : vehicle.seats) { //If the seat has a gun model attached if(seat != null && seat.seatInfo != null && seat.seatInfo.gunName != null && gunModels.get(seat.seatInfo.gunName) != null && vehicle.isPartIntact(seat.seatInfo.part) && vehicle.rotateWithTurret(seat.seatInfo)) { float yaw = seat.prevLooking.getYaw() + (seat.looking.getYaw() - seat.prevLooking.getYaw()) * f; float pitch = seat.prevLooking.getPitch() + (seat.looking.getPitch() - seat.prevLooking.getPitch()) * f; //Iterate over the parts of that model ModelRendererTurbo[][] gunModel = gunModels.get(seat.seatInfo.gunName); //Yaw only parts for(ModelRendererTurbo gunModelPart : gunModel[0]) { //Yaw and render gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F; gunModelPart.render(f5); } //Yaw and pitch, no recoil parts for(ModelRendererTurbo gunModelPart : gunModel[1]) { //Yaw, pitch and render gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F; gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F; gunModelPart.render(f5); } //Yaw, pitch and recoil parts for(ModelRendererTurbo gunModelPart : gunModel[2]) { //Yaw, pitch, recoil and render gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F; gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F; gunModelPart.render(f5); } } }*/ } @Override public void flipAll() { super.flipAll(); flip(turretModel); flip(barrelModel); flip(leftFrontWheelModel); flip(rightFrontWheelModel); flip(leftBackWheelModel); flip(rightBackWheelModel); flip(bodyDoorOpenModel); flip(bodyDoorCloseModel); flip(rightTrackModel); flip(leftTrackModel); flip(rightTrackWheelModels); flip(leftTrackWheelModels); flip(trailerModel); flip(steeringWheelModel); } public void translateAll(int y) { translate(bodyModel, y); translate(turretModel, y); translate(barrelModel, y); translate(leftFrontWheelModel, y); translate(rightFrontWheelModel, y); translate(leftBackWheelModel, y); translate(rightBackWheelModel, y); translate(bodyDoorOpenModel, y); translate(bodyDoorCloseModel, y); translate(rightTrackModel, y); translate(leftTrackModel, y); translate(rightTrackWheelModels, y); translate(leftTrackWheelModels, y); translate(trailerModel, y); translate(steeringWheelModel, y); } protected void translate(ModelRendererTurbo[] model, int y) { for(ModelRendererTurbo mod : model) { mod.rotationPointY += y; } } public ModelRendererTurbo turretModel[] = new ModelRendererTurbo[0]; //The turret (for tanks) public ModelRendererTurbo barrelModel[] = new ModelRendererTurbo[0]; //The barrel of the main turret public ModelRendererTurbo frontWheelModel[] = new ModelRendererTurbo[0]; //Front and back wheels are for bicycles and motorbikes and whatnot public ModelRendererTurbo backWheelModel[] = new ModelRendererTurbo[0]; public ModelRendererTurbo leftFrontWheelModel[] = new ModelRendererTurbo[0]; //This set of 4 wheels are for 4 or more wheeled things public ModelRendererTurbo rightFrontWheelModel[] = new ModelRendererTurbo[0]; //The front wheels will turn as the player steers, and the back ones will not public ModelRendererTurbo leftBackWheelModel[] = new ModelRendererTurbo[0]; //They will all turn as the car drives if the option to do so is set on public ModelRendererTurbo rightBackWheelModel[] = new ModelRendererTurbo[0]; //In the vehicle type file public ModelRendererTurbo rightTrackModel[] = new ModelRendererTurbo[0]; public ModelRendererTurbo leftTrackModel[] = new ModelRendererTurbo[0]; public ModelRendererTurbo rightTrackWheelModels[] = new ModelRendererTurbo[0]; //These go with the tracks but rotate public ModelRendererTurbo leftTrackWheelModels[] = new ModelRendererTurbo[0]; public ModelRendererTurbo bodyDoorOpenModel[] = new ModelRendererTurbo[0]; public ModelRendererTurbo bodyDoorCloseModel[] = new ModelRendererTurbo[0]; public ModelRendererTurbo trailerModel[] = new ModelRendererTurbo[0]; public ModelRendererTurbo steeringWheelModel[] = new ModelRendererTurbo[0]; }
false
true
public void render(float f5, EntityVehicle vehicle, float f) { boolean rotateWheels = vehicle.getVehicleType().rotateWheels; //Rendering the body if(vehicle.isPartIntact(EnumDriveablePart.core)) { for(int i = 0; i < bodyModel.length; i++) { bodyModel[i].render(f5); } for(int i = 0; i < bodyDoorOpenModel.length; i++) { if(vehicle.varDoor == true) bodyDoorOpenModel[i].render(f5); } for(int i = 0; i < bodyDoorCloseModel.length; i++) { if(vehicle.varDoor == false) bodyDoorCloseModel[i].render(f5); } for(int i = 0; i < steeringWheelModel.length; i++) { steeringWheelModel[i].rotateAngleX = vehicle.wheelsYaw * 3.14159265F / 180F * 3F; steeringWheelModel[i].render(f5); } } //Wheels if(vehicle.isPartIntact(EnumDriveablePart.backLeftWheel)) { for(int i = 0; i < leftBackWheelModel.length; i++) { leftBackWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; leftBackWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.backRightWheel)) { for(int i = 0; i < rightBackWheelModel.length; i++) { rightBackWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; rightBackWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.frontLeftWheel)) { for(int i = 0; i < leftFrontWheelModel.length; i++) { leftFrontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; leftFrontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; leftFrontWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.frontRightWheel)) { for(int i = 0; i < rightFrontWheelModel.length; i++) { rightFrontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; rightFrontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; rightFrontWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.frontWheel)) { for(int i = 0; i < frontWheelModel.length; i++) { frontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; frontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; frontWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.backWheel)) { for(int i = 0; i < backWheelModel.length; i++) { backWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; backWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.leftTrack)) { for(int i = 0; i < leftTrackModel.length; i++) { leftTrackModel[i].render(f5); } for(int i = 0; i < leftTrackWheelModels.length; i++) { leftTrackModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; leftTrackModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.rightTrack)) { for(int i = 0; i < rightTrackModel.length; i++) { rightTrackModel[i].render(f5); } for(int i = 0; i < rightTrackWheelModels.length; i++) { rightTrackWheelModels[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; rightTrackWheelModels[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.trailer)) { for(int i = 0; i < trailerModel.length; i++) { trailerModel[i].render(f5); } } //Render guns for(EntitySeat seat : vehicle.seats) { //If the seat has a gun model attached if(seat != null && seat.seatInfo != null && seat.seatInfo.gunName != null && gunModels.get(seat.seatInfo.gunName) != null && vehicle.isPartIntact(seat.seatInfo.part))// && !vehicle.rotateWithTurret(seat.seatInfo)) { float yaw = seat.prevLooking.getYaw() + (seat.looking.getYaw() - seat.prevLooking.getYaw()) * f; float pitch = seat.prevLooking.getPitch() + (seat.looking.getPitch() - seat.prevLooking.getPitch()) * f; //Iterate over the parts of that model ModelRendererTurbo[][] gunModel = gunModels.get(seat.seatInfo.gunName); //Yaw only parts for(ModelRendererTurbo gunModelPart : gunModel[0]) { //Yaw and render gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F; gunModelPart.render(f5); } //Yaw and pitch, no recoil parts for(ModelRendererTurbo gunModelPart : gunModel[1]) { //Yaw, pitch and render gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F; gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F; gunModelPart.render(f5); } //Yaw, pitch and recoil parts for(ModelRendererTurbo gunModelPart : gunModel[2]) { //Yaw, pitch, recoil and render gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F; gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F; gunModelPart.render(f5); } } } }
public void render(float f5, EntityVehicle vehicle, float f) { boolean rotateWheels = vehicle.getVehicleType().rotateWheels; //Rendering the body if(vehicle.isPartIntact(EnumDriveablePart.core)) { for(int i = 0; i < bodyModel.length; i++) { bodyModel[i].render(f5); } for(int i = 0; i < bodyDoorOpenModel.length; i++) { if(vehicle.varDoor == true) bodyDoorOpenModel[i].render(f5); } for(int i = 0; i < bodyDoorCloseModel.length; i++) { if(vehicle.varDoor == false) bodyDoorCloseModel[i].render(f5); } for(int i = 0; i < steeringWheelModel.length; i++) { steeringWheelModel[i].rotateAngleX = vehicle.wheelsYaw * 3.14159265F / 180F * 3F; steeringWheelModel[i].render(f5); } } //Wheels if(vehicle.isPartIntact(EnumDriveablePart.backLeftWheel)) { for(int i = 0; i < leftBackWheelModel.length; i++) { leftBackWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; leftBackWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.backRightWheel)) { for(int i = 0; i < rightBackWheelModel.length; i++) { rightBackWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; rightBackWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.frontLeftWheel)) { for(int i = 0; i < leftFrontWheelModel.length; i++) { leftFrontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; leftFrontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; leftFrontWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.frontRightWheel)) { for(int i = 0; i < rightFrontWheelModel.length; i++) { rightFrontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; rightFrontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; rightFrontWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.frontWheel)) { for(int i = 0; i < frontWheelModel.length; i++) { frontWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; frontWheelModel[i].rotateAngleY = -vehicle.wheelsYaw * 3.14159265F / 180F * 3F; frontWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.backWheel)) { for(int i = 0; i < backWheelModel.length; i++) { backWheelModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; backWheelModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.leftTrack)) { for(int i = 0; i < leftTrackModel.length; i++) { leftTrackModel[i].render(f5); } for(int i = 0; i < leftTrackWheelModels.length; i++) { leftTrackModel[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; leftTrackModel[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.rightTrack)) { for(int i = 0; i < rightTrackModel.length; i++) { rightTrackModel[i].render(f5); } for(int i = 0; i < rightTrackWheelModels.length; i++) { rightTrackWheelModels[i].rotateAngleZ = rotateWheels ? -vehicle.wheelsAngle : 0; rightTrackWheelModels[i].render(f5); } } if(vehicle.isPartIntact(EnumDriveablePart.trailer)) { for(int i = 0; i < trailerModel.length; i++) { trailerModel[i].render(f5); } } //Render guns for(EntitySeat seat : vehicle.seats) { //If the seat has a gun model attached if(seat != null && seat.seatInfo != null && seat.seatInfo.gunName != null && gunModels.get(seat.seatInfo.gunName) != null && vehicle.isPartIntact(seat.seatInfo.part))// && !vehicle.rotateWithTurret(seat.seatInfo)) { float yaw = seat.prevLooking.getYaw() + (seat.looking.getYaw() - seat.prevLooking.getYaw()) * f; float pitch = seat.prevLooking.getPitch() + (seat.looking.getPitch() - seat.prevLooking.getPitch()) * f; //Iterate over the parts of that model ModelRendererTurbo[][] gunModel = gunModels.get(seat.seatInfo.gunName); //Yaw only parts for(ModelRendererTurbo gunModelPart : gunModel[0]) { //Yaw and render gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F; gunModelPart.render(f5); } //Yaw and pitch, no recoil parts for(ModelRendererTurbo gunModelPart : gunModel[1]) { //Yaw, pitch and render gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F; gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F; gunModelPart.render(f5); } //Yaw, pitch and recoil parts for(ModelRendererTurbo gunModelPart : gunModel[2]) { //Yaw, pitch, recoil and render gunModelPart.rotateAngleY = -yaw * 3.14159265F / 180F; gunModelPart.rotateAngleZ = -pitch * 3.14159265F / 180F; gunModelPart.render(f5); } } } }
diff --git a/cruisecontrol/main/src/net/sourceforge/cruisecontrol/sourcecontrols/MKS.java b/cruisecontrol/main/src/net/sourceforge/cruisecontrol/sourcecontrols/MKS.java index 4bb8ecc7..e3f60142 100644 --- a/cruisecontrol/main/src/net/sourceforge/cruisecontrol/sourcecontrols/MKS.java +++ b/cruisecontrol/main/src/net/sourceforge/cruisecontrol/sourcecontrols/MKS.java @@ -1,288 +1,288 @@ /******************************************************************************** * CruiseControl, a Continuous Integration Toolkit * Copyright (c) 2001-2003, ThoughtWorks, Inc. * 651 W Washington Ave. Suite 600 * Chicago, IL 60661 USA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * + Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * + Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * + Neither the name of ThoughtWorks, Inc., CruiseControl, nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ********************************************************************************/ package net.sourceforge.cruisecontrol.sourcecontrols; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import net.sourceforge.cruisecontrol.CruiseControlException; import net.sourceforge.cruisecontrol.Modification; import net.sourceforge.cruisecontrol.SourceControl; import net.sourceforge.cruisecontrol.util.Commandline; import net.sourceforge.cruisecontrol.util.IO; import net.sourceforge.cruisecontrol.util.StreamLogger; import net.sourceforge.cruisecontrol.util.ValidationHelper; import org.apache.log4j.Logger; /** * This class implements the SourceControlElement methods for a MKS repository. * The call to MKS is assumed to work with any setup: * The call to MKS login should be done prior to calling this class. * * * attributes: * localWorkingDir - local directory for the sandbox * project - the name and path to the MKS project * doNothing - if this attribute is set to true, no mks command is executed. This is for * testing purposes, if a potentially slow mks server connection should avoid * * @author Suresh K Bathala Skila, Inc. * @author Dominik Hirt, Wincor-Nixdorf International GmbH, Leipzig */ public class MKS implements SourceControl { private static final Logger LOG = Logger.getLogger(MKS.class); private SourceControlProperties properties = new SourceControlProperties(); private String project; private File localWorkingDir; /** * if this attribute is set to true, no mks command is executed. This is for * testing purposes, if a potentially slow mks server connection should * avoid */ private boolean doNothing; /** * This is the workaround for the missing feature of MKS to return differences * for a given time period. If a modification is detected during the quietperiod, * CruiseControl calls <code>getModifications</code> of this sourcecontrol object * again, with the new values for <code>Date now</code>. In that case, and if all * modification are already found in the first cycle, the list of modifications * becomes empty. Therefor, we have to return the summarized list of modifications: * the values from the last run, and -maybe- results return by MKS for this run. */ private List listOfModifications = new ArrayList(); public void setProject(String project) { this.project = project; } /** * Sets the local working copy to use when making calls to MKS. * * @param local * String indicating the relative or absolute path to the local * working copy of the module of which to find the log history. */ public void setLocalWorkingDir(String local) { localWorkingDir = new File(local); } public void setProperty(String property) { properties.assignPropertyName(property); } public Map getProperties() { return properties.getPropertiesAndReset(); } public void setDoNothing(String doNothing) { this.doNothing = Boolean.valueOf(doNothing).booleanValue(); } public void validate() throws CruiseControlException { ValidationHelper.assertIsSet(localWorkingDir, "localWorkingDir", this.getClass()); ValidationHelper.assertIsSet(project, "project", this.getClass()); } /** * Returns an ArrayList of Modifications. * MKS ignores dates for such a range so therefor ALL * modifications since the last resynch step are returned. * * @param lastBuild * Last build time. * @param now * Time now, or time to check. * @return maybe empty, never null. */ public List getModifications(Date lastBuild, Date now) { int numberOfFilesForDot = 0; boolean printCR = false; if (doNothing) { properties.modificationFound(); return listOfModifications; } String cmd; String projectFilePath = localWorkingDir.getAbsolutePath() + File.separator + project; if (!new File(projectFilePath).exists()) { throw new RuntimeException("project file not found at " + projectFilePath); } - cmd = "si resync -f -R -S " + projectFilePath; + cmd = "si resync -f -R -S \"" + projectFilePath + "\""; /* Sample output: * output: Connecting to baswmks1:7001 ... Connecting to baswmks1:7001 * as dominik.hirt ... Resynchronizing files... * c:\temp\test\Admin\ComponentBuild\antfile.xml * c:\temp\test\Admin\PCEAdminCommand\projectbuild.properties: checked * out revision 1.1 */ try { LOG.debug(cmd); Process proc = Runtime.getRuntime() .exec(cmd, null, localWorkingDir); Thread stdout = logStream(proc.getInputStream()); InputStream in = proc.getErrorStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String line = reader.readLine(); while (line != null) { int idxCheckedOutRevision = line .indexOf(": checked out revision"); if (idxCheckedOutRevision == -1) { numberOfFilesForDot++; if (numberOfFilesForDot == 20) { System.out.print("."); // don't use LOG, avoid linefeed numberOfFilesForDot = 0; printCR = true; } line = reader.readLine(); continue; } if (printCR) { System.out.println(""); // avoid LOG prefix 'MKS - ' printCR = false; } LOG.info(line); int idxSeparator = line.lastIndexOf(File.separator); String folderName = line.substring(0, idxSeparator); String fileName = line.substring(idxSeparator + 1, idxCheckedOutRevision); Modification modification = new Modification(); Modification.ModifiedFile modFile = modification .createModifiedFile(fileName, folderName); modification.modifiedTime = new Date(new File(folderName, fileName).lastModified()); modFile.revision = line.substring(idxCheckedOutRevision + 23); modification.revision = modFile.revision; setUserNameAndComment(modification, folderName, fileName); listOfModifications.add(modification); line = reader.readLine(); properties.modificationFound(); } proc.waitFor(); stdout.join(); IO.close(proc); } catch (Exception ex) { LOG.warn(ex.getMessage(), ex); } System.out.println(); // finishing dotted line, avoid LOG prefix 'MKS - ' LOG.info("resync finished"); return listOfModifications; } /** * Sample output: * dominik.hirt;add forceDeploy peter.neumcke;path to properties file fixed, * copy generated properties Member added to project * d:/MKS/PCE_Usedom/Products/Info/Info.pj * * @param fileName */ private void setUserNameAndComment(Modification modification, String folderName, String fileName) { try { Commandline commandLine = new Commandline(); commandLine.setExecutable("si"); if (localWorkingDir != null) { commandLine.setWorkingDirectory(localWorkingDir.getAbsolutePath()); } commandLine.createArgument("rlog"); commandLine.createArgument("--format={author};{description}"); commandLine.createArgument("--noHeaderFormat"); commandLine.createArgument("--noTrailerFormat"); commandLine.createArguments("-r", modification.revision); commandLine.createArgument(folderName + File.separator + fileName); LOG.debug(commandLine.toString()); Process proc = commandLine.execute(); Thread stderr = logStream(proc.getErrorStream()); InputStream in = proc.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String line = reader.readLine(); LOG.debug(line); int idx = line.indexOf(";"); while (idx == -1) { line = reader.readLine(); // unknown output, read again LOG.debug(line); idx = line.indexOf(";"); } modification.userName = line.substring(0, idx); modification.comment = line.substring(idx + 1); proc.waitFor(); stderr.join(); IO.close(proc); } catch (Exception e) { LOG.warn(e.getMessage(), e); modification.userName = ""; modification.comment = ""; } } private static Thread logStream(InputStream inStream) { Thread stderr = new Thread(StreamLogger.getWarnPumper(LOG, inStream)); stderr.start(); return stderr; } }
true
true
public List getModifications(Date lastBuild, Date now) { int numberOfFilesForDot = 0; boolean printCR = false; if (doNothing) { properties.modificationFound(); return listOfModifications; } String cmd; String projectFilePath = localWorkingDir.getAbsolutePath() + File.separator + project; if (!new File(projectFilePath).exists()) { throw new RuntimeException("project file not found at " + projectFilePath); } cmd = "si resync -f -R -S " + projectFilePath; /* Sample output: * output: Connecting to baswmks1:7001 ... Connecting to baswmks1:7001 * as dominik.hirt ... Resynchronizing files... * c:\temp\test\Admin\ComponentBuild\antfile.xml * c:\temp\test\Admin\PCEAdminCommand\projectbuild.properties: checked * out revision 1.1 */ try { LOG.debug(cmd); Process proc = Runtime.getRuntime() .exec(cmd, null, localWorkingDir); Thread stdout = logStream(proc.getInputStream()); InputStream in = proc.getErrorStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String line = reader.readLine(); while (line != null) { int idxCheckedOutRevision = line .indexOf(": checked out revision"); if (idxCheckedOutRevision == -1) { numberOfFilesForDot++; if (numberOfFilesForDot == 20) { System.out.print("."); // don't use LOG, avoid linefeed numberOfFilesForDot = 0; printCR = true; } line = reader.readLine(); continue; } if (printCR) { System.out.println(""); // avoid LOG prefix 'MKS - ' printCR = false; } LOG.info(line); int idxSeparator = line.lastIndexOf(File.separator); String folderName = line.substring(0, idxSeparator); String fileName = line.substring(idxSeparator + 1, idxCheckedOutRevision); Modification modification = new Modification(); Modification.ModifiedFile modFile = modification .createModifiedFile(fileName, folderName); modification.modifiedTime = new Date(new File(folderName, fileName).lastModified()); modFile.revision = line.substring(idxCheckedOutRevision + 23); modification.revision = modFile.revision; setUserNameAndComment(modification, folderName, fileName); listOfModifications.add(modification); line = reader.readLine(); properties.modificationFound(); } proc.waitFor(); stdout.join(); IO.close(proc); } catch (Exception ex) { LOG.warn(ex.getMessage(), ex); } System.out.println(); // finishing dotted line, avoid LOG prefix 'MKS - ' LOG.info("resync finished"); return listOfModifications; }
public List getModifications(Date lastBuild, Date now) { int numberOfFilesForDot = 0; boolean printCR = false; if (doNothing) { properties.modificationFound(); return listOfModifications; } String cmd; String projectFilePath = localWorkingDir.getAbsolutePath() + File.separator + project; if (!new File(projectFilePath).exists()) { throw new RuntimeException("project file not found at " + projectFilePath); } cmd = "si resync -f -R -S \"" + projectFilePath + "\""; /* Sample output: * output: Connecting to baswmks1:7001 ... Connecting to baswmks1:7001 * as dominik.hirt ... Resynchronizing files... * c:\temp\test\Admin\ComponentBuild\antfile.xml * c:\temp\test\Admin\PCEAdminCommand\projectbuild.properties: checked * out revision 1.1 */ try { LOG.debug(cmd); Process proc = Runtime.getRuntime() .exec(cmd, null, localWorkingDir); Thread stdout = logStream(proc.getInputStream()); InputStream in = proc.getErrorStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String line = reader.readLine(); while (line != null) { int idxCheckedOutRevision = line .indexOf(": checked out revision"); if (idxCheckedOutRevision == -1) { numberOfFilesForDot++; if (numberOfFilesForDot == 20) { System.out.print("."); // don't use LOG, avoid linefeed numberOfFilesForDot = 0; printCR = true; } line = reader.readLine(); continue; } if (printCR) { System.out.println(""); // avoid LOG prefix 'MKS - ' printCR = false; } LOG.info(line); int idxSeparator = line.lastIndexOf(File.separator); String folderName = line.substring(0, idxSeparator); String fileName = line.substring(idxSeparator + 1, idxCheckedOutRevision); Modification modification = new Modification(); Modification.ModifiedFile modFile = modification .createModifiedFile(fileName, folderName); modification.modifiedTime = new Date(new File(folderName, fileName).lastModified()); modFile.revision = line.substring(idxCheckedOutRevision + 23); modification.revision = modFile.revision; setUserNameAndComment(modification, folderName, fileName); listOfModifications.add(modification); line = reader.readLine(); properties.modificationFound(); } proc.waitFor(); stdout.join(); IO.close(proc); } catch (Exception ex) { LOG.warn(ex.getMessage(), ex); } System.out.println(); // finishing dotted line, avoid LOG prefix 'MKS - ' LOG.info("resync finished"); return listOfModifications; }
diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/strategy/CloudStackComputeServiceAdapter.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/strategy/CloudStackComputeServiceAdapter.java index 5ad2fffddf..0da11fb582 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/strategy/CloudStackComputeServiceAdapter.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/strategy/CloudStackComputeServiceAdapter.java @@ -1,449 +1,449 @@ /* * 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.jclouds.cloudstack.compute.strategy; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Iterables.contains; import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.get; import static org.jclouds.cloudstack.options.DeployVirtualMachineOptions.Builder.displayName; import static org.jclouds.cloudstack.options.ListTemplatesOptions.Builder.id; import static org.jclouds.cloudstack.predicates.TemplatePredicates.isReady; import static org.jclouds.cloudstack.predicates.ZonePredicates.supportsSecurityGroups; import static org.jclouds.ssh.SshKeys.fingerprintPrivateKey; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.jclouds.cloudstack.CloudStackClient; import org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions; import org.jclouds.cloudstack.domain.AsyncCreateResponse; import org.jclouds.cloudstack.domain.Capabilities; import org.jclouds.cloudstack.domain.FirewallRule; import org.jclouds.cloudstack.domain.IPForwardingRule; import org.jclouds.cloudstack.domain.Network; import org.jclouds.cloudstack.domain.NetworkType; import org.jclouds.cloudstack.domain.PublicIPAddress; import org.jclouds.cloudstack.domain.SecurityGroup; import org.jclouds.cloudstack.domain.ServiceOffering; import org.jclouds.cloudstack.domain.SshKeyPair; import org.jclouds.cloudstack.domain.Template; import org.jclouds.cloudstack.domain.VirtualMachine; import org.jclouds.cloudstack.domain.Zone; import org.jclouds.cloudstack.domain.ZoneAndName; import org.jclouds.cloudstack.domain.ZoneSecurityGroupNamePortsCidrs; import org.jclouds.cloudstack.functions.CreateFirewallRulesForIP; import org.jclouds.cloudstack.functions.CreatePortForwardingRulesForIP; import org.jclouds.cloudstack.functions.StaticNATVirtualMachineInNetwork; import org.jclouds.cloudstack.functions.StaticNATVirtualMachineInNetwork.Factory; import org.jclouds.cloudstack.options.DeployVirtualMachineOptions; import org.jclouds.cloudstack.options.ListFirewallRulesOptions; import org.jclouds.cloudstack.strategy.BlockUntilJobCompletesAndReturnResult; import org.jclouds.collect.Memoized; import org.jclouds.compute.ComputeServiceAdapter; import org.jclouds.compute.functions.GroupNamingConvention; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Credentials; import org.jclouds.domain.LoginCredentials; import org.jclouds.logging.Logger; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.base.Throwables; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.google.common.collect.ImmutableSet.Builder; import com.google.common.primitives.Ints; /** * defines the connection between the {@link CloudStackClient} implementation * and the jclouds {@link ComputeService} */ @Singleton public class CloudStackComputeServiceAdapter implements ComputeServiceAdapter<VirtualMachine, ServiceOffering, Template, Zone> { @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; private final CloudStackClient client; private final Predicate<String> jobComplete; private final Supplier<Map<String, Network>> networkSupplier; private final BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult; private final Factory staticNATVMInNetwork; private final CreatePortForwardingRulesForIP setupPortForwardingRulesForIP; private final CreateFirewallRulesForIP setupFirewallRulesForIP; private final LoadingCache<String, Set<IPForwardingRule>> vmToRules; private final Map<String, Credentials> credentialStore; private final Map<NetworkType, ? extends OptionsConverter> optionsConverters; private final Supplier<LoadingCache<String, Zone>> zoneIdToZone; private final LoadingCache<ZoneAndName, SecurityGroup> securityGroupCache; private final LoadingCache<String, SshKeyPair> keyPairCache; private final GroupNamingConvention.Factory namingConvention; @Inject public CloudStackComputeServiceAdapter(CloudStackClient client, Predicate<String> jobComplete, @Memoized Supplier<Map<String, Network>> networkSupplier, BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult, StaticNATVirtualMachineInNetwork.Factory staticNATVMInNetwork, CreatePortForwardingRulesForIP setupPortForwardingRulesForIP, CreateFirewallRulesForIP setupFirewallRulesForIP, LoadingCache<String, Set<IPForwardingRule>> vmToRules, Map<String, Credentials> credentialStore, Map<NetworkType, ? extends OptionsConverter> optionsConverters, Supplier<LoadingCache<String, Zone>> zoneIdToZone, LoadingCache<ZoneAndName, SecurityGroup> securityGroupCache, LoadingCache<String, SshKeyPair> keyPairCache, GroupNamingConvention.Factory namingConvention) { this.client = checkNotNull(client, "client"); this.jobComplete = checkNotNull(jobComplete, "jobComplete"); this.networkSupplier = checkNotNull(networkSupplier, "networkSupplier"); this.blockUntilJobCompletesAndReturnResult = checkNotNull(blockUntilJobCompletesAndReturnResult, "blockUntilJobCompletesAndReturnResult"); this.staticNATVMInNetwork = checkNotNull(staticNATVMInNetwork, "staticNATVMInNetwork"); this.setupPortForwardingRulesForIP = checkNotNull(setupPortForwardingRulesForIP, "setupPortForwardingRulesForIP"); this.setupFirewallRulesForIP = checkNotNull(setupFirewallRulesForIP, "setupFirewallRulesForIP"); this.vmToRules = checkNotNull(vmToRules, "vmToRules"); this.credentialStore = checkNotNull(credentialStore, "credentialStore"); this.securityGroupCache = checkNotNull(securityGroupCache, "securityGroupCache"); this.keyPairCache = checkNotNull(keyPairCache, "keyPairCache"); this.optionsConverters = optionsConverters; this.zoneIdToZone = zoneIdToZone; this.namingConvention = namingConvention; } @Override public NodeAndInitialCredentials<VirtualMachine> createNodeWithGroupEncodedIntoName(String group, String name, org.jclouds.compute.domain.Template template) { checkNotNull(template, "template was null"); checkNotNull(template.getOptions(), "template options was null"); checkArgument(template.getOptions().getClass().isAssignableFrom(CloudStackTemplateOptions.class), "options class %s should have been assignable from CloudStackTemplateOptions", template.getOptions() .getClass()); Map<String, Network> networks = networkSupplier.get(); final String zoneId = template.getLocation().getId(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); CloudStackTemplateOptions templateOptions = template.getOptions().as(CloudStackTemplateOptions.class); checkState(optionsConverters.containsKey(zone.getNetworkType()), "no options converter configured for network type %s", zone.getNetworkType()); DeployVirtualMachineOptions options = displayName(name).name(name); if (templateOptions.getAccount() != null) { options.accountInDomain(templateOptions.getAccount(), templateOptions.getDomainId()); } else if (templateOptions.getDomainId() != null) { options.domainId(templateOptions.getDomainId()); } OptionsConverter optionsConverter = optionsConverters.get(zone.getNetworkType()); options = optionsConverter.apply(templateOptions, networks, zoneId, options); if (templateOptions.getIpOnDefaultNetwork() != null) { options.ipOnDefaultNetwork(templateOptions.getIpOnDefaultNetwork()); } if (templateOptions.getIpsToNetworks().size() > 0) { options.ipsToNetworks(templateOptions.getIpsToNetworks()); } if (templateOptions.getKeyPair() != null) { SshKeyPair keyPair = null; if (templateOptions.getLoginPrivateKey() != null) { String pem = templateOptions.getLoginPrivateKey(); keyPair = SshKeyPair.builder().name(templateOptions.getKeyPair()) .fingerprint(fingerprintPrivateKey(pem)).privateKey(pem).build(); keyPairCache.asMap().put(keyPair.getName(), keyPair); options.keyPair(keyPair.getName()); } else if (client.getSSHKeyPairClient().getSSHKeyPair(templateOptions.getKeyPair()) != null) { keyPair = client.getSSHKeyPairClient().getSSHKeyPair(templateOptions.getKeyPair()); } if (keyPair != null) { keyPairCache.asMap().put(keyPair.getName(), keyPair); options.keyPair(keyPair.getName()); } } else if (templateOptions.shouldGenerateKeyPair()) { SshKeyPair keyPair = keyPairCache.getUnchecked(namingConvention.create() .sharedNameForGroup(group)); keyPairCache.asMap().put(keyPair.getName(), keyPair); templateOptions.keyPair(keyPair.getName()); options.keyPair(keyPair.getName()); } if (supportsSecurityGroups().apply(zone)) { List<Integer> inboundPorts = Ints.asList(templateOptions.getInboundPorts()); if (templateOptions.getSecurityGroupIds().size() == 0 && inboundPorts.size() > 0 && templateOptions.shouldGenerateSecurityGroup()) { String securityGroupName = namingConvention.create().sharedNameForGroup(group); SecurityGroup sg = securityGroupCache.getUnchecked(ZoneSecurityGroupNamePortsCidrs.builder() .zone(zone.getId()) .name(securityGroupName) .ports(ImmutableSet.copyOf(inboundPorts)) .cidrs(ImmutableSet.<String> of()).build()); options.securityGroupId(sg.getId()); } } String templateId = template.getImage().getId(); String serviceOfferingId = template.getHardware().getId(); logger.debug("serviceOfferingId %s, templateId %s, zoneId %s, options %s%n", serviceOfferingId, templateId, zoneId, options); AsyncCreateResponse job = client.getVirtualMachineClient().deployVirtualMachineInZone(zoneId, serviceOfferingId, templateId, options); VirtualMachine vm = blockUntilJobCompletesAndReturnResult.<VirtualMachine>apply(job); logger.debug("--- virtualmachine: %s", vm); LoginCredentials.Builder credentialsBuilder = LoginCredentials.builder(); - if (!vm.isPasswordEnabled() || templateOptions.getKeyPair() != null) { + if (templateOptions.getKeyPair() != null) { SshKeyPair keyPair = keyPairCache.getUnchecked(templateOptions.getKeyPair()); credentialsBuilder.privateKey(keyPair.getPrivateKey()); - } else { + } else if (vm.isPasswordEnabled()) { assert vm.getPassword() != null : vm; credentialsBuilder.password(vm.getPassword()); } if (templateOptions.shouldSetupStaticNat()) { Capabilities capabilities = client.getConfigurationClient().listCapabilities(); // TODO: possibly not all network ids, do we want to do this for (String networkId : options.getNetworkIds()) { logger.debug(">> creating static NAT for virtualMachine(%s) in network(%s)", vm.getId(), networkId); PublicIPAddress ip = staticNATVMInNetwork.create(networks.get(networkId)).apply(vm); logger.trace("<< static NATed IPAddress(%s) to virtualMachine(%s)", ip.getId(), vm.getId()); vm = client.getVirtualMachineClient().getVirtualMachine(vm.getId()); List<Integer> ports = Ints.asList(templateOptions.getInboundPorts()); if (capabilities.getCloudStackVersion().startsWith("2")) { logger.debug(">> setting up IP forwarding for IPAddress(%s) rules(%s)", ip.getId(), ports); Set<IPForwardingRule> rules = setupPortForwardingRulesForIP.apply(ip, ports); logger.trace("<< setup %d IP forwarding rules on IPAddress(%s)", rules.size(), ip.getId()); } else { logger.debug(">> setting up firewall rules for IPAddress(%s) rules(%s)", ip.getId(), ports); Set<FirewallRule> rules = setupFirewallRulesForIP.apply(ip, ports); logger.trace("<< setup %d firewall rules on IPAddress(%s)", rules.size(), ip.getId()); } } } return new NodeAndInitialCredentials<VirtualMachine>(vm, vm.getId() + "", credentialsBuilder.build()); } @Override public Iterable<ServiceOffering> listHardwareProfiles() { // TODO: we may need to filter these return client.getOfferingClient().listServiceOfferings(); } @Override public Iterable<Template> listImages() { // TODO: we may need to filter these further // we may also want to see if we can work with ssh keys return filter(client.getTemplateClient().listTemplates(), isReady()); } @Override public Template getImage(String id) { return get(client.getTemplateClient().listTemplates(id(id)), 0, null); } @Override public Iterable<VirtualMachine> listNodes() { return client.getVirtualMachineClient().listVirtualMachines(); } @Override public Iterable<VirtualMachine> listNodesByIds(final Iterable<String> ids) { return filter(listNodes(), new Predicate<VirtualMachine>() { @Override public boolean apply(VirtualMachine vm) { return contains(ids, vm.getId()); } }); } @Override public Iterable<Zone> listLocations() { // TODO: we may need to filter these return client.getZoneClient().listZones(); } @Override public VirtualMachine getNode(String id) { String virtualMachineId = id; return client.getVirtualMachineClient().getVirtualMachine(virtualMachineId); } @Override public void destroyNode(String id) { String virtualMachineId = id; // There was a bug in 2.2.12 release happening when static nat IP address // was being released, and corresponding firewall rules were left behind. // So next time the same IP is allocated, it might be not be static nat // enabled, but there are still rules associated with it. And when you try // to release this IP, the release will fail. // // The bug was fixed in 2.2.13 release only, and the current system wasn't // updated yet. // // To avoid the issue, every time you release a static nat ip address, do // the following: // 1) Delete IP forwarding rules associated with IP. Set<String> ipAddresses = deleteIPForwardingRulesForVMAndReturnDistinctIPs(virtualMachineId); // 2) Delete firewall rules associated with IP. ipAddresses.addAll(deleteFirewallRulesForVMAndReturnDistinctIPs(virtualMachineId)); // 3) Disable static nat rule for the IP. disableStaticNATOnIPAddresses(ipAddresses); // 4) Only after 1 and 2 release the IP address. disassociateIPAddresses(ipAddresses); destroyVirtualMachine(virtualMachineId); vmToRules.invalidate(virtualMachineId); } public void disassociateIPAddresses(Set<String> ipAddresses) { for (String ipAddress : ipAddresses) { logger.debug(">> disassociating IPAddress(%s)", ipAddress); client.getAddressClient().disassociateIPAddress(ipAddress); } } public void destroyVirtualMachine(String virtualMachineId) { String destroyVirtualMachine = client.getVirtualMachineClient().destroyVirtualMachine(virtualMachineId); if (destroyVirtualMachine != null) { logger.debug(">> destroying virtualMachine(%s) job(%s)", virtualMachineId, destroyVirtualMachine); awaitCompletion(destroyVirtualMachine); } else { logger.trace("<< virtualMachine(%s) not found", virtualMachineId); } } public void disableStaticNATOnIPAddresses(Set<String> ipAddresses) { Builder<String> jobsToTrack = ImmutableSet.builder(); for (String ipAddress : ipAddresses) { String disableStaticNAT = client.getNATClient().disableStaticNATOnPublicIP(ipAddress); if (disableStaticNAT != null) { logger.debug(">> disabling static NAT IPAddress(%s) job(%s)", ipAddress, disableStaticNAT); jobsToTrack.add(disableStaticNAT); } } awaitCompletion(jobsToTrack.build()); } public Set<String> deleteIPForwardingRulesForVMAndReturnDistinctIPs(String virtualMachineId) { Builder<String> jobsToTrack = ImmutableSet.builder(); // immutable doesn't permit duplicates Set<String> ipAddresses = Sets.newLinkedHashSet(); Set<IPForwardingRule> forwardingRules = client.getNATClient().getIPForwardingRulesForVirtualMachine( virtualMachineId); for (IPForwardingRule rule : forwardingRules) { if (!"Deleting".equals(rule.getState())) { ipAddresses.add(rule.getIPAddressId()); String deleteForwardingRule = client.getNATClient().deleteIPForwardingRule(rule.getId()); if (deleteForwardingRule != null) { logger.debug(">> deleting IPForwardingRule(%s) job(%s)", rule.getId(), deleteForwardingRule); jobsToTrack.add(deleteForwardingRule); } } } awaitCompletion(jobsToTrack.build()); return ipAddresses; } public Set<String> deleteFirewallRulesForVMAndReturnDistinctIPs(String virtualMachineId) { // immutable doesn't permit duplicates Set<String> ipAddresses = Sets.newLinkedHashSet(); String publicIpId = client.getVirtualMachineClient().getVirtualMachine(virtualMachineId).getPublicIPId(); if (publicIpId != null) { Set<FirewallRule> firewallRules = client.getFirewallClient() .listFirewallRules(ListFirewallRulesOptions.Builder.ipAddressId(client.getVirtualMachineClient().getVirtualMachine(virtualMachineId).getPublicIPId())); for (FirewallRule rule : firewallRules) { if (rule.getState() != FirewallRule.State.DELETING) { ipAddresses.add(rule.getIpAddressId()); client.getFirewallClient().deleteFirewallRule(rule.getId()); logger.debug(">> deleting FirewallRule(%s)", rule.getId()); } } } return ipAddresses; } public void awaitCompletion(Iterable<String> jobs) { logger.debug(">> awaiting completion of jobs(%s)", jobs); for (String job : jobs) awaitCompletion(job); logger.trace("<< completed jobs(%s)", jobs); } public void awaitCompletion(String job) { boolean completed = jobComplete.apply(job); logger.trace("<< job(%s) complete(%s)", job, completed); } @Override public void rebootNode(String id) { String virtualMachineId = id; String job = client.getVirtualMachineClient().rebootVirtualMachine(virtualMachineId); if (job != null) { logger.debug(">> rebooting virtualMachine(%s) job(%s)", virtualMachineId, job); awaitCompletion(job); } } @Override public void resumeNode(String id) { String virtualMachineId = id; String job = client.getVirtualMachineClient().startVirtualMachine(id); if (job != null) { logger.debug(">> starting virtualMachine(%s) job(%s)", virtualMachineId, job); awaitCompletion(job); } } @Override public void suspendNode(String id) { String virtualMachineId = id; String job = client.getVirtualMachineClient().stopVirtualMachine(id); if (job != null) { logger.debug(">> stopping virtualMachine(%s) job(%s)", virtualMachineId, job); awaitCompletion(job); } } }
false
true
public NodeAndInitialCredentials<VirtualMachine> createNodeWithGroupEncodedIntoName(String group, String name, org.jclouds.compute.domain.Template template) { checkNotNull(template, "template was null"); checkNotNull(template.getOptions(), "template options was null"); checkArgument(template.getOptions().getClass().isAssignableFrom(CloudStackTemplateOptions.class), "options class %s should have been assignable from CloudStackTemplateOptions", template.getOptions() .getClass()); Map<String, Network> networks = networkSupplier.get(); final String zoneId = template.getLocation().getId(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); CloudStackTemplateOptions templateOptions = template.getOptions().as(CloudStackTemplateOptions.class); checkState(optionsConverters.containsKey(zone.getNetworkType()), "no options converter configured for network type %s", zone.getNetworkType()); DeployVirtualMachineOptions options = displayName(name).name(name); if (templateOptions.getAccount() != null) { options.accountInDomain(templateOptions.getAccount(), templateOptions.getDomainId()); } else if (templateOptions.getDomainId() != null) { options.domainId(templateOptions.getDomainId()); } OptionsConverter optionsConverter = optionsConverters.get(zone.getNetworkType()); options = optionsConverter.apply(templateOptions, networks, zoneId, options); if (templateOptions.getIpOnDefaultNetwork() != null) { options.ipOnDefaultNetwork(templateOptions.getIpOnDefaultNetwork()); } if (templateOptions.getIpsToNetworks().size() > 0) { options.ipsToNetworks(templateOptions.getIpsToNetworks()); } if (templateOptions.getKeyPair() != null) { SshKeyPair keyPair = null; if (templateOptions.getLoginPrivateKey() != null) { String pem = templateOptions.getLoginPrivateKey(); keyPair = SshKeyPair.builder().name(templateOptions.getKeyPair()) .fingerprint(fingerprintPrivateKey(pem)).privateKey(pem).build(); keyPairCache.asMap().put(keyPair.getName(), keyPair); options.keyPair(keyPair.getName()); } else if (client.getSSHKeyPairClient().getSSHKeyPair(templateOptions.getKeyPair()) != null) { keyPair = client.getSSHKeyPairClient().getSSHKeyPair(templateOptions.getKeyPair()); } if (keyPair != null) { keyPairCache.asMap().put(keyPair.getName(), keyPair); options.keyPair(keyPair.getName()); } } else if (templateOptions.shouldGenerateKeyPair()) { SshKeyPair keyPair = keyPairCache.getUnchecked(namingConvention.create() .sharedNameForGroup(group)); keyPairCache.asMap().put(keyPair.getName(), keyPair); templateOptions.keyPair(keyPair.getName()); options.keyPair(keyPair.getName()); } if (supportsSecurityGroups().apply(zone)) { List<Integer> inboundPorts = Ints.asList(templateOptions.getInboundPorts()); if (templateOptions.getSecurityGroupIds().size() == 0 && inboundPorts.size() > 0 && templateOptions.shouldGenerateSecurityGroup()) { String securityGroupName = namingConvention.create().sharedNameForGroup(group); SecurityGroup sg = securityGroupCache.getUnchecked(ZoneSecurityGroupNamePortsCidrs.builder() .zone(zone.getId()) .name(securityGroupName) .ports(ImmutableSet.copyOf(inboundPorts)) .cidrs(ImmutableSet.<String> of()).build()); options.securityGroupId(sg.getId()); } } String templateId = template.getImage().getId(); String serviceOfferingId = template.getHardware().getId(); logger.debug("serviceOfferingId %s, templateId %s, zoneId %s, options %s%n", serviceOfferingId, templateId, zoneId, options); AsyncCreateResponse job = client.getVirtualMachineClient().deployVirtualMachineInZone(zoneId, serviceOfferingId, templateId, options); VirtualMachine vm = blockUntilJobCompletesAndReturnResult.<VirtualMachine>apply(job); logger.debug("--- virtualmachine: %s", vm); LoginCredentials.Builder credentialsBuilder = LoginCredentials.builder(); if (!vm.isPasswordEnabled() || templateOptions.getKeyPair() != null) { SshKeyPair keyPair = keyPairCache.getUnchecked(templateOptions.getKeyPair()); credentialsBuilder.privateKey(keyPair.getPrivateKey()); } else { assert vm.getPassword() != null : vm; credentialsBuilder.password(vm.getPassword()); } if (templateOptions.shouldSetupStaticNat()) { Capabilities capabilities = client.getConfigurationClient().listCapabilities(); // TODO: possibly not all network ids, do we want to do this for (String networkId : options.getNetworkIds()) { logger.debug(">> creating static NAT for virtualMachine(%s) in network(%s)", vm.getId(), networkId); PublicIPAddress ip = staticNATVMInNetwork.create(networks.get(networkId)).apply(vm); logger.trace("<< static NATed IPAddress(%s) to virtualMachine(%s)", ip.getId(), vm.getId()); vm = client.getVirtualMachineClient().getVirtualMachine(vm.getId()); List<Integer> ports = Ints.asList(templateOptions.getInboundPorts()); if (capabilities.getCloudStackVersion().startsWith("2")) { logger.debug(">> setting up IP forwarding for IPAddress(%s) rules(%s)", ip.getId(), ports); Set<IPForwardingRule> rules = setupPortForwardingRulesForIP.apply(ip, ports); logger.trace("<< setup %d IP forwarding rules on IPAddress(%s)", rules.size(), ip.getId()); } else { logger.debug(">> setting up firewall rules for IPAddress(%s) rules(%s)", ip.getId(), ports); Set<FirewallRule> rules = setupFirewallRulesForIP.apply(ip, ports); logger.trace("<< setup %d firewall rules on IPAddress(%s)", rules.size(), ip.getId()); } } } return new NodeAndInitialCredentials<VirtualMachine>(vm, vm.getId() + "", credentialsBuilder.build()); }
public NodeAndInitialCredentials<VirtualMachine> createNodeWithGroupEncodedIntoName(String group, String name, org.jclouds.compute.domain.Template template) { checkNotNull(template, "template was null"); checkNotNull(template.getOptions(), "template options was null"); checkArgument(template.getOptions().getClass().isAssignableFrom(CloudStackTemplateOptions.class), "options class %s should have been assignable from CloudStackTemplateOptions", template.getOptions() .getClass()); Map<String, Network> networks = networkSupplier.get(); final String zoneId = template.getLocation().getId(); Zone zone = zoneIdToZone.get().getUnchecked(zoneId); CloudStackTemplateOptions templateOptions = template.getOptions().as(CloudStackTemplateOptions.class); checkState(optionsConverters.containsKey(zone.getNetworkType()), "no options converter configured for network type %s", zone.getNetworkType()); DeployVirtualMachineOptions options = displayName(name).name(name); if (templateOptions.getAccount() != null) { options.accountInDomain(templateOptions.getAccount(), templateOptions.getDomainId()); } else if (templateOptions.getDomainId() != null) { options.domainId(templateOptions.getDomainId()); } OptionsConverter optionsConverter = optionsConverters.get(zone.getNetworkType()); options = optionsConverter.apply(templateOptions, networks, zoneId, options); if (templateOptions.getIpOnDefaultNetwork() != null) { options.ipOnDefaultNetwork(templateOptions.getIpOnDefaultNetwork()); } if (templateOptions.getIpsToNetworks().size() > 0) { options.ipsToNetworks(templateOptions.getIpsToNetworks()); } if (templateOptions.getKeyPair() != null) { SshKeyPair keyPair = null; if (templateOptions.getLoginPrivateKey() != null) { String pem = templateOptions.getLoginPrivateKey(); keyPair = SshKeyPair.builder().name(templateOptions.getKeyPair()) .fingerprint(fingerprintPrivateKey(pem)).privateKey(pem).build(); keyPairCache.asMap().put(keyPair.getName(), keyPair); options.keyPair(keyPair.getName()); } else if (client.getSSHKeyPairClient().getSSHKeyPair(templateOptions.getKeyPair()) != null) { keyPair = client.getSSHKeyPairClient().getSSHKeyPair(templateOptions.getKeyPair()); } if (keyPair != null) { keyPairCache.asMap().put(keyPair.getName(), keyPair); options.keyPair(keyPair.getName()); } } else if (templateOptions.shouldGenerateKeyPair()) { SshKeyPair keyPair = keyPairCache.getUnchecked(namingConvention.create() .sharedNameForGroup(group)); keyPairCache.asMap().put(keyPair.getName(), keyPair); templateOptions.keyPair(keyPair.getName()); options.keyPair(keyPair.getName()); } if (supportsSecurityGroups().apply(zone)) { List<Integer> inboundPorts = Ints.asList(templateOptions.getInboundPorts()); if (templateOptions.getSecurityGroupIds().size() == 0 && inboundPorts.size() > 0 && templateOptions.shouldGenerateSecurityGroup()) { String securityGroupName = namingConvention.create().sharedNameForGroup(group); SecurityGroup sg = securityGroupCache.getUnchecked(ZoneSecurityGroupNamePortsCidrs.builder() .zone(zone.getId()) .name(securityGroupName) .ports(ImmutableSet.copyOf(inboundPorts)) .cidrs(ImmutableSet.<String> of()).build()); options.securityGroupId(sg.getId()); } } String templateId = template.getImage().getId(); String serviceOfferingId = template.getHardware().getId(); logger.debug("serviceOfferingId %s, templateId %s, zoneId %s, options %s%n", serviceOfferingId, templateId, zoneId, options); AsyncCreateResponse job = client.getVirtualMachineClient().deployVirtualMachineInZone(zoneId, serviceOfferingId, templateId, options); VirtualMachine vm = blockUntilJobCompletesAndReturnResult.<VirtualMachine>apply(job); logger.debug("--- virtualmachine: %s", vm); LoginCredentials.Builder credentialsBuilder = LoginCredentials.builder(); if (templateOptions.getKeyPair() != null) { SshKeyPair keyPair = keyPairCache.getUnchecked(templateOptions.getKeyPair()); credentialsBuilder.privateKey(keyPair.getPrivateKey()); } else if (vm.isPasswordEnabled()) { assert vm.getPassword() != null : vm; credentialsBuilder.password(vm.getPassword()); } if (templateOptions.shouldSetupStaticNat()) { Capabilities capabilities = client.getConfigurationClient().listCapabilities(); // TODO: possibly not all network ids, do we want to do this for (String networkId : options.getNetworkIds()) { logger.debug(">> creating static NAT for virtualMachine(%s) in network(%s)", vm.getId(), networkId); PublicIPAddress ip = staticNATVMInNetwork.create(networks.get(networkId)).apply(vm); logger.trace("<< static NATed IPAddress(%s) to virtualMachine(%s)", ip.getId(), vm.getId()); vm = client.getVirtualMachineClient().getVirtualMachine(vm.getId()); List<Integer> ports = Ints.asList(templateOptions.getInboundPorts()); if (capabilities.getCloudStackVersion().startsWith("2")) { logger.debug(">> setting up IP forwarding for IPAddress(%s) rules(%s)", ip.getId(), ports); Set<IPForwardingRule> rules = setupPortForwardingRulesForIP.apply(ip, ports); logger.trace("<< setup %d IP forwarding rules on IPAddress(%s)", rules.size(), ip.getId()); } else { logger.debug(">> setting up firewall rules for IPAddress(%s) rules(%s)", ip.getId(), ports); Set<FirewallRule> rules = setupFirewallRulesForIP.apply(ip, ports); logger.trace("<< setup %d firewall rules on IPAddress(%s)", rules.size(), ip.getId()); } } } return new NodeAndInitialCredentials<VirtualMachine>(vm, vm.getId() + "", credentialsBuilder.build()); }
diff --git a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/background/JavaScriptJobManagerTest.java b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/background/JavaScriptJobManagerTest.java index a641cb3db..6d6edd74e 100644 --- a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/background/JavaScriptJobManagerTest.java +++ b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/background/JavaScriptJobManagerTest.java @@ -1,254 +1,254 @@ /* * Copyright (c) 2002-2010 Gargoyle Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gargoylesoftware.htmlunit.javascript.background; import static org.junit.Assert.assertNotNull; import java.io.PrintStream; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.Assert; import org.junit.Test; import com.gargoylesoftware.htmlunit.MockWebConnection; import com.gargoylesoftware.htmlunit.TopLevelWindow; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.WebTestCase; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlInlineFrame; import com.gargoylesoftware.htmlunit.html.HtmlPage; /** * Tests for {@link JavaScriptJobManagerImpl} using the full HtmlUnit stack. Minimal unit tests * which do not use the full HtmlUnit stack go in {@link JavaScriptJobManagerMinimalTest}. * * @version $Revision$ * @author Brad Clarke * @author Ahmed Ashour */ public class JavaScriptJobManagerTest extends WebTestCase { private long startTime_; private void startTimedTest() { startTime_ = System.currentTimeMillis(); } private void assertMaxTestRunTime(final long maxRunTimeMilliseconds) { final long endTime = System.currentTimeMillis(); final long runTime = endTime - startTime_; assertTrue("\nTest took too long to run and results may not be accurate. Please try again. " + "\n Actual Run Time: " + runTime + "\n Max Run Time: " + maxRunTimeMilliseconds, runTime < maxRunTimeMilliseconds); } /** * @throws Exception if the test fails */ @Test public void setClearTimeoutUsesManager() throws Exception { final String content = "<html>\n" + "<head>\n" + " <title>test</title>\n" + " <script>\n" + " var threadID;\n" + " function test() {\n" + " threadID = setTimeout(doAlert, 10000);\n" + " }\n" + " function doAlert() {\n" + " alert('blah');\n" + " }\n" + " </script>\n" + "</head>\n" + "<body onload='test()'>\n" + "<a onclick='clearTimeout(threadID);' id='clickme'/>\n" + "</body>\n" + "</html>"; final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>()); startTimedTest(); final HtmlPage page = loadPage(content, collectedAlerts); final JavaScriptJobManager jobManager = page.getEnclosingWindow().getJobManager(); assertNotNull(jobManager); assertEquals(1, jobManager.getJobCount()); final HtmlAnchor a = page.getHtmlElementById("clickme"); a.click(); jobManager.waitForJobs(7000); assertEquals(0, jobManager.getJobCount()); assertEquals(Collections.EMPTY_LIST, collectedAlerts); assertMaxTestRunTime(10000); } /** * @throws Exception if the test fails */ @Test public void setClearIntervalUsesManager() throws Exception { final String content = "<html>\n" + "<head>\n" + " <title>test</title>\n" + " <script>\n" + " var threadID;\n" + " function test() {\n" + " threadID = setInterval(doAlert, 100);\n" + " }\n" + " var iterationNumber=0;\n" + " function doAlert() {\n" + " alert('blah');\n" + " if (++iterationNumber >= 3) {\n" + " clearInterval(threadID);\n" + " }\n" + " }\n" + " </script>\n" + "</head>\n" + "<body onload='test()'>\n" + "</body>\n" + "</html>"; final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>()); startTimedTest(); final HtmlPage page = loadPage(content, collectedAlerts); final JavaScriptJobManager jobManager = page.getEnclosingWindow().getJobManager(); assertNotNull(jobManager); assertEquals(1, jobManager.getJobCount()); jobManager.waitForJobs(1000); assertEquals(0, jobManager.getJobCount()); assertEquals(Collections.nCopies(3, "blah"), collectedAlerts); assertMaxTestRunTime(1000); } /** * @throws Exception if the test fails */ @Test public void navigationStopThreadsInChildWindows() throws Exception { final String firstContent = "<html><head><title>First</title></head><body>\n" + "<iframe id='iframe1' src='" + URL_SECOND + "'>\n" + "<a href='" + URL_THIRD.toExternalForm() + "' id='clickme'>click me</a>\n" + "</body></html>"; final String secondContent = "<html><head><title>Second</title></head><body>\n" + "<script>\n" + "setInterval('', 30000);\n" + "</script>\n" + "</body></html>"; final String thirdContent = "<html><head><title>Third</title></head><body></body></html>"; final WebClient client = new WebClient(); final MockWebConnection webConnection = new MockWebConnection(); webConnection.setResponse(URL_FIRST, firstContent); webConnection.setResponse(URL_SECOND, secondContent); webConnection.setResponse(URL_THIRD, thirdContent); client.setWebConnection(webConnection); final HtmlPage page = client.getPage(URL_FIRST); final HtmlInlineFrame iframe = page.getHtmlElementById("iframe1"); final JavaScriptJobManager mgr = iframe.getEnclosedWindow().getJobManager(); Assert.assertEquals("inner frame should show child thread", 1, mgr.getJobCount()); final HtmlAnchor anchor = page.getHtmlElementById("clickme"); final HtmlPage newPage = anchor.click(); Assert.assertEquals("new page should load", "Third", newPage.getTitleText()); Assert.assertEquals("frame should be gone", 0, newPage.getFrames().size()); mgr.waitForJobs(10000); final int nbJobs = mgr.getJobCount(); if (nbJobs != 0) { dumpThreads(System.err); } - Assert.assertEquals("thread should stop", 0, mgr.getJobCount()); + Assert.assertEquals("job manager should have no jobs left", 0, mgr.getJobCount()); } private void dumpThreads(final PrintStream out) { out.println("Thread dump:"); final ThreadMXBean mxBean = ManagementFactory.getThreadMXBean(); final long[] allIds = mxBean.getAllThreadIds(); final ThreadInfo[] threadInfo = mxBean.getThreadInfo(allIds, Integer.MAX_VALUE); for (final ThreadInfo oneInfo : threadInfo) { out.println(); out.println("\"" + oneInfo.getThreadName() + "\" " + oneInfo.getThreadState()); final StackTraceElement[] stackTrace = oneInfo.getStackTrace(); out.println(stackTrace.length + " stack trace elements"); boolean first = true; for (final StackTraceElement stackElement : stackTrace) { if (!first) { out.print("at "); } first = false; out.println(stackElement.getClassName() + "(" + stackElement.getFileName() + ":" + stackElement.getLineNumber() + ")"); } } } /** * Test for bug 1728883 that makes sure closing a window prevents a * recursive setTimeout from continuing forever. * * @throws Exception if the test fails */ @Test public void interruptAllWithRecursiveSetTimeout() throws Exception { final String content = "<html>\n" + "<head>\n" + " <title>test</title>\n" + " <script>\n" + " var threadID;\n" + " function test() {\n" + " alert('ping');\n" + " threadID = setTimeout(test, 5);\n" + " }\n" + " </script>\n" + "</head>\n" + "<body onload='test()'>\n" + "</body>\n" + "</html>"; final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>()); final HtmlPage page = loadPage(content, collectedAlerts); final JavaScriptJobManager jobManager = page.getEnclosingWindow().getJobManager(); assertNotNull(jobManager); // Not perfect, but 100 chances to start should be enough for a loaded system Thread.sleep(500); Assert.assertFalse("At least one alert should have fired by now", collectedAlerts.isEmpty()); ((TopLevelWindow) page.getEnclosingWindow()).close(); // 100 chances to stop jobManager.waitForJobs(500); final int finalValue = collectedAlerts.size(); // 100 chances to fail jobManager.waitForJobs(500); Assert.assertEquals("No new alerts should have happened", finalValue, collectedAlerts.size()); } }
true
true
public void navigationStopThreadsInChildWindows() throws Exception { final String firstContent = "<html><head><title>First</title></head><body>\n" + "<iframe id='iframe1' src='" + URL_SECOND + "'>\n" + "<a href='" + URL_THIRD.toExternalForm() + "' id='clickme'>click me</a>\n" + "</body></html>"; final String secondContent = "<html><head><title>Second</title></head><body>\n" + "<script>\n" + "setInterval('', 30000);\n" + "</script>\n" + "</body></html>"; final String thirdContent = "<html><head><title>Third</title></head><body></body></html>"; final WebClient client = new WebClient(); final MockWebConnection webConnection = new MockWebConnection(); webConnection.setResponse(URL_FIRST, firstContent); webConnection.setResponse(URL_SECOND, secondContent); webConnection.setResponse(URL_THIRD, thirdContent); client.setWebConnection(webConnection); final HtmlPage page = client.getPage(URL_FIRST); final HtmlInlineFrame iframe = page.getHtmlElementById("iframe1"); final JavaScriptJobManager mgr = iframe.getEnclosedWindow().getJobManager(); Assert.assertEquals("inner frame should show child thread", 1, mgr.getJobCount()); final HtmlAnchor anchor = page.getHtmlElementById("clickme"); final HtmlPage newPage = anchor.click(); Assert.assertEquals("new page should load", "Third", newPage.getTitleText()); Assert.assertEquals("frame should be gone", 0, newPage.getFrames().size()); mgr.waitForJobs(10000); final int nbJobs = mgr.getJobCount(); if (nbJobs != 0) { dumpThreads(System.err); } Assert.assertEquals("thread should stop", 0, mgr.getJobCount()); }
public void navigationStopThreadsInChildWindows() throws Exception { final String firstContent = "<html><head><title>First</title></head><body>\n" + "<iframe id='iframe1' src='" + URL_SECOND + "'>\n" + "<a href='" + URL_THIRD.toExternalForm() + "' id='clickme'>click me</a>\n" + "</body></html>"; final String secondContent = "<html><head><title>Second</title></head><body>\n" + "<script>\n" + "setInterval('', 30000);\n" + "</script>\n" + "</body></html>"; final String thirdContent = "<html><head><title>Third</title></head><body></body></html>"; final WebClient client = new WebClient(); final MockWebConnection webConnection = new MockWebConnection(); webConnection.setResponse(URL_FIRST, firstContent); webConnection.setResponse(URL_SECOND, secondContent); webConnection.setResponse(URL_THIRD, thirdContent); client.setWebConnection(webConnection); final HtmlPage page = client.getPage(URL_FIRST); final HtmlInlineFrame iframe = page.getHtmlElementById("iframe1"); final JavaScriptJobManager mgr = iframe.getEnclosedWindow().getJobManager(); Assert.assertEquals("inner frame should show child thread", 1, mgr.getJobCount()); final HtmlAnchor anchor = page.getHtmlElementById("clickme"); final HtmlPage newPage = anchor.click(); Assert.assertEquals("new page should load", "Third", newPage.getTitleText()); Assert.assertEquals("frame should be gone", 0, newPage.getFrames().size()); mgr.waitForJobs(10000); final int nbJobs = mgr.getJobCount(); if (nbJobs != 0) { dumpThreads(System.err); } Assert.assertEquals("job manager should have no jobs left", 0, mgr.getJobCount()); }
diff --git a/src/main/java/org/fortasoft/maven/plugin/gradle/GradleMojo.java b/src/main/java/org/fortasoft/maven/plugin/gradle/GradleMojo.java index 6d61e39..3bdbe5c 100644 --- a/src/main/java/org/fortasoft/maven/plugin/gradle/GradleMojo.java +++ b/src/main/java/org/fortasoft/maven/plugin/gradle/GradleMojo.java @@ -1,288 +1,288 @@ // Copyright (C) 2013 Rob Schoening - http://www.github.com/if6was9 // // 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.fortasoft.maven.plugin.gradle; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.gradle.tooling.BuildLauncher; import org.gradle.tooling.GradleConnectionException; import org.gradle.tooling.GradleConnector; import org.gradle.tooling.ProgressEvent; import org.gradle.tooling.ProgressListener; import org.gradle.tooling.ProjectConnection; import org.gradle.tooling.ResultHandler; import org.slf4j.impl.MavenLogWrapper; import org.slf4j.impl.NewMojoLogger; import groovy.lang.Binding; import groovy.lang.GroovyShell; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; /** * Goal which invokes gradle! * * @goal invoke * */ public class GradleMojo extends AbstractMojo { /** * @parameter expression="1.6" * @required */ private String gradleVersion; /** * @parameter expression="${tasks}" */ private String[] tasks; /** * @parameter expression="${task}" */ private String task; /** * @parameter expression="${project.basedir}" */ private File gradleProjectDirectory; /** * @parameter * */ private String checkInvokeScript; /** * * @parameter */ private String[] args; /** * * @parameter */ private String[] jvmArgs; /** * @parameter */ private File javaHome; /** * * @parameter expression="${project.basedir}" * @required */ private File mavenBaseDir; /** * @parameter */ // http://www.gradle.org/docs/current/javadoc/org/gradle/tooling/GradleConnector.html#useDistribution(java.net.URI) private String gradleDistribution; /** * @parameter */ // http://www.gradle.org/docs/current/javadoc/org/gradle/tooling/GradleConnector.html#useGradleUserHomeDir(java.io.File) private File gradleUserHomeDir; /** * @parameter */ // http://www.gradle.org/docs/current/javadoc/org/gradle/tooling/GradleConnector.html#useInstallation(java.io.File) private File gradleInstallationDir; File getGradleProjectDirectory() { return gradleProjectDirectory; } String[] getTasks() throws MojoFailureException { String[] theTasks; if (task != null) { if (tasks != null) { throw new MojoFailureException( "<task> and <tasks> are mutually exclusive"); } theTasks = new String[] { task }; } else if (tasks != null) { if (tasks.length > 0) { theTasks = tasks; } else { throw new MojoFailureException( "No <task> elements specified within <tasks>"); } } else { throw new MojoFailureException( "<task> or <tasks> elements are mandatory"); } return theTasks; } protected GradleConnectionException gradleConnectionException; volatile boolean invocationComplete = false; class MyProgressListener implements ProgressListener { @Override public void statusChanged(ProgressEvent arg0) { getLog().info(arg0.getDescription()); } } class MyResultHandler implements ResultHandler<Void> { @Override public void onComplete(Void arg0) { invocationComplete = true; getLog().info("gradle execution complete"); } @Override public void onFailure(GradleConnectionException arg0) { synchronized (this) { invocationComplete = true; } gradleConnectionException = arg0; } } protected boolean shouldExecute() throws MojoFailureException { boolean shouldExecute = true; if (checkInvokeScript != null && checkInvokeScript.trim().length() > 0) { Binding b = new Binding(); b.setVariable("mavenBaseDir", mavenBaseDir); GroovyShell gs = new GroovyShell(b); Object rval = gs.evaluate(checkInvokeScript); if (rval != null && rval instanceof Boolean) { Boolean boolRval = (Boolean) rval; shouldExecute = boolRval.booleanValue(); } else { throw new MojoFailureException( "checkScript must return boolean"); } } return shouldExecute; } public void execute() throws MojoExecutionException, MojoFailureException { ProjectConnection connection = null; try { NewMojoLogger.attachMojo(this); if (!shouldExecute()) { return; } GradleConnector c = GradleConnector.newConnector(); getLog().info("jvmArgs: " + args); getLog().info( "gradleProjectDirectory: " + getGradleProjectDirectory().getAbsolutePath()); c = c.useGradleVersion(gradleVersion).forProjectDirectory( getGradleProjectDirectory()); if (gradleInstallationDir != null) { getLog().info( "gradleInstallation: " + gradleInstallationDir.getAbsolutePath()); c = c.useInstallation(gradleInstallationDir); } if (gradleUserHomeDir != null) { getLog().info( - "gradleInstallation: " + "gradleUserHome: " + gradleUserHomeDir.getAbsolutePath()); - c = c.useInstallation(gradleUserHomeDir); + c = c.useGradleUserHomeDir(gradleUserHomeDir); } if (gradleDistribution != null) { getLog().info("gradleDistributionUri: " + gradleDistribution); c = c.useDistribution(new URI(gradleDistribution)); } connection = c.connect(); BuildLauncher launcher = connection.newBuild(); launcher.forTasks(getTasks()); if (jvmArgs != null && jvmArgs.length > 0) { launcher.setJvmArguments(jvmArgs); } if (args != null && args.length > 0) { launcher.withArguments(args); } if (javaHome != null) { launcher.setJavaHome(javaHome); } launcher.addProgressListener(new MyProgressListener()); // launcher will not block launcher.run(new MyResultHandler()); waitForGradleToComplete(); if (gradleConnectionException != null) { throw new MojoFailureException(gradleConnectionException, gradleConnectionException.toString(), gradleConnectionException.toString()); } } catch (URISyntaxException e) { throw new MojoFailureException("gradleDistribution is not in URI syntax"); } finally { if (connection != null) { connection.close(); } NewMojoLogger.detachMojo(); } } synchronized void waitForGradleToComplete() { while (!invocationComplete) { try { this.wait(50L); } catch (InterruptedException e) { } getLog().debug("waiting...."); } } }
false
true
public void execute() throws MojoExecutionException, MojoFailureException { ProjectConnection connection = null; try { NewMojoLogger.attachMojo(this); if (!shouldExecute()) { return; } GradleConnector c = GradleConnector.newConnector(); getLog().info("jvmArgs: " + args); getLog().info( "gradleProjectDirectory: " + getGradleProjectDirectory().getAbsolutePath()); c = c.useGradleVersion(gradleVersion).forProjectDirectory( getGradleProjectDirectory()); if (gradleInstallationDir != null) { getLog().info( "gradleInstallation: " + gradleInstallationDir.getAbsolutePath()); c = c.useInstallation(gradleInstallationDir); } if (gradleUserHomeDir != null) { getLog().info( "gradleInstallation: " + gradleUserHomeDir.getAbsolutePath()); c = c.useInstallation(gradleUserHomeDir); } if (gradleDistribution != null) { getLog().info("gradleDistributionUri: " + gradleDistribution); c = c.useDistribution(new URI(gradleDistribution)); } connection = c.connect(); BuildLauncher launcher = connection.newBuild(); launcher.forTasks(getTasks()); if (jvmArgs != null && jvmArgs.length > 0) { launcher.setJvmArguments(jvmArgs); } if (args != null && args.length > 0) { launcher.withArguments(args); } if (javaHome != null) { launcher.setJavaHome(javaHome); } launcher.addProgressListener(new MyProgressListener()); // launcher will not block launcher.run(new MyResultHandler()); waitForGradleToComplete(); if (gradleConnectionException != null) { throw new MojoFailureException(gradleConnectionException, gradleConnectionException.toString(), gradleConnectionException.toString()); } } catch (URISyntaxException e) { throw new MojoFailureException("gradleDistribution is not in URI syntax"); } finally { if (connection != null) { connection.close(); } NewMojoLogger.detachMojo(); } }
public void execute() throws MojoExecutionException, MojoFailureException { ProjectConnection connection = null; try { NewMojoLogger.attachMojo(this); if (!shouldExecute()) { return; } GradleConnector c = GradleConnector.newConnector(); getLog().info("jvmArgs: " + args); getLog().info( "gradleProjectDirectory: " + getGradleProjectDirectory().getAbsolutePath()); c = c.useGradleVersion(gradleVersion).forProjectDirectory( getGradleProjectDirectory()); if (gradleInstallationDir != null) { getLog().info( "gradleInstallation: " + gradleInstallationDir.getAbsolutePath()); c = c.useInstallation(gradleInstallationDir); } if (gradleUserHomeDir != null) { getLog().info( "gradleUserHome: " + gradleUserHomeDir.getAbsolutePath()); c = c.useGradleUserHomeDir(gradleUserHomeDir); } if (gradleDistribution != null) { getLog().info("gradleDistributionUri: " + gradleDistribution); c = c.useDistribution(new URI(gradleDistribution)); } connection = c.connect(); BuildLauncher launcher = connection.newBuild(); launcher.forTasks(getTasks()); if (jvmArgs != null && jvmArgs.length > 0) { launcher.setJvmArguments(jvmArgs); } if (args != null && args.length > 0) { launcher.withArguments(args); } if (javaHome != null) { launcher.setJavaHome(javaHome); } launcher.addProgressListener(new MyProgressListener()); // launcher will not block launcher.run(new MyResultHandler()); waitForGradleToComplete(); if (gradleConnectionException != null) { throw new MojoFailureException(gradleConnectionException, gradleConnectionException.toString(), gradleConnectionException.toString()); } } catch (URISyntaxException e) { throw new MojoFailureException("gradleDistribution is not in URI syntax"); } finally { if (connection != null) { connection.close(); } NewMojoLogger.detachMojo(); } }
diff --git a/src/parse/MethodDefParser.java b/src/parse/MethodDefParser.java index 49e0c4a..87de3ad 100644 --- a/src/parse/MethodDefParser.java +++ b/src/parse/MethodDefParser.java @@ -1,183 +1,183 @@ package parse; import java.util.*; import common.NiftyException; import parse.misc.*; import parse.stm.BlockParser; import a.*; import a.gen.GenericConstraint; import a.stm.Block; public class MethodDefParser extends Parser<MemberDef> { public static final Parser<MemberDef> singleton = new MethodDefParser(); private MethodDefParser() {} private static String[] methodQualifiers = {"public", "private", "static", "sealed"}; private static boolean isMethodQualifier(String s) { for (String qual : methodQualifiers) if (s.equals(qual)) return true; return false; } private static Success<String> parseMethodQualifier(String s, int p) { Success<String> resQual = IdentifierParser.singleton.parse(s, p); if (resQual != null && isMethodQualifier(resQual.value)) return resQual; return null; } @Override public Success<MemberDef> parse(String s, int p) { // Parse generic constraints. Success<GenericConstraint[]> resGenConstraints = GenericConstraintListParser.singleton.parse(s, p); p = resGenConstraints.rem; p = optWS(s, p); // Parse any qualifiers. List<String> quals = new ArrayList<String>(); for (;;) { Success<String> resQual = parseMethodQualifier(s, p); if (resQual == null) break; quals.add(resQual.value); p = resQual.rem; p = optWS(s, p); } // Parse the return type. Success<Type> resType = TypeParser.singleton.parse(s, p); if (resType == null) return null; p = resType.rem; p = optWS(s, p); // Parse the method name. Success<String> resName = IdentifierOrOpParser.singleton.parse(s, p); if (resName == null) return null; p = resName.rem; p = optWS(s, p); // Parse the generic parameter list, if there is one. List<String> genericParams = new ArrayList<String>(); if (s.charAt(p) == '[') { p = optWS(s, p + 1); // Parse the first generic parameter. Success<String> resGenParam = IdentifierParser.singleton.parse(s, p); if (resGenParam == null) throw new NiftyException("Expecting at least one generic parameter name after '['."); genericParams.add(resGenParam.value); p = resGenParam.rem; p = optWS(s, p); // Parse any other generic parameter names. for (;;) { // Parse the comma. if (s.charAt(p) != ',') break; - p = optWS(s, p); + p = optWS(s, p + 1); // Parse the next generic parameter name. resGenParam = IdentifierParser.singleton.parse(s, p); if (resGenParam == null) throw new NiftyException("Expecting another generic parameter name after ','."); genericParams.add(resGenParam.value); p = resGenParam.rem; p = optWS(s, p); } // Parse the ']'. if (s.charAt(p++) != ']') throw new NiftyException("Unclosed generic param list; expecting ']'."); p = optWS(s, p); } // Parse the parameter list. List<Type> paramTypes = new ArrayList<Type>(); List<String> paramNames = new ArrayList<String>(); if (s.charAt(p++) != '(') return null; p = optWS(s, p); if (s.charAt(p) != ')') { // Parse the first parameter. Success<Type> resParamType = TypeParser.singleton.parse(s, p); if (resParamType == null) return null; p = resParamType.rem; p = optWS(s, p); Success<String> resParamName = IdentifierParser.singleton.parse(s, p); if (resParamName == null) throw new NiftyException("Found a parameter type with no corresponding name."); p = resParamName.rem; p = optWS(s, p); paramTypes.add(resParamType.value); paramNames.add(resParamName.value); // Parse any other parameters. for (;;) { // Parse the comma. if (s.charAt(p) != ',') break; p = optWS(s, p + 1); // Parse the parameter type. resParamType = TypeParser.singleton.parse(s, p); if (resParamType == null) throw new NiftyException("Expecting another parameter type after ','."); p = resParamType.rem; p = optWS(s, p); // Parse the parameter name. resParamName = IdentifierParser.singleton.parse(s, p); if (resParamName == null) throw new NiftyException("Found a parameter type with no corresponding name."); p = resParamName.rem; p = optWS(s, p); paramTypes.add(resParamType.value); paramNames.add(resParamName.value); } } if (s.charAt(p++) != ')') throw new NiftyException("Expecting ')' to close method parameter list."); p = optWS(s, p); // Parse the method body. Block body; if (s.charAt(p) == ';') { // This is an abstract method. body = null; ++p; } else { Success<Block> resBody; try { resBody = BlockParser.singleton.parse(s, p); } catch (RuntimeException e) { throw new NiftyException(e, "Parse error in method %s.", resName.value); } if (resBody == null) throw new NiftyException("Expecting method body or ';'."); body = resBody.value; p = resBody.rem; } p = optWS(s, p); // Collect the results. String[] qualsArr = quals.toArray(new String[quals.size()]); String[] genericParamsArr = genericParams.toArray(new String[genericParams.size()]); Type[] paramTypesArr = paramTypes.toArray(new Type[paramTypes.size()]); String[] paramNamesArr = paramNames.toArray(new String[paramNames.size()]); MethodDef result = new MethodDef( resGenConstraints.value, qualsArr, resType.value, resName.value, genericParamsArr, paramTypesArr, paramNamesArr, body); return new Success<MemberDef>(result, p); } }
true
true
public Success<MemberDef> parse(String s, int p) { // Parse generic constraints. Success<GenericConstraint[]> resGenConstraints = GenericConstraintListParser.singleton.parse(s, p); p = resGenConstraints.rem; p = optWS(s, p); // Parse any qualifiers. List<String> quals = new ArrayList<String>(); for (;;) { Success<String> resQual = parseMethodQualifier(s, p); if (resQual == null) break; quals.add(resQual.value); p = resQual.rem; p = optWS(s, p); } // Parse the return type. Success<Type> resType = TypeParser.singleton.parse(s, p); if (resType == null) return null; p = resType.rem; p = optWS(s, p); // Parse the method name. Success<String> resName = IdentifierOrOpParser.singleton.parse(s, p); if (resName == null) return null; p = resName.rem; p = optWS(s, p); // Parse the generic parameter list, if there is one. List<String> genericParams = new ArrayList<String>(); if (s.charAt(p) == '[') { p = optWS(s, p + 1); // Parse the first generic parameter. Success<String> resGenParam = IdentifierParser.singleton.parse(s, p); if (resGenParam == null) throw new NiftyException("Expecting at least one generic parameter name after '['."); genericParams.add(resGenParam.value); p = resGenParam.rem; p = optWS(s, p); // Parse any other generic parameter names. for (;;) { // Parse the comma. if (s.charAt(p) != ',') break; p = optWS(s, p); // Parse the next generic parameter name. resGenParam = IdentifierParser.singleton.parse(s, p); if (resGenParam == null) throw new NiftyException("Expecting another generic parameter name after ','."); genericParams.add(resGenParam.value); p = resGenParam.rem; p = optWS(s, p); } // Parse the ']'. if (s.charAt(p++) != ']') throw new NiftyException("Unclosed generic param list; expecting ']'."); p = optWS(s, p); } // Parse the parameter list. List<Type> paramTypes = new ArrayList<Type>(); List<String> paramNames = new ArrayList<String>(); if (s.charAt(p++) != '(') return null; p = optWS(s, p); if (s.charAt(p) != ')') { // Parse the first parameter. Success<Type> resParamType = TypeParser.singleton.parse(s, p); if (resParamType == null) return null; p = resParamType.rem; p = optWS(s, p); Success<String> resParamName = IdentifierParser.singleton.parse(s, p); if (resParamName == null) throw new NiftyException("Found a parameter type with no corresponding name."); p = resParamName.rem; p = optWS(s, p); paramTypes.add(resParamType.value); paramNames.add(resParamName.value); // Parse any other parameters. for (;;) { // Parse the comma. if (s.charAt(p) != ',') break; p = optWS(s, p + 1); // Parse the parameter type. resParamType = TypeParser.singleton.parse(s, p); if (resParamType == null) throw new NiftyException("Expecting another parameter type after ','."); p = resParamType.rem; p = optWS(s, p); // Parse the parameter name. resParamName = IdentifierParser.singleton.parse(s, p); if (resParamName == null) throw new NiftyException("Found a parameter type with no corresponding name."); p = resParamName.rem; p = optWS(s, p); paramTypes.add(resParamType.value); paramNames.add(resParamName.value); } } if (s.charAt(p++) != ')') throw new NiftyException("Expecting ')' to close method parameter list."); p = optWS(s, p); // Parse the method body. Block body; if (s.charAt(p) == ';') { // This is an abstract method. body = null; ++p; } else { Success<Block> resBody; try { resBody = BlockParser.singleton.parse(s, p); } catch (RuntimeException e) { throw new NiftyException(e, "Parse error in method %s.", resName.value); } if (resBody == null) throw new NiftyException("Expecting method body or ';'."); body = resBody.value; p = resBody.rem; } p = optWS(s, p); // Collect the results. String[] qualsArr = quals.toArray(new String[quals.size()]); String[] genericParamsArr = genericParams.toArray(new String[genericParams.size()]); Type[] paramTypesArr = paramTypes.toArray(new Type[paramTypes.size()]); String[] paramNamesArr = paramNames.toArray(new String[paramNames.size()]); MethodDef result = new MethodDef( resGenConstraints.value, qualsArr, resType.value, resName.value, genericParamsArr, paramTypesArr, paramNamesArr, body); return new Success<MemberDef>(result, p); }
public Success<MemberDef> parse(String s, int p) { // Parse generic constraints. Success<GenericConstraint[]> resGenConstraints = GenericConstraintListParser.singleton.parse(s, p); p = resGenConstraints.rem; p = optWS(s, p); // Parse any qualifiers. List<String> quals = new ArrayList<String>(); for (;;) { Success<String> resQual = parseMethodQualifier(s, p); if (resQual == null) break; quals.add(resQual.value); p = resQual.rem; p = optWS(s, p); } // Parse the return type. Success<Type> resType = TypeParser.singleton.parse(s, p); if (resType == null) return null; p = resType.rem; p = optWS(s, p); // Parse the method name. Success<String> resName = IdentifierOrOpParser.singleton.parse(s, p); if (resName == null) return null; p = resName.rem; p = optWS(s, p); // Parse the generic parameter list, if there is one. List<String> genericParams = new ArrayList<String>(); if (s.charAt(p) == '[') { p = optWS(s, p + 1); // Parse the first generic parameter. Success<String> resGenParam = IdentifierParser.singleton.parse(s, p); if (resGenParam == null) throw new NiftyException("Expecting at least one generic parameter name after '['."); genericParams.add(resGenParam.value); p = resGenParam.rem; p = optWS(s, p); // Parse any other generic parameter names. for (;;) { // Parse the comma. if (s.charAt(p) != ',') break; p = optWS(s, p + 1); // Parse the next generic parameter name. resGenParam = IdentifierParser.singleton.parse(s, p); if (resGenParam == null) throw new NiftyException("Expecting another generic parameter name after ','."); genericParams.add(resGenParam.value); p = resGenParam.rem; p = optWS(s, p); } // Parse the ']'. if (s.charAt(p++) != ']') throw new NiftyException("Unclosed generic param list; expecting ']'."); p = optWS(s, p); } // Parse the parameter list. List<Type> paramTypes = new ArrayList<Type>(); List<String> paramNames = new ArrayList<String>(); if (s.charAt(p++) != '(') return null; p = optWS(s, p); if (s.charAt(p) != ')') { // Parse the first parameter. Success<Type> resParamType = TypeParser.singleton.parse(s, p); if (resParamType == null) return null; p = resParamType.rem; p = optWS(s, p); Success<String> resParamName = IdentifierParser.singleton.parse(s, p); if (resParamName == null) throw new NiftyException("Found a parameter type with no corresponding name."); p = resParamName.rem; p = optWS(s, p); paramTypes.add(resParamType.value); paramNames.add(resParamName.value); // Parse any other parameters. for (;;) { // Parse the comma. if (s.charAt(p) != ',') break; p = optWS(s, p + 1); // Parse the parameter type. resParamType = TypeParser.singleton.parse(s, p); if (resParamType == null) throw new NiftyException("Expecting another parameter type after ','."); p = resParamType.rem; p = optWS(s, p); // Parse the parameter name. resParamName = IdentifierParser.singleton.parse(s, p); if (resParamName == null) throw new NiftyException("Found a parameter type with no corresponding name."); p = resParamName.rem; p = optWS(s, p); paramTypes.add(resParamType.value); paramNames.add(resParamName.value); } } if (s.charAt(p++) != ')') throw new NiftyException("Expecting ')' to close method parameter list."); p = optWS(s, p); // Parse the method body. Block body; if (s.charAt(p) == ';') { // This is an abstract method. body = null; ++p; } else { Success<Block> resBody; try { resBody = BlockParser.singleton.parse(s, p); } catch (RuntimeException e) { throw new NiftyException(e, "Parse error in method %s.", resName.value); } if (resBody == null) throw new NiftyException("Expecting method body or ';'."); body = resBody.value; p = resBody.rem; } p = optWS(s, p); // Collect the results. String[] qualsArr = quals.toArray(new String[quals.size()]); String[] genericParamsArr = genericParams.toArray(new String[genericParams.size()]); Type[] paramTypesArr = paramTypes.toArray(new Type[paramTypes.size()]); String[] paramNamesArr = paramNames.toArray(new String[paramNames.size()]); MethodDef result = new MethodDef( resGenConstraints.value, qualsArr, resType.value, resName.value, genericParamsArr, paramTypesArr, paramNamesArr, body); return new Success<MemberDef>(result, p); }
diff --git a/com/tivo/hme/sdk/Factory.java b/com/tivo/hme/sdk/Factory.java index fb0b57c..2630205 100644 --- a/com/tivo/hme/sdk/Factory.java +++ b/com/tivo/hme/sdk/Factory.java @@ -1,714 +1,714 @@ ////////////////////////////////////////////////////////////////////// // // File: Factory.java // // Copyright (c) 2003-2005 TiVo Inc. // ////////////////////////////////////////////////////////////////////// package com.tivo.hme.sdk; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.text.NumberFormat; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import java.util.Vector; import com.tivo.hme.interfaces.IApplication; import com.tivo.hme.interfaces.IArgumentList; import com.tivo.hme.interfaces.IContext; import com.tivo.hme.interfaces.IFactory; import com.tivo.hme.interfaces.IHmeConstants; import com.tivo.hme.interfaces.IHttpRequest; import com.tivo.hme.interfaces.IListener; import com.tivo.hme.interfaces.ILoader; import com.tivo.hme.interfaces.ILogger; import com.tivo.hme.sdk.io.FastInputStream; import com.tivo.hme.sdk.io.HmeInputStream; import com.tivo.hme.sdk.io.HmeOutputStream; import com.tivo.hme.sdk.util.Mp3Helper; /** * A factory of applications. * * @author Adam Doppelt * @author Arthur van Hoff * @author Brigham Stevens * @author Jonathan Payne * @author Steven Samorodin */ @SuppressWarnings("unchecked") public class Factory implements IFactory { /** * The listener for this factory. */ protected IListener listener; /** * Class loader for the main class. */ protected ClassLoader loader; /** * The factory uri prefix, used to accept connections. It always starts * and ends with '/'. */ protected String uri; /** * The asset uri used to load external assets. This might be null. */ protected URL assetURI; /** * The factory title that will be displayed in the chooser. */ protected String title; /** * The class used to create application instances. */ protected Class clazz; /** * The list of active applications created by the factory. */ protected Vector active; /** * Whether or not this factory is draining (waiting for the last instance to * finish) or not. */ protected boolean isActive; /** * For associating data with the factory */ protected Map factoryData; /** * A factory of applications. */ public Factory() { this.active = new Vector(); } /** * Init the factory. Subclasses should override this. */ protected void init(IArgumentList args) { } /** * Create an instance of an application. Uses clazz by default. */ public IApplication createApplication(IContext context) throws IOException { HmeOutputStream out = null; HmeInputStream in = null; if (context.getOutputStream() instanceof HmeOutputStream) out = (HmeOutputStream)context.getOutputStream(); else out = new HmeOutputStream(context.getOutputStream()); if (context.getInputStream() instanceof HmeInputStream) in = (HmeInputStream)context.getInputStream(); else in = new HmeInputStream(context.getInputStream()); // HME protocol starts here out.writeInt(IHmeProtocol.MAGIC); out.writeInt(IHmeProtocol.VERSION); out.flush(); // read magic and version int magic = in.readInt(); if (magic != IHmeProtocol.MAGIC) { throw new IOException("bad magic: 0x" + Integer.toHexString(magic)); } int version = in.readInt(); if (version >> 8 < IHmeProtocol.VERSION >> 8 ) { throw new IOException( "version mismatch: " + ( version >> 8 ) + "." + ( version & 0xff ) + " < " + ( IHmeProtocol.VERSION >> 8 ) + "." + ( IHmeProtocol.VERSION & 0xff ) ); } IApplication retApp = null; try { Application app = (Application)clazz.newInstance(); app.setFactory(this); app.setContext(context, version); retApp = app; } catch (InstantiationException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } return retApp; } // // accessors // /** * Get the factory uri prefix. */ public String getURI() { return uri; } /** * The URI for loading external assets. */ public URL getAssetURI() { return assetURI; } /** * Get the factory's title. */ public String getTitle() { return title; } /** * Set the uri prefix. */ public void setURI(String uri) { if (!uri.startsWith("/")) { uri = "/" + uri; } if (!uri.endsWith("/")) { uri += "/"; } this.uri = uri; } /** * Set the title. */ public void setTitle(String title) { this.title = title; } /** * Set the asset URI. */ public void setAssetURI(URL assetURI) { this.assetURI = assetURI; } /** * Returns false if the factory is draining, i.e., not accepting new * connections. */ public boolean isActive() { return isActive; } /** * Returns the # of active connections. */ public int getActiveCount() { return active.size(); } protected long getMP3Duration(String uri) { return -1; } /** * This is called by the HTTP server when the factory must handle an http * request. */ private InputStream handleHTTP(IHttpRequest http, String uri) throws IOException { InputStream in = null; // check for query portion of URI - i.e. "?foo=bar" stuff String queryStr = getQuery(uri); String baseUri = removeQueryFromURI(uri); try { in = getStream(baseUri); } catch (IOException e) { http.reply(404, e.getMessage()); return null; } long offset = 0; String range = http.get("Range"); if ((range != null) && range.startsWith("bytes=") && range.endsWith("-")) { try { offset = Long.parseLong(range.substring(6, range.length() - 1)); } catch (NumberFormatException e) { // ignore } } if (!http.getReplied()) { if (offset == 0) { http.reply(200, "Media follows"); } else { http.reply(206, "Partial Media follows"); } } String ct = null; if (baseUri.endsWith(".mpeg") || baseUri.endsWith(".mpg")) { ct = "video/mpeg"; } else if (baseUri.endsWith(".mp3")) { // set the MP3 content type string ct = "audio/mpeg"; // Get the mp3 stream's duration - long mp3duration = getMP3Duration(uri); + long mp3duration = getMP3Duration(baseUri); System.out.println("MP3 stream duration: " + mp3duration); if (mp3duration > 0) http.addHeader(IHmeConstants.TIVO_DURATION, "" + mp3duration); // do MP3 seek if needed if (in != null && queryStr != null) { int seekTime = getSeekTime(queryStr); Mp3Helper mp3Helper = new Mp3Helper(in, in.available()); in = mp3Helper.seek(seekTime); } } if (ct != null) { http.addHeader("Content-Type", ct); } if (offset > 0) { long total = in.available(); http.addHeader("Content-Range", "bytes " + offset + "-" + (total-1) + "/" + total); in.skip(offset); } addHeaders(http, baseUri); if (http.get("http-method").equalsIgnoreCase("HEAD")) { return null; } return in; } /** * Subclasses can override this method to add more HTTP headers to a response. * */ protected void addHeaders(IHttpRequest http, String uri) throws IOException { } /** * A simple stream that responds correctly to in.available(). This is for * http streams. */ static class URLStream extends FastInputStream { long contentLength; URLStream(InputStream in, long contentLength) { super(in, IHmeConstants.TCP_BUFFER_SIZE); this.contentLength = contentLength; } public int available() { return (int) contentLength; } public int read() throws IOException { contentLength -= 1; return in.read(); } public int read(byte b[], int off, int length) throws IOException { int n = super.read(b, off, length); if (n > 0) { contentLength -= n; } return n; } public long skip(long n) throws IOException { n = super.skip(n); if (n > 0) { contentLength -= n; } return n; } } /** * Open a resource stream. Throws an exception if it cannot find the * requested stream. */ public InputStream getStream(String uri) throws IOException { // // 1 - is it a full URI? // if (uri.startsWith("http://")) { URL url = new URL(uri); URLConnection conn = url.openConnection(); return new URLStream(conn.getInputStream(), conn.getContentLength()); } // // 2 - try package/uri in classpath // String pkg = clazz.getName(); int last = pkg.lastIndexOf('.'); if (last > 0) { pkg = pkg.substring(0, last).replace('.', '/'); InputStream in = loader.getResourceAsStream(pkg + "/" + uri); if (in != null) { return in; } } // // 3 - try uri in classpath // InputStream in = loader.getResourceAsStream(uri); if (in != null) { return in; } throw new FileNotFoundException(uri); } /* (non-Javadoc) * @see com.tivo.hme.hosting.IFactory#addApplication(com.tivo.hme.hosting.IApplication) */ public void addApplication(IApplication app) { active.addElement(app); log(ILogger.LOG_NOTICE, "HME receiver connected"); } /* (non-Javadoc) * @see com.tivo.hme.hosting.IFactory#removeApplication(com.tivo.hme.hosting.IApplication) */ public void removeApplication(IApplication app) { log(ILogger.LOG_NOTICE, "HME receiver disconnected"); active.removeElement(app); // If we're not active and we just removed the last instance then remove // this from the listener. if (!isActive && active.size() == 0) { listener.remove(this); } } /** * Sets the factory to active or not. An active factory accepts new factory * connections. */ public void setActive(boolean isActive) { if (this.isActive != isActive) { this.isActive = isActive; if (!isActive) { if (active.size() == 0) { listener.remove(this); close(); } else { log(ILogger.LOG_NOTICE, "Start draining " + active.size() + " active"); } } } } /** * Close down the factory. This is called for inactive applications with no * active connections and by shutdown(). Subclasses can override this to do * factory-specific things. */ protected void close() { } /** * Shutdown the factory: remove it from the listener and close all the * connections. This is called if there is a security error while loading * one of the application's classes. */ public final void shutdown() { if (listener != null) { listener.remove(this); listener = null; for (int i = active.size(); --i >= 0;) { IApplication app = (IApplication)active.elementAt(i); try { app.close(); } catch (RuntimeException e) { System.out.println("Ignoring: " + e); } } active.clear(); if (loader instanceof ILoader) { ((ILoader) loader).close(); } } } /** * Convert to string for debugging. */ public String toString() { String nm = getClass().getName(); int i = nm.lastIndexOf('$'); if (i >= 0) { nm = nm.substring(i+1); } return nm + "[" + uri + "," + title + "]"; } public void log(int priority, String msg) { if (listener != null) { listener.getLogger().log(priority, msg); } else { System.out.println("LOG: " + msg); } } private String getField(String name) { try { return (String) clazz.getField(name).get(null); } catch (NoSuchFieldException e) { } catch (IllegalAccessException e) { } return null; } protected String getQuery(String uri) { String queryStr = null; int index = uri.lastIndexOf("?"); if (index > 0) { queryStr = uri.substring(uri.lastIndexOf("?")+1); //System.out.println("**** queryStr = ->"+queryStr+"<-"); } return queryStr; } protected String removeQueryFromURI(String uri) { int index = uri.lastIndexOf("?"); if (index > 0) { uri = uri.substring(0, uri.lastIndexOf("?")); //System.out.println("**** uri minus queryStr = ->"+uri+"<-"); } return uri; } protected int getSeekTime(String queryStr) { int timeToSkip = 0; if (queryStr != null && queryStr.indexOf("Seek=") != -1) { // determine how far to seek. int index = queryStr.indexOf("Seek=")+5; String sub = queryStr.substring(index); NumberFormat numFormatter = NumberFormat.getInstance(); numFormatter.setParseIntegerOnly(true); try { timeToSkip = numFormatter.parse(sub).intValue(); } catch (ParseException e) { // can't parse the number, return 0 } } return timeToSkip; } /* (non-Javadoc) * @see com.tivo.hme.hosting.IFactory#init(com.tivo.hme.hosting.IContext) */ public void initFactory(String appClassName, ClassLoader loader, IArgumentList args) { this.loader = loader; try { // load the class and make sure it has a public empty constructor this.clazz = Class.forName(appClassName, true, loader); if (!IApplication.class.isAssignableFrom(clazz)) { log(ILogger.LOG_WARNING, clazz.getName() + " does not implement IApplication, can't construct application."); } this.clazz.getConstructor(new Class[0]); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } // set uri String uri = this.getField("URI"); if (uri == null) { uri = appClassName; int d2 = appClassName.lastIndexOf('.'); if (d2 >= 0) { int d1 = appClassName.lastIndexOf('.', d2 - 1); if (d1 >= 0) { uri = appClassName.substring(d1 + 1, d2); } else { uri = appClassName.substring(0, d2); } } } this.setURI(uri); // set title this.title = this.getField("TITLE"); if (this.title == null) { String classNoPackage = appClassName.substring(appClassName.lastIndexOf('.') + 1); this.title = classNoPackage; } String user = System.getProperty("hme.user"); if (user != null) { this.title += " " + user; } getFactoryData().put(IFactory.HME_APPLICATION_CLASSNAME, appClassName); getFactoryData().put(IFactory.HME_VERSION_TAG, IHmeProtocol.VERSION_STRING); // tell jar class loaders about the factory because jar class loaders // will react to security errors in the jar file if (loader instanceof ILoader) { ((ILoader) loader).setFactory(this); } // initialize the factory this.init(args); } /* (non-Javadoc) * @see com.tivo.hme.hosting.IFactory#destroy() */ public void destroyFactory() { shutdown(); } /* (non-Javadoc) * @see com.tivo.hme.hosting.IFactory#getAppName() */ public String getAppName() { return getURI(); } /* (non-Javadoc) * @see com.tivo.hme.hosting.IFactory#getAppTitle() */ public String getAppTitle() { return getTitle(); } /* (non-Javadoc) * @see com.tivo.hme.hosting.IFactory#setAppName(java.lang.String) */ public void setAppName(String appName) { setURI(appName); } /* (non-Javadoc) * @see com.tivo.hme.hosting.IFactory#setAppTitle(java.lang.String) */ public void setAppTitle(String title) { setTitle(title); } /* (non-Javadoc) * @see com.tivo.hme.hosting.IFactory#fetchAsset(com.tivo.hme.hosting.IHttpRequest) */ public InputStream fetchAsset(IHttpRequest req) { InputStream inStr = null; try { String path = req.getURI(); // Note the getURI.length() - 1 below. That's in case the original // URL is missing the trailing slash, e.g., http://host:port/bar?arg=val String relpath = URLDecoder.decode(path.substring(getAppName().length() - 1), "UTF-8"); // If the relative path is empty (except for query-style arguments) then // this is an application instantiation. Otherwise, pass the relative // path to the factory so it can handle it. if (relpath.startsWith("/")) { relpath = relpath.substring(1); } inStr = handleHTTP(req, relpath); } catch (IOException ex) { inStr = null; log(ILogger.LOG_WARNING , "unable to fetch asset: " + req.getURI()); } return inStr; } /* (non-Javadoc) * @see com.tivo.hme.hosting.IFactory#getFactoryData() */ public Map getFactoryData() { if (factoryData == null) { factoryData = new HashMap(); } return factoryData; } /* (non-Javadoc) * @see com.tivo.hme.hosting.IFactory#setListener(com.tivo.hme.hosting.IListener) */ public void setListener(IListener listener) { this.listener = listener; } }
true
true
private InputStream handleHTTP(IHttpRequest http, String uri) throws IOException { InputStream in = null; // check for query portion of URI - i.e. "?foo=bar" stuff String queryStr = getQuery(uri); String baseUri = removeQueryFromURI(uri); try { in = getStream(baseUri); } catch (IOException e) { http.reply(404, e.getMessage()); return null; } long offset = 0; String range = http.get("Range"); if ((range != null) && range.startsWith("bytes=") && range.endsWith("-")) { try { offset = Long.parseLong(range.substring(6, range.length() - 1)); } catch (NumberFormatException e) { // ignore } } if (!http.getReplied()) { if (offset == 0) { http.reply(200, "Media follows"); } else { http.reply(206, "Partial Media follows"); } } String ct = null; if (baseUri.endsWith(".mpeg") || baseUri.endsWith(".mpg")) { ct = "video/mpeg"; } else if (baseUri.endsWith(".mp3")) { // set the MP3 content type string ct = "audio/mpeg"; // Get the mp3 stream's duration long mp3duration = getMP3Duration(uri); System.out.println("MP3 stream duration: " + mp3duration); if (mp3duration > 0) http.addHeader(IHmeConstants.TIVO_DURATION, "" + mp3duration); // do MP3 seek if needed if (in != null && queryStr != null) { int seekTime = getSeekTime(queryStr); Mp3Helper mp3Helper = new Mp3Helper(in, in.available()); in = mp3Helper.seek(seekTime); } } if (ct != null) { http.addHeader("Content-Type", ct); } if (offset > 0) { long total = in.available(); http.addHeader("Content-Range", "bytes " + offset + "-" + (total-1) + "/" + total); in.skip(offset); } addHeaders(http, baseUri); if (http.get("http-method").equalsIgnoreCase("HEAD")) { return null; } return in; }
private InputStream handleHTTP(IHttpRequest http, String uri) throws IOException { InputStream in = null; // check for query portion of URI - i.e. "?foo=bar" stuff String queryStr = getQuery(uri); String baseUri = removeQueryFromURI(uri); try { in = getStream(baseUri); } catch (IOException e) { http.reply(404, e.getMessage()); return null; } long offset = 0; String range = http.get("Range"); if ((range != null) && range.startsWith("bytes=") && range.endsWith("-")) { try { offset = Long.parseLong(range.substring(6, range.length() - 1)); } catch (NumberFormatException e) { // ignore } } if (!http.getReplied()) { if (offset == 0) { http.reply(200, "Media follows"); } else { http.reply(206, "Partial Media follows"); } } String ct = null; if (baseUri.endsWith(".mpeg") || baseUri.endsWith(".mpg")) { ct = "video/mpeg"; } else if (baseUri.endsWith(".mp3")) { // set the MP3 content type string ct = "audio/mpeg"; // Get the mp3 stream's duration long mp3duration = getMP3Duration(baseUri); System.out.println("MP3 stream duration: " + mp3duration); if (mp3duration > 0) http.addHeader(IHmeConstants.TIVO_DURATION, "" + mp3duration); // do MP3 seek if needed if (in != null && queryStr != null) { int seekTime = getSeekTime(queryStr); Mp3Helper mp3Helper = new Mp3Helper(in, in.available()); in = mp3Helper.seek(seekTime); } } if (ct != null) { http.addHeader("Content-Type", ct); } if (offset > 0) { long total = in.available(); http.addHeader("Content-Range", "bytes " + offset + "-" + (total-1) + "/" + total); in.skip(offset); } addHeaders(http, baseUri); if (http.get("http-method").equalsIgnoreCase("HEAD")) { return null; } return in; }
diff --git a/src-ai/hughai/packcoordinators/AttackPackCoordinator.java b/src-ai/hughai/packcoordinators/AttackPackCoordinator.java index b75f0b4..90d0a64 100755 --- a/src-ai/hughai/packcoordinators/AttackPackCoordinator.java +++ b/src-ai/hughai/packcoordinators/AttackPackCoordinator.java @@ -1,283 +1,286 @@ // Copyright Hugh Perkins 2006, 2009 // [email protected] http://manageddreams.com // // 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 in the file licence.txt; if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111- // 1307 USA // You can find the licence also on the web at: // http://www.opensource.org/licenses/gpl-license.php // // ====================================================================================== // package hughai.packcoordinators; import java.util.*; import com.springrts.ai.*; import com.springrts.ai.oo.*; import com.springrts.ai.oo.Map; import hughai.*; import hughai.utils.*; import hughai.basictypes.*; import hughai.unitdata.*; // this manages an attack pack, eg group of tanks // specifically ,ensures they stay together, rather than streaming // in theory public class AttackPackCoordinator extends PackCoordinator { public float MaxPackDiameterOuterThreshold = 500; public float MaxPackDiameterInnerThreshold = 300; public float movetothreshold = 20; public int MaxPackToConsider = 5; public float AttackDistance = 50; // HashMap< Integer,UnitDef> UnitDefListByDeployedId; TerrainPos targetpos; UnitController unitController; //public delegate void AttackPackDeadHandler(); //public event AttackPackDeadHandler AttackPackDeadEvent; // can pass in pointer to a hashtable in another class if we want // ie other class can directly modify our hashtable public AttackPackCoordinator( PlayerObjects playerObjects ) { super(playerObjects); this.unitController = playerObjects.getUnitController(); csai.registerGameListener( new GameListenerHandler() ); // csai.TickEvent += new CSAI.TickHandler( this.Tick ); } // does NOT imply Activate() @Override public void SetTarget( TerrainPos newtarget ) { this.targetpos = newtarget; //Activate(); } TerrainPos lasttargetpos = null; @Override void Recoordinate() { if( !activated ) { return; } // first we scan the list to find the 5 closest units to target, in order // next we measure distance of first unit from 5th // if distance is less than MaxPackDiameter, we move in // otherwise 5th unit holds, and we move units to position of 5th unit // pack must have at least 5 units, otherwise we call AttackPackDead event if( !CheckIfPackAlive() ) { return; } logfile.WriteLine( this.getClass().getSimpleName() + " recoordinate" ); int packsize = Math.min(MaxPackToConsider, unitsControlled.size()); UnitInfo[] closestunits = GetClosestUnits(targetpos, packsize); + if( closestunits.length < 0 ) { + return; + } TerrainPos packheadpos = closestunits[0].pos; TerrainPos packtailpos = closestunits[packsize - 1].pos; double packsquareddiameter = packheadpos.GetSquaredDistance( packtailpos ); csai.DebugSay("packsize: " + packsize + " packdiameter: " + Math.sqrt(packsquareddiameter)); // logfile.WriteLine( "AttackPackCoordinator packheadpos " + packheadpos.toString() + " packtailpos " + packtailpos.toString() + " packsquareddiamter " + packsquareddiameter ); if (( regrouping && ( packsquareddiameter < (MaxPackDiameterInnerThreshold * MaxPackDiameterInnerThreshold) ) ) || (!regrouping && ( packsquareddiameter < (MaxPackDiameterOuterThreshold * MaxPackDiameterOuterThreshold)) )) { regrouping = false; csai.DebugSay("attacking"); Attack( closestunits); } else { csai.DebugSay("regrouping"); regrouping = true; Regroup(closestunits[(packsize / 2)].pos); } } //boolean attacking = false; boolean regrouping = false; // placeholder... void GetAttackDistance(UnitInfo[]closestunits) { // for( UnitInfo unitinfo : closestunits ) // { // if( unitinfo.unitdef. // } } void Attack(UnitInfo[] closestunits) { //logfile.WriteLine( "AttackPackCoordinator attacking" ); //if( debugon ) // { // aicallback.SendTextMsg( "AttackPackCoordinator attacking", 0 ); // } // get vector from head unit to target // pick point a bit behind target, backwards along vector TerrainPos vectortargettohead = targetpos.subtract( closestunits[0].pos ); vectortargettohead.Normalize(); //vectortargettohead = vectortargettohead * AttackDistance; MoveTo( targetpos.add( vectortargettohead.multiply( AttackDistance ) ) ); } void Regroup( TerrainPos regouppos ) { logfile.WriteLine( "AttackPackCoordinator regrouping to " + regouppos ); if( debugon ) { // csai.SendTextMsg( "AttackPackCoordinator regrouping to " + regouppos ); } MoveTo( regouppos ); } void MoveTo( TerrainPos pos ) { // check whether we really need to do anything or if order is roughly same as last one if( csai.DebugOn ) { drawingUtils.DrawUnit("ARMSOLAR", pos, 0.0f, 50, aicallback.getTeamId(), true, true); } if( restartedfrompause || pos.GetSquaredDistance( lasttargetpos ) > ( movetothreshold * movetothreshold ) ) { for( Unit unit : unitsControlled ) { //int deployedid = (int)de.Key; //UnitDef unitdef = de.Value as UnitDef; giveOrderWrapper.MoveTo(unit, pos ); //aicallback.GiveOrder( deployedid, new Command( Command.CMD_MOVE, pos.ToDoubleArray() ) ); } restartedfrompause = false; lasttargetpos = pos; } } boolean CheckIfPackAlive() { //if( UnitDefListByDeployedId.size() < MinPackSize ) // { // if( AttackPackDeadEvent != null ) // { // AttackPackDeadEvent(); // } // return false; // } return true; } class UnitInfo { public Unit unit; public TerrainPos pos; public UnitDef unitdef; public double squareddistance; public UnitInfo(){} public UnitInfo( Unit unit, TerrainPos pos, UnitDef unitdef, double squareddistance ) { this.unit = unit; this.pos = pos; this.unitdef = unitdef; this.squareddistance = squareddistance; } } UnitInfo[] GetClosestUnits( TerrainPos targetpos, int numclosestunits ) { UnitInfo[] closestunits = new UnitInfo[ numclosestunits ]; double worsttopfivesquareddistance = 0; // got to get better than this to enter the list int numclosestunitsfound = 0; for( Unit unit : unitsControlled ) { TerrainPos unitpos = unitController.getPos( unit ); UnitDef unitdef = unit.getDef(); double unitsquareddistance = unitpos.GetSquaredDistance( targetpos ); if( numclosestunitsfound < numclosestunits ) { UnitInfo unitinfo = new UnitInfo( unit, unitpos, unitdef, unitsquareddistance ); InsertIntoArray( closestunits, unitinfo, numclosestunitsfound ); numclosestunitsfound++; worsttopfivesquareddistance = closestunits[ numclosestunitsfound - 1 ].squareddistance; } else if( unitsquareddistance < worsttopfivesquareddistance ) { UnitInfo unitinfo = new UnitInfo( unit, unitpos, unitdef, unitsquareddistance ); InsertIntoArray( closestunits, unitinfo, numclosestunits ); worsttopfivesquareddistance = closestunits[ numclosestunits - 1 ].squareddistance; } } return closestunits; } // we add it to the bottom, then bubble it up void InsertIntoArray( UnitInfo[] closestunits, UnitInfo newunit, int numexistingunits ) { if( numexistingunits < closestunits.length ) { closestunits[ numexistingunits ] = newunit; numexistingunits++; } else { closestunits[ numexistingunits - 1 ] = newunit; } // bubble new unit up for( int i = numexistingunits - 2; i >= 0; i-- ) { if( closestunits[ i ].squareddistance > closestunits[ i + 1 ].squareddistance ) { UnitInfo swap = closestunits[ i ]; closestunits[ i ] = closestunits[ i + 1 ]; closestunits[ i + 1 ] = swap; } } // debug; // logfile.WriteLine( "AttackPackCoordinator.InsertIntoArray"); // for( int i = 0; i < numexistingunits; i++ ) // { // logfile.WriteLine(i + ": " + closestunits[ i ].squareddistance ); // } } class GameListenerHandler extends GameAdapter { // int ticks = 0; @Override public void Tick( int frame ) { // ticks++; // if( ticks >= 30 ) // { Recoordinate(); // ticks = 0; // } } } }
true
true
void Recoordinate() { if( !activated ) { return; } // first we scan the list to find the 5 closest units to target, in order // next we measure distance of first unit from 5th // if distance is less than MaxPackDiameter, we move in // otherwise 5th unit holds, and we move units to position of 5th unit // pack must have at least 5 units, otherwise we call AttackPackDead event if( !CheckIfPackAlive() ) { return; } logfile.WriteLine( this.getClass().getSimpleName() + " recoordinate" ); int packsize = Math.min(MaxPackToConsider, unitsControlled.size()); UnitInfo[] closestunits = GetClosestUnits(targetpos, packsize); TerrainPos packheadpos = closestunits[0].pos; TerrainPos packtailpos = closestunits[packsize - 1].pos; double packsquareddiameter = packheadpos.GetSquaredDistance( packtailpos ); csai.DebugSay("packsize: " + packsize + " packdiameter: " + Math.sqrt(packsquareddiameter)); // logfile.WriteLine( "AttackPackCoordinator packheadpos " + packheadpos.toString() + " packtailpos " + packtailpos.toString() + " packsquareddiamter " + packsquareddiameter ); if (( regrouping && ( packsquareddiameter < (MaxPackDiameterInnerThreshold * MaxPackDiameterInnerThreshold) ) ) || (!regrouping && ( packsquareddiameter < (MaxPackDiameterOuterThreshold * MaxPackDiameterOuterThreshold)) )) { regrouping = false; csai.DebugSay("attacking"); Attack( closestunits); } else { csai.DebugSay("regrouping"); regrouping = true; Regroup(closestunits[(packsize / 2)].pos); } }
void Recoordinate() { if( !activated ) { return; } // first we scan the list to find the 5 closest units to target, in order // next we measure distance of first unit from 5th // if distance is less than MaxPackDiameter, we move in // otherwise 5th unit holds, and we move units to position of 5th unit // pack must have at least 5 units, otherwise we call AttackPackDead event if( !CheckIfPackAlive() ) { return; } logfile.WriteLine( this.getClass().getSimpleName() + " recoordinate" ); int packsize = Math.min(MaxPackToConsider, unitsControlled.size()); UnitInfo[] closestunits = GetClosestUnits(targetpos, packsize); if( closestunits.length < 0 ) { return; } TerrainPos packheadpos = closestunits[0].pos; TerrainPos packtailpos = closestunits[packsize - 1].pos; double packsquareddiameter = packheadpos.GetSquaredDistance( packtailpos ); csai.DebugSay("packsize: " + packsize + " packdiameter: " + Math.sqrt(packsquareddiameter)); // logfile.WriteLine( "AttackPackCoordinator packheadpos " + packheadpos.toString() + " packtailpos " + packtailpos.toString() + " packsquareddiamter " + packsquareddiameter ); if (( regrouping && ( packsquareddiameter < (MaxPackDiameterInnerThreshold * MaxPackDiameterInnerThreshold) ) ) || (!regrouping && ( packsquareddiameter < (MaxPackDiameterOuterThreshold * MaxPackDiameterOuterThreshold)) )) { regrouping = false; csai.DebugSay("attacking"); Attack( closestunits); } else { csai.DebugSay("regrouping"); regrouping = true; Regroup(closestunits[(packsize / 2)].pos); } }
diff --git a/src/com/tabbie/android/radar/RadarCommonController.java b/src/com/tabbie/android/radar/RadarCommonController.java index d537ed2..0b2dd5f 100644 --- a/src/com/tabbie/android/radar/RadarCommonController.java +++ b/src/com/tabbie/android/radar/RadarCommonController.java @@ -1,153 +1,153 @@ package com.tabbie.android.radar; /* * RadarCommonController.java * * Created on: July 22, 2012 * Author: Valeri Karpov * * Data structure for maintaining a collection of events with the radar feature. Events * are accessible by id. */ import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import android.os.Parcel; import android.os.Parcelable; public class RadarCommonController implements Parcelable { public static final int MAX_RADAR_SELECTIONS = 3; private final LinkedHashMap<String, Event> events = new LinkedHashMap<String, Event>(); public final List<Event> eventsList = new ArrayList<Event>(); private final LinkedHashSet<String> radarIds = new LinkedHashSet<String>(); public final List<Event> radar = new ArrayList<Event>(); // Sort by # of people with event in radar, reversed private static final Comparator<Event> defaultOrdering = new Comparator<Event>() { public int compare(Event e1, Event e2) { if (e1.radarCount > e2.radarCount) { return -1; } else if (e1.radarCount < e2.radarCount) { return 1; } return 0; } }; public RadarCommonController() { try { Event e1 = new Event( "1", - "Rager", - "Get smashed, yeah!", + "DJ Enuff", + "DJ Enuff plays a rare live show at Skyroom NYC. Known primarily for his production work, Enuff is eager to return to the his first home, the club. ", "Skyroom NYC", - new URL("http://thechive.files.wordpress.com/2009/04/demotivated-funny-karate.jpg"), + new URL("http://th02.deviantart.net/fs51/PRE/f/2009/277/3/0/Reload_Flyer_by_vektorscksprojekt.jpg"), 40.709208, -74.005864, 4, false, "11:00pm"); Event e2 = new Event( "2", - "Ginyu Force Party", - "Dress up as Ginyu Force and show off your Recoome Boom!", - "230 Fifth", - new URL("http://3.bp.blogspot.com/_NQz93lR8zIY/TSlxGIsV3vI/AAAAAAAAAOI/s0AoNlr18v8/s640/230_Fifth_v2_460x285.jpg"), + "Ok Go", + "Ok Go plays Williamsburg Park for a free show! No strangers to the Brooklyn music scene, OK Go returns with special guests to deliver an electrifying show.", + "Williamsburg Park", + new URL("http://www.examiner.com/images/blog/EXID27067/images/ok_go(1).jpg"), 40.744253, -73.987991, 6, true, "8:00pm"); addEvent(e1); addEvent(e2); order(); } catch (MalformedURLException e) { e.printStackTrace(); } } public void addEvent(Event e) { events.put(e.id, e); eventsList.add(e); } public void order() { Collections.sort(eventsList, defaultOrdering); } public Event getEvent(String id) { return events.get(id); } public boolean isOnRadar(Event e) { return radarIds.contains(e.id); } public boolean addToRadar(Event e) { if (radarIds.contains(e.id) || radar.size() >= MAX_RADAR_SELECTIONS) { return false; } radarIds.add(e.id); radar.add(e); ++e.radarCount; e.setOnRadar(true); return true; } public boolean removeFromRadar(Event e) { if (!radarIds.contains(e.id)) { return false; } radarIds.remove(e.id); // TODO: this is slow, improve radar.remove(e); --e.radarCount; e.setOnRadar(false); return true; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { // Technically all we need to do is write eventsList, and then reconstruct on the other side dest.writeTypedList(eventsList); } public static final Parcelable.Creator<RadarCommonController> CREATOR = new Parcelable.Creator<RadarCommonController>() { public RadarCommonController createFromParcel(Parcel in) { List<Event> events = new ArrayList<Event>(); in.readTypedList(events, Event.CREATOR); RadarCommonController c = new RadarCommonController(); c.eventsList.clear(); c.events.clear(); c.radar.clear(); c.radarIds.clear(); c.eventsList.addAll(events); for (Event e : events) { c.events.put(e.id, e); if (e.isOnRadar()) { c.radarIds.add(e.id); c.radar.add(e); } } return c; } public RadarCommonController[] newArray(int size) { return new RadarCommonController[size]; } }; }
false
true
public RadarCommonController() { try { Event e1 = new Event( "1", "Rager", "Get smashed, yeah!", "Skyroom NYC", new URL("http://thechive.files.wordpress.com/2009/04/demotivated-funny-karate.jpg"), 40.709208, -74.005864, 4, false, "11:00pm"); Event e2 = new Event( "2", "Ginyu Force Party", "Dress up as Ginyu Force and show off your Recoome Boom!", "230 Fifth", new URL("http://3.bp.blogspot.com/_NQz93lR8zIY/TSlxGIsV3vI/AAAAAAAAAOI/s0AoNlr18v8/s640/230_Fifth_v2_460x285.jpg"), 40.744253, -73.987991, 6, true, "8:00pm"); addEvent(e1); addEvent(e2); order(); } catch (MalformedURLException e) { e.printStackTrace(); } }
public RadarCommonController() { try { Event e1 = new Event( "1", "DJ Enuff", "DJ Enuff plays a rare live show at Skyroom NYC. Known primarily for his production work, Enuff is eager to return to the his first home, the club. ", "Skyroom NYC", new URL("http://th02.deviantart.net/fs51/PRE/f/2009/277/3/0/Reload_Flyer_by_vektorscksprojekt.jpg"), 40.709208, -74.005864, 4, false, "11:00pm"); Event e2 = new Event( "2", "Ok Go", "Ok Go plays Williamsburg Park for a free show! No strangers to the Brooklyn music scene, OK Go returns with special guests to deliver an electrifying show.", "Williamsburg Park", new URL("http://www.examiner.com/images/blog/EXID27067/images/ok_go(1).jpg"), 40.744253, -73.987991, 6, true, "8:00pm"); addEvent(e1); addEvent(e2); order(); } catch (MalformedURLException e) { e.printStackTrace(); } }
diff --git a/bundles/org.eclipse.orion.server.authentication.openid.core/src/org/eclipse/orion/server/openid/core/OpenIdHelper.java b/bundles/org.eclipse.orion.server.authentication.openid.core/src/org/eclipse/orion/server/openid/core/OpenIdHelper.java index 00054cd1..ce707f5c 100644 --- a/bundles/org.eclipse.orion.server.authentication.openid.core/src/org/eclipse/orion/server/openid/core/OpenIdHelper.java +++ b/bundles/org.eclipse.orion.server.authentication.openid.core/src/org/eclipse/orion/server/openid/core/OpenIdHelper.java @@ -1,400 +1,400 @@ /******************************************************************************* * Copyright (c) 2010 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.orion.server.openid.core; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.orion.server.core.LogHelper; import org.eclipse.orion.server.core.PreferenceHelper; import org.eclipse.orion.server.core.ServerConstants; import org.eclipse.orion.server.core.resources.Base64; import org.eclipse.orion.server.user.profile.IOrionUserProfileConstants; import org.eclipse.orion.server.user.profile.IOrionUserProfileNode; import org.eclipse.orion.server.user.profile.IOrionUserProfileService; import org.eclipse.orion.server.useradmin.IOrionCredentialsService; import org.eclipse.orion.server.useradmin.User; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.openid4java.consumer.ConsumerException; import org.openid4java.discovery.Identifier; import org.osgi.service.http.HttpContext; import org.osgi.service.http.HttpService; import org.osgi.service.http.NamespaceException; /** * Groups methods to handle session attributes for OpenID authentication. * */ public class OpenIdHelper { public static final String OPENID = "openid"; //$NON-NLS-1$ public static final String OP_RETURN = "op_return"; //$NON-NLS-1$ public static final String REDIRECT = "redirect"; //$NON-NLS-1$ static final String OPENID_IDENTIFIER = "openid_identifier"; //$NON-NLS-1$ static final String OPENID_DISC = "openid-disc"; //$NON-NLS-1$ private static IOrionCredentialsService userAdmin; private static List<OpendIdProviderDescription> defaultOpenids; private static IOrionUserProfileService userProfileService; private HttpService httpService; private static boolean allowAnonymousAccountCreation; static { //if there is no list of users authorised to create accounts, it means everyone can create accounts allowAnonymousAccountCreation = PreferenceHelper.getString(ServerConstants.CONFIG_AUTH_USER_CREATION, null) == null; //$NON-NLS-1$ } /** * Checks session attributes to retrieve authenticated user identifier. * * @param req * @return OpenID identifier of authenticated user of <code>null</code> if * user is not authenticated * @throws IOException */ public static String getAuthenticatedUser(HttpServletRequest req) throws IOException { HttpSession s = req.getSession(true); if (s.getAttribute("user") != null) { //$NON-NLS-1$ return (String) s.getAttribute("user"); //$NON-NLS-1$ } return null; } /** * Redirects to OpenId provider stored in <code>openid</code> parameter of * request. If user is to be redirected after login perform the redirect * site should be stored in <code>redirect<code> parameter. * * @param req * @param resp * @param consumer * {@link OpenidConsumer} used to login user by OpenId. The same * consumer should be used for * {@link #handleOpenIdReturnAndLogin(HttpServletRequest, HttpServletResponse, OpenidConsumer)} * . If <code>null</code> the new {@link OpenidConsumer} will be * created and returned * @return * @throws IOException */ public static OpenidConsumer redirectToOpenIdProvider(HttpServletRequest req, HttpServletResponse resp, OpenidConsumer consumer) throws IOException { String redirect = req.getParameter(REDIRECT); try { StringBuffer sb = getRequestServer(req); sb.append(req.getServletPath() + (req.getPathInfo() == null ? "" : req.getPathInfo())); //$NON-NLS-1$ sb.append("?").append(OP_RETURN).append("=true"); //$NON-NLS-1$ //$NON-NLS-2$ if (redirect != null && redirect.length() > 0) { sb.append("&").append(REDIRECT).append("="); //$NON-NLS-1$ //$NON-NLS-2$ sb.append(redirect); } consumer = new OpenidConsumer(sb.toString()); consumer.authRequest(req.getParameter(OPENID), req, resp); // redirection takes place in the authRequest method } catch (ConsumerException e) { writeOpenIdError(e.getMessage(), req, resp); LogHelper.log(new Status(IStatus.ERROR, Activator.PI_OPENID_CORE, "An error occured when creating OpenidConsumer", e)); } catch (CoreException e) { writeOpenIdError(e.getMessage(), req, resp); LogHelper.log(new Status(IStatus.ERROR, Activator.PI_OPENID_CORE, "An error occured when authenticing request", e)); } return consumer; } private static void writeOpenIdError(String error, HttpServletRequest req, HttpServletResponse resp) throws IOException { if (req.getParameter(REDIRECT) == null) { PrintWriter out = resp.getWriter(); out.println("<html><head></head>"); //$NON-NLS-1$ // TODO: send a message using // window.eclipseMessage.postImmediate(otherWindow, message) from // /org.eclipse.e4.webide/web/orion/message.js out.print("<body onload=\"window.opener.handleOpenIDResponse((window.location+'').split('?')[1],'"); out.print(error); out.println("');window.close();\">"); //$NON-NLS-1$ out.println("</body>"); //$NON-NLS-1$ out.println("</html>"); //$NON-NLS-1$ out.close(); return; } PrintWriter out = resp.getWriter(); out.println("<html><head></head>"); //$NON-NLS-1$ // TODO: send a message using // window.eclipseMessage.postImmediate(otherWindow, message) from // /org.eclipse.e4.webide/web/orion/message.js String url = req.getParameter(REDIRECT); url = url.replaceAll("/&error(\\=[^&]*)?(?=&|$)|^error(\\=[^&]*)?(&|$)/", ""); // remove // "error" // parameter out.print("<body onload=\"window.location.replace('"); out.print(url.toString()); if (url.contains("?")) { out.print("&error="); } else { out.print("?error="); } out.print(new String(Base64.encode(error.getBytes()))); out.println("');\">"); //$NON-NLS-1$ out.println("</body>"); //$NON-NLS-1$ out.println("</html>"); //$NON-NLS-1$ } private static boolean canAddUsers() { return allowAnonymousAccountCreation ? userAdmin.canCreateUsers() : false; } /** * Parses the response from OpenId provider. If <code>redirect</code> * parameter is not set closes the current window. * * @param req * @param resp * @param consumer * same {@link OpenidConsumer} as used in * {@link #redirectToOpenIdProvider(HttpServletRequest, HttpServletResponse, OpenidConsumer)} * @throws IOException */ public static void handleOpenIdReturnAndLogin(HttpServletRequest req, HttpServletResponse resp, OpenidConsumer consumer) throws IOException { String redirect = req.getParameter(REDIRECT); String op_return = req.getParameter(OP_RETURN); if (Boolean.parseBoolean(op_return) && consumer != null) { Identifier id = consumer.verifyResponse(req); if (id == null || id.getIdentifier() == null || id.getIdentifier().equals("")) { writeOpenIdError("Authentication response is not sufficient", req, resp); return; } Set<User> users = userAdmin.getUsersByProperty("openid", ".*\\Q" + id.getIdentifier() + "\\E.*", true); User user; if (users.size() > 0) { user = users.iterator().next(); } else if (canAddUsers()) { User newUser = new User(); newUser.setName(id.getIdentifier()); newUser.addProperty("openid", id.getIdentifier()); user = userAdmin.createUser(newUser); } else { - writeOpenIdError("Your authentication was successful but you are not authorized to access Orion", req, resp); + writeOpenIdError("Your authentication was successful but you are not authorized to access Orion. Contact administrator to create an Orion account.", req, resp); return; } req.getSession().setAttribute("user", user.getUid()); //$NON-NLS-1$ IOrionUserProfileNode userProfileNode = getUserProfileService().getUserProfileNode(user.getUid(), IOrionUserProfileConstants.GENERAL_PROFILE_PART); try { // try to store the login timestamp in the user profile userProfileNode.put(IOrionUserProfileConstants.LAST_LOGIN_TIMESTAMP, new Long(System.currentTimeMillis()).toString(), false); userProfileNode.flush(); } catch (CoreException e) { // just log that the login timestamp was not stored LogHelper.log(e); } if (redirect != null) { resp.sendRedirect(redirect); return; } return; } } public static void handleOpenIdReturn(HttpServletRequest req, HttpServletResponse resp, OpenidConsumer consumer) throws IOException { String op_return = req.getParameter(OP_RETURN); if (Boolean.parseBoolean(op_return) && consumer != null) { Identifier id = consumer.verifyResponse(req); if (id == null || id.getIdentifier() == null || id.getIdentifier().equals("")) { writeOpenIdError("Authentication response is not sufficient", req, resp); return; } PrintWriter out = resp.getWriter(); out.println("<html><head></head>"); //$NON-NLS-1$ // TODO: send a message using // window.eclipseMessage.postImmediate(otherWindow, message) from // /org.eclipse.e4.webide/web/js/message.js out.println("<body onload=\"window.opener.handleOpenIDResponse('" + id.getIdentifier() + "');window.close();\">"); //$NON-NLS-1$ //$NON-NLS-2$ out.println("</body>"); //$NON-NLS-1$ out.println("</html>"); //$NON-NLS-1$ out.close(); return; } } private static StringBuffer getRequestServer(HttpServletRequest req) { StringBuffer url = new StringBuffer(); String scheme = req.getScheme(); int port = req.getServerPort(); url.append(scheme); url.append("://"); //$NON-NLS-1$ url.append(req.getServerName()); if ((scheme.equals("http") && port != 80) //$NON-NLS-1$ || (scheme.equals("https") && port != 443)) { //$NON-NLS-1$ url.append(':'); url.append(req.getServerPort()); } return url; } /** * Destroys the session attributes that identify the user. * * @param req */ public static void performLogout(HttpServletRequest req) { HttpSession s = req.getSession(true); if (s.getAttribute("user") != null) { //$NON-NLS-1$ s.removeAttribute("user"); //$NON-NLS-1$ } } /** * Writes a response in JSON that contains user login. * * @param login * @param resp * @throws IOException */ public static void writeLoginResponse(String login, HttpServletResponse resp) throws IOException { resp.setStatus(HttpServletResponse.SC_OK); try { JSONObject array = new JSONObject(); array.put("login", login); //$NON-NLS-1$ resp.getWriter().print(array.toString()); } catch (JSONException e) { LogHelper.log(new Status(IStatus.ERROR, Activator.PI_OPENID_CORE, "An error occured when creating JSON object for logged in user", e)); } } public static String getAuthType() { return "OpenId"; //$NON-NLS-1$ } public static IOrionCredentialsService getDefaultUserAdmin() { return userAdmin; } public void setUserAdmin(IOrionCredentialsService userAdmin) { OpenIdHelper.userAdmin = userAdmin; } public void unsetUserAdmin(IOrionCredentialsService userAdmin) { if (userAdmin.equals(OpenIdHelper.userAdmin)) { OpenIdHelper.userAdmin = null; } } public static IOrionUserProfileService getUserProfileService() { return userProfileService; } public static void bindUserProfileService(IOrionUserProfileService _userProfileService) { userProfileService = _userProfileService; } public static void unbindUserProfileService(IOrionUserProfileService userProfileService) { userProfileService = null; } public void setHttpService(HttpService hs) { httpService = hs; HttpContext httpContext = new BundleEntryHttpContext(Activator.getBundleContext().getBundle()); try { httpService.registerResources("/openids", "/openids", httpContext); } catch (NamespaceException e) { LogHelper.log(new Status(IStatus.ERROR, Activator.PI_OPENID_CORE, 1, "A namespace error occured when registering servlets", e)); } } public void unsetHttpService(HttpService hs) { if (httpService != null) { httpService.unregister("/openids"); //$NON-NLS-1$ httpService = null; } } private static String getFileContents(String filename) throws IOException { StringBuilder sb = new StringBuilder(); InputStream is = Activator.getBundleContext().getBundle().getEntry(filename).openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = ""; //$NON-NLS-1$ while ((line = br.readLine()) != null) { sb.append(line).append('\n'); } return sb.toString(); } private static OpendIdProviderDescription getOpenidProviderFromJson(JSONObject json) throws JSONException { OpendIdProviderDescription provider = new OpendIdProviderDescription(); String url = json.getString("url"); provider.setAuthSite(url); try { String name = json.getString("name"); provider.setName(name); } catch (JSONException e) { // ignore, Name is not mandatory } try { String image = json.getString("image"); provider.setImage(image); } catch (JSONException e) { // ignore, Image is not mandatory } return provider; } public static List<OpendIdProviderDescription> getSupportedOpenIdProviders(String openids) throws JSONException { List<OpendIdProviderDescription> opendIdProviders = new ArrayList<OpendIdProviderDescription>(); JSONArray openidArray = new JSONArray(openids); for (int i = 0; i < openidArray.length(); i++) { JSONObject jsonProvider = openidArray.getJSONObject(i); try { opendIdProviders.add(getOpenidProviderFromJson(jsonProvider)); } catch (JSONException e) { LogHelper.log(new Status(IStatus.ERROR, Activator.PI_OPENID_CORE, "Cannot load OpenId provider, invalid entry " + jsonProvider + " Attribute \"ulr\" is mandatory", e)); } } return opendIdProviders; } public static List<OpendIdProviderDescription> getDefaultOpenIdProviders() { try { if (defaultOpenids == null) { defaultOpenids = getSupportedOpenIdProviders(getFileContents("/openids/DefaultOpenIdProviders.json")); //$NON-NLS-1$ } } catch (Exception e) { LogHelper.log(new Status(IStatus.ERROR, Activator.PI_OPENID_CORE, "Cannot load default openid list, JSON format expected", e)); //$NON-NLS-1$ return new ArrayList<OpendIdProviderDescription>(); } return defaultOpenids; } }
true
true
public static void handleOpenIdReturnAndLogin(HttpServletRequest req, HttpServletResponse resp, OpenidConsumer consumer) throws IOException { String redirect = req.getParameter(REDIRECT); String op_return = req.getParameter(OP_RETURN); if (Boolean.parseBoolean(op_return) && consumer != null) { Identifier id = consumer.verifyResponse(req); if (id == null || id.getIdentifier() == null || id.getIdentifier().equals("")) { writeOpenIdError("Authentication response is not sufficient", req, resp); return; } Set<User> users = userAdmin.getUsersByProperty("openid", ".*\\Q" + id.getIdentifier() + "\\E.*", true); User user; if (users.size() > 0) { user = users.iterator().next(); } else if (canAddUsers()) { User newUser = new User(); newUser.setName(id.getIdentifier()); newUser.addProperty("openid", id.getIdentifier()); user = userAdmin.createUser(newUser); } else { writeOpenIdError("Your authentication was successful but you are not authorized to access Orion", req, resp); return; } req.getSession().setAttribute("user", user.getUid()); //$NON-NLS-1$ IOrionUserProfileNode userProfileNode = getUserProfileService().getUserProfileNode(user.getUid(), IOrionUserProfileConstants.GENERAL_PROFILE_PART); try { // try to store the login timestamp in the user profile userProfileNode.put(IOrionUserProfileConstants.LAST_LOGIN_TIMESTAMP, new Long(System.currentTimeMillis()).toString(), false); userProfileNode.flush(); } catch (CoreException e) { // just log that the login timestamp was not stored LogHelper.log(e); } if (redirect != null) { resp.sendRedirect(redirect); return; } return; } }
public static void handleOpenIdReturnAndLogin(HttpServletRequest req, HttpServletResponse resp, OpenidConsumer consumer) throws IOException { String redirect = req.getParameter(REDIRECT); String op_return = req.getParameter(OP_RETURN); if (Boolean.parseBoolean(op_return) && consumer != null) { Identifier id = consumer.verifyResponse(req); if (id == null || id.getIdentifier() == null || id.getIdentifier().equals("")) { writeOpenIdError("Authentication response is not sufficient", req, resp); return; } Set<User> users = userAdmin.getUsersByProperty("openid", ".*\\Q" + id.getIdentifier() + "\\E.*", true); User user; if (users.size() > 0) { user = users.iterator().next(); } else if (canAddUsers()) { User newUser = new User(); newUser.setName(id.getIdentifier()); newUser.addProperty("openid", id.getIdentifier()); user = userAdmin.createUser(newUser); } else { writeOpenIdError("Your authentication was successful but you are not authorized to access Orion. Contact administrator to create an Orion account.", req, resp); return; } req.getSession().setAttribute("user", user.getUid()); //$NON-NLS-1$ IOrionUserProfileNode userProfileNode = getUserProfileService().getUserProfileNode(user.getUid(), IOrionUserProfileConstants.GENERAL_PROFILE_PART); try { // try to store the login timestamp in the user profile userProfileNode.put(IOrionUserProfileConstants.LAST_LOGIN_TIMESTAMP, new Long(System.currentTimeMillis()).toString(), false); userProfileNode.flush(); } catch (CoreException e) { // just log that the login timestamp was not stored LogHelper.log(e); } if (redirect != null) { resp.sendRedirect(redirect); return; } return; } }
diff --git a/rdb/src/main/java/org/apache/tuscany/das/rdb/graphbuilder/schema/ResultSetTypeMap.java b/rdb/src/main/java/org/apache/tuscany/das/rdb/graphbuilder/schema/ResultSetTypeMap.java index 3fcccf6..832cfea 100644 --- a/rdb/src/main/java/org/apache/tuscany/das/rdb/graphbuilder/schema/ResultSetTypeMap.java +++ b/rdb/src/main/java/org/apache/tuscany/das/rdb/graphbuilder/schema/ResultSetTypeMap.java @@ -1,133 +1,133 @@ /** * * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tuscany.das.rdb.graphbuilder.schema; import java.sql.Types; import org.apache.tuscany.sdo.SDOPackage; import commonj.sdo.Type; import commonj.sdo.helper.TypeHelper; /** */ public class ResultSetTypeMap { public static ResultSetTypeMap instance = new ResultSetTypeMap(); /** * Constructor for ResultSetTypeMap. */ protected ResultSetTypeMap() { // Empty Constructor } /** * These mappings taken primarily from "JDBC API and Tutorial and Reference" by * Fisher, Ellis and Bruce. * * @param type * @param isNullable * @return */ public Type getEDataType(int type, boolean isNullable) { TypeHelper helper = TypeHelper.INSTANCE; SDOPackage.eINSTANCE.eClass(); switch (type) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: return helper.getType("commonj.sdo", "String"); case Types.NUMERIC: case Types.DECIMAL: return helper.getType("commonj.sdo", "Decimal"); case Types.BIT: case Types.BOOLEAN: if (isNullable) return helper.getType("commonj.sdo", "Boolean"); else return helper.getType("commonj.sdo", "boolean"); case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: if (isNullable) { return helper.getType("commonj.sdo", "IntObject"); } else return helper.getType("commonj.sdo", "Int"); case Types.BIGINT: if (isNullable) return helper.getType("commonj.sdo", "Long"); else return helper.getType("commonj.sdo", "long"); case Types.REAL: if (isNullable) - return helper.getType("commonj.sdo", "Real"); + return helper.getType("commonj.sdo", "Float"); else - return helper.getType("commonj.sdo", "real"); + return helper.getType("commonj.sdo", "float"); case Types.FLOAT: case Types.DOUBLE: if (isNullable) return helper.getType("commonj.sdo", "Double"); else return helper.getType("commonj.sdo", "double"); case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: return helper.getType("commonj.sdo", "ByteArray"); case Types.DATE: case Types.TIME: case Types.TIMESTAMP: return helper.getType("commonj.sdo", "Date"); case Types.CLOB: return helper.getType("commonj.sdo", "Clob"); case Types.BLOB: return helper.getType("commonj.sdo", "Blob"); case Types.ARRAY: return helper.getType("commonj.sdo", "Array"); case Types.DISTINCT: case Types.STRUCT: case Types.REF: case Types.DATALINK: case Types.JAVA_OBJECT: return helper.getType("commonj.sdo", "Object"); default: return helper.getType("commonj.sdo", "Object"); } } public Type getType(int columnType, boolean b) { return getEDataType(columnType, b); } }
false
true
public Type getEDataType(int type, boolean isNullable) { TypeHelper helper = TypeHelper.INSTANCE; SDOPackage.eINSTANCE.eClass(); switch (type) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: return helper.getType("commonj.sdo", "String"); case Types.NUMERIC: case Types.DECIMAL: return helper.getType("commonj.sdo", "Decimal"); case Types.BIT: case Types.BOOLEAN: if (isNullable) return helper.getType("commonj.sdo", "Boolean"); else return helper.getType("commonj.sdo", "boolean"); case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: if (isNullable) { return helper.getType("commonj.sdo", "IntObject"); } else return helper.getType("commonj.sdo", "Int"); case Types.BIGINT: if (isNullable) return helper.getType("commonj.sdo", "Long"); else return helper.getType("commonj.sdo", "long"); case Types.REAL: if (isNullable) return helper.getType("commonj.sdo", "Real"); else return helper.getType("commonj.sdo", "real"); case Types.FLOAT: case Types.DOUBLE: if (isNullable) return helper.getType("commonj.sdo", "Double"); else return helper.getType("commonj.sdo", "double"); case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: return helper.getType("commonj.sdo", "ByteArray"); case Types.DATE: case Types.TIME: case Types.TIMESTAMP: return helper.getType("commonj.sdo", "Date"); case Types.CLOB: return helper.getType("commonj.sdo", "Clob"); case Types.BLOB: return helper.getType("commonj.sdo", "Blob"); case Types.ARRAY: return helper.getType("commonj.sdo", "Array"); case Types.DISTINCT: case Types.STRUCT: case Types.REF: case Types.DATALINK: case Types.JAVA_OBJECT: return helper.getType("commonj.sdo", "Object"); default: return helper.getType("commonj.sdo", "Object"); } }
public Type getEDataType(int type, boolean isNullable) { TypeHelper helper = TypeHelper.INSTANCE; SDOPackage.eINSTANCE.eClass(); switch (type) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: return helper.getType("commonj.sdo", "String"); case Types.NUMERIC: case Types.DECIMAL: return helper.getType("commonj.sdo", "Decimal"); case Types.BIT: case Types.BOOLEAN: if (isNullable) return helper.getType("commonj.sdo", "Boolean"); else return helper.getType("commonj.sdo", "boolean"); case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: if (isNullable) { return helper.getType("commonj.sdo", "IntObject"); } else return helper.getType("commonj.sdo", "Int"); case Types.BIGINT: if (isNullable) return helper.getType("commonj.sdo", "Long"); else return helper.getType("commonj.sdo", "long"); case Types.REAL: if (isNullable) return helper.getType("commonj.sdo", "Float"); else return helper.getType("commonj.sdo", "float"); case Types.FLOAT: case Types.DOUBLE: if (isNullable) return helper.getType("commonj.sdo", "Double"); else return helper.getType("commonj.sdo", "double"); case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: return helper.getType("commonj.sdo", "ByteArray"); case Types.DATE: case Types.TIME: case Types.TIMESTAMP: return helper.getType("commonj.sdo", "Date"); case Types.CLOB: return helper.getType("commonj.sdo", "Clob"); case Types.BLOB: return helper.getType("commonj.sdo", "Blob"); case Types.ARRAY: return helper.getType("commonj.sdo", "Array"); case Types.DISTINCT: case Types.STRUCT: case Types.REF: case Types.DATALINK: case Types.JAVA_OBJECT: return helper.getType("commonj.sdo", "Object"); default: return helper.getType("commonj.sdo", "Object"); } }
diff --git a/src/java/net/sf/picard/analysis/CollectInsertSizeMetrics.java b/src/java/net/sf/picard/analysis/CollectInsertSizeMetrics.java index 1026301a..cbf5d4f4 100644 --- a/src/java/net/sf/picard/analysis/CollectInsertSizeMetrics.java +++ b/src/java/net/sf/picard/analysis/CollectInsertSizeMetrics.java @@ -1,154 +1,155 @@ /* * The MIT License * * Copyright (c) 2012 The Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.sf.picard.analysis; import java.io.File; import java.util.*; import net.sf.picard.PicardException; import net.sf.picard.analysis.directed.InsertSizeMetricsCollector; import net.sf.picard.cmdline.Option; import net.sf.picard.cmdline.Usage; import net.sf.picard.io.IoUtil; import net.sf.picard.metrics.MetricsFile; import net.sf.picard.reference.ReferenceSequence; import net.sf.picard.util.CollectionUtil; import net.sf.picard.util.Log; import net.sf.picard.util.RExecutor; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMRecord; /** * Command line program to read non-duplicate insert sizes, create a histogram * and report distribution statistics. * * @author Doug Voet (dvoet at broadinstitute dot org) */ public class CollectInsertSizeMetrics extends SinglePassSamProgram { private static final Log log = Log.getInstance(CollectInsertSizeMetrics.class); private static final String HISTOGRAM_R_SCRIPT = "net/sf/picard/analysis/insertSizeHistogram.R"; // Usage and parameters @Usage public String USAGE = getStandardUsagePreamble() + "Reads a SAM or BAM file and writes a file containing metrics about " + "the statistical distribution of insert size (excluding duplicates) " + "and generates a histogram plot.\n"; @Option(shortName="H", doc="File to write insert size histogram chart to.") public File HISTOGRAM_FILE; @Option(doc="Generate mean, sd and plots by trimming the data down to MEDIAN + DEVIATIONS*MEDIAN_ABSOLUTE_DEVIATION. " + "This is done because insert size data typically includes enough anomalous values from chimeras and other " + "artifacts to make the mean and sd grossly misleading regarding the real distribution.") public double DEVIATIONS = 10; @Option(shortName="W", doc="Explicitly sets the histogram width, overriding automatic truncation of histogram tail. " + "Also, when calculating mean and standard deviation, only bins <= HISTOGRAM_WIDTH will be included.", optional=true) public Integer HISTOGRAM_WIDTH = null; @Option(shortName="M", doc="When generating the histogram, discard any data categories (out of FR, TANDEM, RF) that have fewer than this " + "percentage of overall reads. (Range: 0 to 1).") public float MINIMUM_PCT = 0.05f; @Option(shortName="LEVEL", doc="The level(s) at which to accumulate metrics. ") private Set<MetricAccumulationLevel> METRIC_ACCUMULATION_LEVEL = CollectionUtil.makeSet(MetricAccumulationLevel.ALL_READS); // Calculates InsertSizeMetrics for all METRIC_ACCUMULATION_LEVELs provided private InsertSizeMetricsCollector multiCollector; /** Required main method implementation. */ public static void main(final String[] argv) { new CollectInsertSizeMetrics().instanceMainWithExit(argv); } /** * Put any custom command-line validation in an override of this method. * clp is initialized at this point and can be used to print usage and access argv. * Any options set by command-line parser can be validated. * * @return null if command line is valid. If command line is invalid, returns an array of error message * to be written to the appropriate place. */ @Override protected String[] customCommandLineValidation() { if (MINIMUM_PCT < 0 || MINIMUM_PCT > 0.5) { return new String[]{"MINIMUM_PCT was set to " + MINIMUM_PCT + ". It must be between 0 and 0.5 so all data categories don't get discarded."}; } return super.customCommandLineValidation(); } @Override protected boolean usesNoRefReads() { return false; } @Override protected void setup(final SAMFileHeader header, final File samFile) { IoUtil.assertFileIsWritable(OUTPUT); IoUtil.assertFileIsWritable(HISTOGRAM_FILE); //Delegate actual collection to InsertSizeMetricCollector multiCollector = new InsertSizeMetricsCollector(METRIC_ACCUMULATION_LEVEL, header.getReadGroups(), MINIMUM_PCT, HISTOGRAM_WIDTH, DEVIATIONS); } @Override protected void acceptRead(final SAMRecord record, final ReferenceSequence ref) { multiCollector.acceptRecord(record, ref); } @Override protected void finish() { multiCollector.finish(); final MetricsFile<InsertSizeMetrics, Integer> file = getMetricsFile(); multiCollector.addAllLevelsToFile(file); if(file.getNumHistograms() == 0) { //can happen if user sets MINIMUM_PCT = 0.5, etc. log.warn("All data categories were discarded because they contained < " + MINIMUM_PCT + " of the total aligned paired data."); - log.warn("Total mapped pairs in all categories: " + ((InsertSizeMetricsCollector.PerUnitInsertSizeMetricsCollector) multiCollector.getAllReadsCollector()).getTotalInserts()); + final InsertSizeMetricsCollector.PerUnitInsertSizeMetricsCollector allReadsCollector = (InsertSizeMetricsCollector.PerUnitInsertSizeMetricsCollector) multiCollector.getAllReadsCollector(); + log.warn("Total mapped pairs in all categories: " + (allReadsCollector == null ? allReadsCollector : allReadsCollector.getTotalInserts())); } else { file.write(OUTPUT); final int rResult; if(HISTOGRAM_WIDTH == null) { rResult = RExecutor.executeFromClasspath( HISTOGRAM_R_SCRIPT, OUTPUT.getAbsolutePath(), HISTOGRAM_FILE.getAbsolutePath(), INPUT.getName()); } else { rResult = RExecutor.executeFromClasspath( HISTOGRAM_R_SCRIPT, OUTPUT.getAbsolutePath(), HISTOGRAM_FILE.getAbsolutePath(), INPUT.getName(), String.valueOf( HISTOGRAM_WIDTH ) ); //HISTOGRAM_WIDTH is passed because R automatically sets histogram width to the last //bin that has data, which may be less than HISTOGRAM_WIDTH and confuse the user. } if (rResult != 0) { throw new PicardException("R script " + HISTOGRAM_R_SCRIPT + " failed with return code " + rResult); } } } }
true
true
@Override protected void finish() { multiCollector.finish(); final MetricsFile<InsertSizeMetrics, Integer> file = getMetricsFile(); multiCollector.addAllLevelsToFile(file); if(file.getNumHistograms() == 0) { //can happen if user sets MINIMUM_PCT = 0.5, etc. log.warn("All data categories were discarded because they contained < " + MINIMUM_PCT + " of the total aligned paired data."); log.warn("Total mapped pairs in all categories: " + ((InsertSizeMetricsCollector.PerUnitInsertSizeMetricsCollector) multiCollector.getAllReadsCollector()).getTotalInserts()); } else { file.write(OUTPUT); final int rResult; if(HISTOGRAM_WIDTH == null) { rResult = RExecutor.executeFromClasspath( HISTOGRAM_R_SCRIPT, OUTPUT.getAbsolutePath(), HISTOGRAM_FILE.getAbsolutePath(), INPUT.getName()); } else { rResult = RExecutor.executeFromClasspath( HISTOGRAM_R_SCRIPT, OUTPUT.getAbsolutePath(), HISTOGRAM_FILE.getAbsolutePath(), INPUT.getName(), String.valueOf( HISTOGRAM_WIDTH ) ); //HISTOGRAM_WIDTH is passed because R automatically sets histogram width to the last //bin that has data, which may be less than HISTOGRAM_WIDTH and confuse the user. } if (rResult != 0) { throw new PicardException("R script " + HISTOGRAM_R_SCRIPT + " failed with return code " + rResult); } } }
@Override protected void finish() { multiCollector.finish(); final MetricsFile<InsertSizeMetrics, Integer> file = getMetricsFile(); multiCollector.addAllLevelsToFile(file); if(file.getNumHistograms() == 0) { //can happen if user sets MINIMUM_PCT = 0.5, etc. log.warn("All data categories were discarded because they contained < " + MINIMUM_PCT + " of the total aligned paired data."); final InsertSizeMetricsCollector.PerUnitInsertSizeMetricsCollector allReadsCollector = (InsertSizeMetricsCollector.PerUnitInsertSizeMetricsCollector) multiCollector.getAllReadsCollector(); log.warn("Total mapped pairs in all categories: " + (allReadsCollector == null ? allReadsCollector : allReadsCollector.getTotalInserts())); } else { file.write(OUTPUT); final int rResult; if(HISTOGRAM_WIDTH == null) { rResult = RExecutor.executeFromClasspath( HISTOGRAM_R_SCRIPT, OUTPUT.getAbsolutePath(), HISTOGRAM_FILE.getAbsolutePath(), INPUT.getName()); } else { rResult = RExecutor.executeFromClasspath( HISTOGRAM_R_SCRIPT, OUTPUT.getAbsolutePath(), HISTOGRAM_FILE.getAbsolutePath(), INPUT.getName(), String.valueOf( HISTOGRAM_WIDTH ) ); //HISTOGRAM_WIDTH is passed because R automatically sets histogram width to the last //bin that has data, which may be less than HISTOGRAM_WIDTH and confuse the user. } if (rResult != 0) { throw new PicardException("R script " + HISTOGRAM_R_SCRIPT + " failed with return code " + rResult); } } }
diff --git a/org/python/core/exceptions.java b/org/python/core/exceptions.java index 79ab093e..5bc1ee30 100644 --- a/org/python/core/exceptions.java +++ b/org/python/core/exceptions.java @@ -1,437 +1,438 @@ // Copyright 2001 Finn Bock package org.python.core; import java.lang.reflect.*; /** * The builtin exceptions module. The entire module should be imported * from python. None of the methods defined here should be called * from java. */ public class exceptions implements ClassDictInit { public static String __doc__ = "Python's standard exception class hierarchy.\n" + "\n" + "Here is a rundown of the class hierarchy. The classes found here are\n" + "inserted into both the exceptions module and the `built-in' module. "+ "It is\n" + "recommended that user defined class based exceptions be derived from the\n" + "`Exception' class, although this is currently not enforced.\n" + "\n" + "Exception\n" + " |\n" + " +-- SystemExit\n" + " +-- StandardError\n" + " | |\n" + " | +-- KeyboardInterrupt\n" + " | +-- ImportError\n" + " | +-- EnvironmentError\n" + " | | |\n" + " | | +-- IOError\n" + " | | +-- OSError\n" + " | | |\n" + " | | +-- WindowsError\n" + " | |\n" + " | +-- EOFError\n" + " | +-- RuntimeError\n" + " | | |\n" + " | | +-- NotImplementedError\n" + " | |\n" + " | +-- NameError\n" + " | | |\n" + " | | +-- UnboundLocalError\n" + " | |\n" + " | +-- AttributeError\n" + " | +-- SyntaxError\n" + " | | |\n" + " | | +-- IndentationError\n" + " | | |\n" + " | | +-- TabError\n" + " | |\n" + " | +-- TypeError\n" + " | +-- AssertionError\n" + " | +-- LookupError\n" + " | | |\n" + " | | +-- IndexError\n" + " | | +-- KeyError\n" + " | |\n" + " | +-- ArithmeticError\n" + " | | |\n" + " | | +-- OverflowError\n" + " | | +-- ZeroDivisionError\n" + " | | +-- FloatingPointError\n" + " | |\n" + " | +-- ValueError\n" + " | | |\n" + " | | +-- UnicodeError\n" + " | |\n" + " | +-- SystemError\n" + " | +-- MemoryError\n" + " |\n" + " +---Warning\n" + " |\n" + " +-- UserWarning\n" + " +-- DeprecationWarning\n" + " +-- SyntaxWarning\n" + " +-- RuntimeWarning"; private exceptions() { ; } /** <i>Internal use only. Do not call this method explicit.</i> */ public static void classDictInit(PyObject dict) { dict.invoke("clear"); dict.__setitem__("__name__", new PyString("exceptions")); dict.__setitem__("__doc__", new PyString(__doc__)); ThreadState ts = Py.getThreadState(); if (ts.systemState == null) { ts.systemState = Py.defaultSystemState; } // Push frame PyFrame frame = new PyFrame(null, new PyStringMap()); frame.f_back = ts.frame; if (frame.f_builtins == null) { if (frame.f_back != null) { frame.f_builtins = frame.f_back.f_builtins; } else { frame.f_builtins = ts.systemState.builtins; } } ts.frame = frame; buildClass(dict, "Exception", null, "Exception", "Proposed base class for all exceptions."); buildClass(dict, "StandardError", "Exception", "empty__init__", "Base class for all standard Python exceptions."); buildClass(dict, "SyntaxError", "StandardError", "SyntaxError", "Invalid syntax"); buildClass(dict, "IndentationError", "SyntaxError", "empty__init__", "Improper indentation"); buildClass(dict, "TabError", "IndentationError", "empty__init__", "Improper mixture of spaces and tabs."); buildClass(dict, "EnvironmentError", "StandardError", "EnvironmentError", "Base class for I/O related errors."); buildClass(dict, "IOError", "EnvironmentError", "empty__init__", "I/O operation failed."); buildClass(dict, "OSError", "EnvironmentError", "empty__init__", "OS system call failed."); buildClass(dict, "RuntimeError", "StandardError", "empty__init__", "Unspecified run-time error."); buildClass(dict, "NotImplementedError", "RuntimeError", "empty__init__", "Method or function hasn't been implemented yet."); buildClass(dict, "SystemError", "StandardError", "empty__init__", "Internal error in the Python interpreter.\n\n" + "Please report this to the Python maintainer, "+ "along with the traceback,\n" + "the Python version, and the hardware/OS "+ "platform and version."); buildClass(dict, "EOFError", "StandardError", "empty__init__", "Read beyond end of file."); buildClass(dict, "ImportError", "StandardError", "empty__init__", "Import can't find module, or can't find name in module."); buildClass(dict, "TypeError", "StandardError", "empty__init__", "Inappropriate argument type."); buildClass(dict, "ValueError", "StandardError", "empty__init__", "Inappropriate argument value (of correct type)."); buildClass(dict, "UnicodeError", "ValueError", "empty__init__", "Unicode related error."); buildClass(dict, "KeyboardInterrupt", "StandardError", "empty__init__", "Program interrupted by user."); buildClass(dict, "AssertionError", "StandardError", "empty__init__", "Assertion failed."); buildClass(dict, "ArithmeticError", "StandardError", "empty__init__", "Base class for arithmetic errors."); buildClass(dict, "OverflowError", "ArithmeticError", "empty__init__", "Result too large to be represented."); buildClass(dict, "FloatingPointError", "ArithmeticError", "empty__init__", "Floating point operation failed."); buildClass(dict, "ZeroDivisionError", "ArithmeticError", "empty__init__", "Second argument to a division or modulo operation "+ "was zero."); buildClass(dict, "LookupError", "StandardError", "empty__init__", "Base class for lookup errors."); buildClass(dict, "IndexError", "LookupError", "empty__init__", "Sequence index out of range."); buildClass(dict, "KeyError", "LookupError", "empty__init__", "Mapping key not found."); buildClass(dict, "AttributeError", "StandardError", "empty__init__", "Attribute not found."); buildClass(dict, "NameError", "StandardError", "empty__init__", "Name not found globally."); buildClass(dict, "UnboundLocalError", "NameError", "empty__init__", "Local name referenced but not bound to a value."); buildClass(dict, "MemoryError", "StandardError", "empty__init__", "Out of memory."); buildClass(dict, "SystemExit", "Exception", "SystemExit", "Request to exit from the interpreter."); buildClass(dict, "Warning", "Exception", "empty__init__", "Base class for warning categories."); buildClass(dict, "UserWarning", "Warning", "empty__init__", "Base class for warnings generated by user code."); buildClass(dict, "DeprecationWarning", "Warning", "empty__init__", "Base class for warnings about deprecated features."); buildClass(dict, "SyntaxWarning", "Warning", "empty__init__", "Base class for warnings about dubious syntax."); buildClass(dict, "RuntimeWarning", "Warning", "empty__init__", "Base class for warnings about dubious runtime behavior."); + ts.frame = ts.frame.f_back; } // An empty __init__ method public static PyObject empty__init__(PyObject[] arg, String[] kws) { PyObject dict = new PyStringMap(); dict.__setitem__("__module__", new PyString("exceptions")); return dict; } public static PyObject Exception(PyObject[] arg, String[] kws) { PyObject dict = empty__init__(arg, kws); dict.__setitem__("__init__", getJavaFunc("Exception__init__")); dict.__setitem__("__str__", getJavaFunc("Exception__str__")); dict.__setitem__("__getitem__", getJavaFunc("Exception__getitem__")); return dict; } public static void Exception__init__(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("__init__", arg, kws, "self", "args"); PyObject self = ap.getPyObject(0); PyObject args = ap.getList(1); self.__setattr__("args", args); } public static PyString Exception__str__(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("__str__", arg, kws, "self"); PyObject self = ap.getPyObject(0); PyObject args = self.__getattr__("args"); if (!args.__nonzero__()) return new PyString(""); else if (args.__len__() == 1) return args.__getitem__(0).__str__(); else return args.__str__(); } public static PyObject Exception__getitem__(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("__getitem__", arg, kws, "self", "i"); PyObject self = ap.getPyObject(0); PyObject i = ap.getPyObject(1); return self.__getattr__("args").__getitem__(i); } public static PyObject SyntaxError(PyObject[] arg, String[] kws) { PyObject __dict__ = empty__init__(arg, kws); __dict__.__setitem__("filename", Py.None); __dict__.__setitem__("lineno", Py.None); __dict__.__setitem__("offset", Py.None); __dict__.__setitem__("text", Py.None); __dict__.__setitem__("msg", new PyString("")); __dict__.__setitem__("__init__", getJavaFunc("SyntaxError__init__")); __dict__.__setitem__("__str__", getJavaFunc("SyntaxError__str__")); return __dict__; } public static void SyntaxError__init__(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("__init__", arg, kws, "self", "args"); PyObject self = ap.getPyObject(0); PyObject args = ap.getList(1); self.__setattr__("args", args); if (args.__len__() >= 1) self.__setattr__("msg", args.__getitem__(0)); if (args.__len__() == 2) { PyObject info = args.__getitem__(1); try { PyObject[] tmp = Py.unpackSequence(info, 4); self.__setattr__("filename", tmp[0]); self.__setattr__("lineno", tmp[1]); self.__setattr__("offset", tmp[2]); self.__setattr__("text", tmp[3]); } catch (PyException exc) { ; } } } public static PyString SyntaxError__str__(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("__init__", arg, kws, "self", "args"); PyObject self = ap.getPyObject(0); PyString str = self.__getattr__("msg").__str__(); PyObject filename = basename(self.__findattr__("filename")); PyObject lineno = self.__findattr__("lineno"); if (filename instanceof PyString && lineno instanceof PyInteger) return new PyString(str + " (" + filename + ", line " + lineno + ")"); else if (filename instanceof PyString) return new PyString(str + " (" + filename + ")"); else if (lineno instanceof PyInteger) return new PyString(str + " (line " + lineno + ")"); return str; } private static PyObject basename(PyObject filename) { if (filename instanceof PyString) { int i = ((PyString) filename).rfind(java.io.File.separator); if (i >= 0) return filename.__getslice__( new PyInteger(i+1), new PyInteger(Integer.MAX_VALUE)); } return filename; } public static PyObject EnvironmentError(PyObject[] arg, String[] kws) { PyObject dict = empty__init__(arg, kws); dict.__setitem__("__init__", getJavaFunc("EnvironmentError__init__")); dict.__setitem__("__str__", getJavaFunc("EnvironmentError__str__")); return dict; } public static void EnvironmentError__init__(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("__init__", arg, kws, "self", "args"); PyObject self = ap.getPyObject(0); PyObject args = ap.getList(1); self.__setattr__("args", args); self.__setattr__("errno", Py.None); self.__setattr__("strerror", Py.None); self.__setattr__("filename", Py.None); if (args.__len__() == 3) { // open() errors give third argument which is the filename. BUT, // so common in-place unpacking doesn't break, e.g.: // // except IOError, (errno, strerror): // // we hack args so that it only contains two items. This also // means we need our own __str__() which prints out the filename // when it was supplied. PyObject[] tmp = Py.unpackSequence(args, 3); self.__setattr__("errno", tmp[0]); self.__setattr__("strerror", tmp[1]); self.__setattr__("filename", tmp[2]); self.__setattr__("args", args.__getslice__(Py.Zero, Py.newInteger(2), Py.One)); } if (args.__len__() == 2) { // common case: PyErr_SetFromErrno() PyObject[] tmp = Py.unpackSequence(args, 2); self.__setattr__("errno", tmp[0]); self.__setattr__("strerror", tmp[1]); } } public static PyString EnvironmentError__str__(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("__init__", arg, kws, "self"); PyObject self = ap.getPyObject(0); if (self.__getattr__("filename") != Py.None) { return Py.newString("[Errno %s] %s: %s").__mod__( new PyTuple(new PyObject[] { self.__getattr__("errno"), self.__getattr__("strerror"), self.__getattr__("filename")})).__str__(); } else if (self.__getattr__("errno").__nonzero__() && self.__getattr__("strerror").__nonzero__()) { return Py.newString("[Errno %s] %s").__mod__( new PyTuple(new PyObject[] { self.__getattr__("errno"), self.__getattr__("strerror")})).__str__(); } else { return Exception__str__(arg, kws); } } public static PyObject SystemExit(PyObject[] arg, String[] kws) { PyObject dict = empty__init__(arg, kws); dict.__setitem__("__init__", getJavaFunc("SystemExit__init__")); return dict; } public static void SystemExit__init__(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("__init__", arg, kws, "self", "args"); PyObject self = ap.getPyObject(0); PyObject args = ap.getList(1); self.__setattr__("args", args); if (args.__len__() == 0) self.__setattr__("code", Py.None); else if (args.__len__() == 1) self.__setattr__("code", args.__getitem__(0)); else self.__setattr__("code", args); } private static PyObject getJavaFunc(String name) { return Py.newJavaFunc(exceptions.class, name); } private static PyObject buildClass(PyObject dict, String classname, String superclass, String classCodeName, String doc) { PyObject[] sclass = Py.EmptyObjects; if (superclass != null) sclass = new PyObject[] { dict.__getitem__(new PyString(superclass)) }; PyObject cls = Py.makeClass( classname, sclass, Py.newJavaCode(exceptions.class, classCodeName), new PyString(doc)); dict.__setitem__(classname, cls); return cls; } }
true
true
public static void classDictInit(PyObject dict) { dict.invoke("clear"); dict.__setitem__("__name__", new PyString("exceptions")); dict.__setitem__("__doc__", new PyString(__doc__)); ThreadState ts = Py.getThreadState(); if (ts.systemState == null) { ts.systemState = Py.defaultSystemState; } // Push frame PyFrame frame = new PyFrame(null, new PyStringMap()); frame.f_back = ts.frame; if (frame.f_builtins == null) { if (frame.f_back != null) { frame.f_builtins = frame.f_back.f_builtins; } else { frame.f_builtins = ts.systemState.builtins; } } ts.frame = frame; buildClass(dict, "Exception", null, "Exception", "Proposed base class for all exceptions."); buildClass(dict, "StandardError", "Exception", "empty__init__", "Base class for all standard Python exceptions."); buildClass(dict, "SyntaxError", "StandardError", "SyntaxError", "Invalid syntax"); buildClass(dict, "IndentationError", "SyntaxError", "empty__init__", "Improper indentation"); buildClass(dict, "TabError", "IndentationError", "empty__init__", "Improper mixture of spaces and tabs."); buildClass(dict, "EnvironmentError", "StandardError", "EnvironmentError", "Base class for I/O related errors."); buildClass(dict, "IOError", "EnvironmentError", "empty__init__", "I/O operation failed."); buildClass(dict, "OSError", "EnvironmentError", "empty__init__", "OS system call failed."); buildClass(dict, "RuntimeError", "StandardError", "empty__init__", "Unspecified run-time error."); buildClass(dict, "NotImplementedError", "RuntimeError", "empty__init__", "Method or function hasn't been implemented yet."); buildClass(dict, "SystemError", "StandardError", "empty__init__", "Internal error in the Python interpreter.\n\n" + "Please report this to the Python maintainer, "+ "along with the traceback,\n" + "the Python version, and the hardware/OS "+ "platform and version."); buildClass(dict, "EOFError", "StandardError", "empty__init__", "Read beyond end of file."); buildClass(dict, "ImportError", "StandardError", "empty__init__", "Import can't find module, or can't find name in module."); buildClass(dict, "TypeError", "StandardError", "empty__init__", "Inappropriate argument type."); buildClass(dict, "ValueError", "StandardError", "empty__init__", "Inappropriate argument value (of correct type)."); buildClass(dict, "UnicodeError", "ValueError", "empty__init__", "Unicode related error."); buildClass(dict, "KeyboardInterrupt", "StandardError", "empty__init__", "Program interrupted by user."); buildClass(dict, "AssertionError", "StandardError", "empty__init__", "Assertion failed."); buildClass(dict, "ArithmeticError", "StandardError", "empty__init__", "Base class for arithmetic errors."); buildClass(dict, "OverflowError", "ArithmeticError", "empty__init__", "Result too large to be represented."); buildClass(dict, "FloatingPointError", "ArithmeticError", "empty__init__", "Floating point operation failed."); buildClass(dict, "ZeroDivisionError", "ArithmeticError", "empty__init__", "Second argument to a division or modulo operation "+ "was zero."); buildClass(dict, "LookupError", "StandardError", "empty__init__", "Base class for lookup errors."); buildClass(dict, "IndexError", "LookupError", "empty__init__", "Sequence index out of range."); buildClass(dict, "KeyError", "LookupError", "empty__init__", "Mapping key not found."); buildClass(dict, "AttributeError", "StandardError", "empty__init__", "Attribute not found."); buildClass(dict, "NameError", "StandardError", "empty__init__", "Name not found globally."); buildClass(dict, "UnboundLocalError", "NameError", "empty__init__", "Local name referenced but not bound to a value."); buildClass(dict, "MemoryError", "StandardError", "empty__init__", "Out of memory."); buildClass(dict, "SystemExit", "Exception", "SystemExit", "Request to exit from the interpreter."); buildClass(dict, "Warning", "Exception", "empty__init__", "Base class for warning categories."); buildClass(dict, "UserWarning", "Warning", "empty__init__", "Base class for warnings generated by user code."); buildClass(dict, "DeprecationWarning", "Warning", "empty__init__", "Base class for warnings about deprecated features."); buildClass(dict, "SyntaxWarning", "Warning", "empty__init__", "Base class for warnings about dubious syntax."); buildClass(dict, "RuntimeWarning", "Warning", "empty__init__", "Base class for warnings about dubious runtime behavior."); }
public static void classDictInit(PyObject dict) { dict.invoke("clear"); dict.__setitem__("__name__", new PyString("exceptions")); dict.__setitem__("__doc__", new PyString(__doc__)); ThreadState ts = Py.getThreadState(); if (ts.systemState == null) { ts.systemState = Py.defaultSystemState; } // Push frame PyFrame frame = new PyFrame(null, new PyStringMap()); frame.f_back = ts.frame; if (frame.f_builtins == null) { if (frame.f_back != null) { frame.f_builtins = frame.f_back.f_builtins; } else { frame.f_builtins = ts.systemState.builtins; } } ts.frame = frame; buildClass(dict, "Exception", null, "Exception", "Proposed base class for all exceptions."); buildClass(dict, "StandardError", "Exception", "empty__init__", "Base class for all standard Python exceptions."); buildClass(dict, "SyntaxError", "StandardError", "SyntaxError", "Invalid syntax"); buildClass(dict, "IndentationError", "SyntaxError", "empty__init__", "Improper indentation"); buildClass(dict, "TabError", "IndentationError", "empty__init__", "Improper mixture of spaces and tabs."); buildClass(dict, "EnvironmentError", "StandardError", "EnvironmentError", "Base class for I/O related errors."); buildClass(dict, "IOError", "EnvironmentError", "empty__init__", "I/O operation failed."); buildClass(dict, "OSError", "EnvironmentError", "empty__init__", "OS system call failed."); buildClass(dict, "RuntimeError", "StandardError", "empty__init__", "Unspecified run-time error."); buildClass(dict, "NotImplementedError", "RuntimeError", "empty__init__", "Method or function hasn't been implemented yet."); buildClass(dict, "SystemError", "StandardError", "empty__init__", "Internal error in the Python interpreter.\n\n" + "Please report this to the Python maintainer, "+ "along with the traceback,\n" + "the Python version, and the hardware/OS "+ "platform and version."); buildClass(dict, "EOFError", "StandardError", "empty__init__", "Read beyond end of file."); buildClass(dict, "ImportError", "StandardError", "empty__init__", "Import can't find module, or can't find name in module."); buildClass(dict, "TypeError", "StandardError", "empty__init__", "Inappropriate argument type."); buildClass(dict, "ValueError", "StandardError", "empty__init__", "Inappropriate argument value (of correct type)."); buildClass(dict, "UnicodeError", "ValueError", "empty__init__", "Unicode related error."); buildClass(dict, "KeyboardInterrupt", "StandardError", "empty__init__", "Program interrupted by user."); buildClass(dict, "AssertionError", "StandardError", "empty__init__", "Assertion failed."); buildClass(dict, "ArithmeticError", "StandardError", "empty__init__", "Base class for arithmetic errors."); buildClass(dict, "OverflowError", "ArithmeticError", "empty__init__", "Result too large to be represented."); buildClass(dict, "FloatingPointError", "ArithmeticError", "empty__init__", "Floating point operation failed."); buildClass(dict, "ZeroDivisionError", "ArithmeticError", "empty__init__", "Second argument to a division or modulo operation "+ "was zero."); buildClass(dict, "LookupError", "StandardError", "empty__init__", "Base class for lookup errors."); buildClass(dict, "IndexError", "LookupError", "empty__init__", "Sequence index out of range."); buildClass(dict, "KeyError", "LookupError", "empty__init__", "Mapping key not found."); buildClass(dict, "AttributeError", "StandardError", "empty__init__", "Attribute not found."); buildClass(dict, "NameError", "StandardError", "empty__init__", "Name not found globally."); buildClass(dict, "UnboundLocalError", "NameError", "empty__init__", "Local name referenced but not bound to a value."); buildClass(dict, "MemoryError", "StandardError", "empty__init__", "Out of memory."); buildClass(dict, "SystemExit", "Exception", "SystemExit", "Request to exit from the interpreter."); buildClass(dict, "Warning", "Exception", "empty__init__", "Base class for warning categories."); buildClass(dict, "UserWarning", "Warning", "empty__init__", "Base class for warnings generated by user code."); buildClass(dict, "DeprecationWarning", "Warning", "empty__init__", "Base class for warnings about deprecated features."); buildClass(dict, "SyntaxWarning", "Warning", "empty__init__", "Base class for warnings about dubious syntax."); buildClass(dict, "RuntimeWarning", "Warning", "empty__init__", "Base class for warnings about dubious runtime behavior."); ts.frame = ts.frame.f_back; }
diff --git a/src/org/apache/xalan/xsltc/dom/MultiDOM.java b/src/org/apache/xalan/xsltc/dom/MultiDOM.java index 5de475f3..95bfa77e 100644 --- a/src/org/apache/xalan/xsltc/dom/MultiDOM.java +++ b/src/org/apache/xalan/xsltc/dom/MultiDOM.java @@ -1,465 +1,466 @@ /* * @(#)$Id$ * * The Apache Software License, Version 1.1 * * * Copyright (c) 2001 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) 2001, Sun * Microsystems., http://www.sun.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * * @author Jacek Ambroziak * @author Morten Jorgensen * @author Erwin Bolwidt <[email protected]> * */ package org.apache.xalan.xsltc.dom; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.apache.xalan.xsltc.DOM; import org.apache.xalan.xsltc.StripFilter; import org.apache.xalan.xsltc.NodeIterator; import org.apache.xalan.xsltc.TransletOutputHandler; import org.apache.xalan.xsltc.TransletException; import org.apache.xalan.xsltc.runtime.Hashtable; import org.apache.xalan.xsltc.runtime.BasisLibrary; public final class MultiDOM implements DOM { private static final int NO_TYPE = DOM.FIRST_TYPE - 2; private static final int INITIAL_SIZE = 4; private static final int CLR = 0x00FFFFFF; private static final int SET = 0xFF000000; private DOM[] _adapters; private int _free; private int _size; private Hashtable _documents = new Hashtable(); private final class AxisIterator implements NodeIterator { private final int _axis; private final int _type; private int _mask; private NodeIterator _source = null; public AxisIterator(final int axis, final int type) { _axis = axis; _type = type; } public int next() { if (_source == null) return(END); if (_mask == 0) return _source.next(); final int node = _source.next(); return node != END ? (node | _mask) : END; } public void setRestartable(boolean flag) { _source.setRestartable(flag); } public NodeIterator setStartNode(final int node) { - _mask = node & SET; - int dom = node >>> 24; + final int dom = node >>> 24; + final int mask = node & SET; - // Get a new source for the first time only - if (_source == null) { + // Get a new source first time and when mask changes + if (_source == null || _mask != mask) { if (_type == NO_TYPE) { _source = _adapters[dom].getAxisIterator(_axis); } else if (_axis == Axis.CHILD && _type != ELEMENT) { _source = _adapters[dom].getTypedChildren(_type); } else { _source = _adapters[dom].getTypedAxisIterator(_axis, _type); } } + _mask = mask; _source.setStartNode(node & CLR); return this; } public NodeIterator reset() { if (_source != null) _source.reset(); return this; } public int getLast() { return _source.getLast(); } public int getPosition() { return _source.getPosition(); } public boolean isReverse() { return (_source == null) ? false : _source.isReverse(); } public void setMark() { _source.setMark(); } public void gotoMark() { _source.gotoMark(); } public NodeIterator cloneIterator() { final AxisIterator clone = new AxisIterator(_axis, _type); clone._source = _source.cloneIterator(); clone._mask = _mask; return clone; } } // end of AxisIterator /************************************************************** * This is a specialised iterator for predicates comparing node or * attribute values to variable or parameter values. */ private final class NodeValueIterator extends NodeIteratorBase { private NodeIterator _source; private String _value; private boolean _op; private final boolean _isReverse; private int _returnType = RETURN_PARENT; public NodeValueIterator(NodeIterator source, int returnType, String value, boolean op) { _source = source; _returnType = returnType; _value = value; _op = op; _isReverse = source.isReverse(); } public boolean isReverse() { return _isReverse; } public NodeIterator cloneIterator() { try { NodeValueIterator clone = (NodeValueIterator)super.clone(); clone._source = _source.cloneIterator(); clone.setRestartable(false); return clone.reset(); } catch (CloneNotSupportedException e) { BasisLibrary.runTimeError(BasisLibrary.ITERATOR_CLONE_ERR, e.toString()); return null; } } public void setRestartable(boolean isRestartable) { _isRestartable = isRestartable; _source.setRestartable(isRestartable); } public NodeIterator reset() { _source.reset(); return resetPosition(); } public int next() { int node; while ((node = _source.next()) != END) { String val = getNodeValue(node); if (_value.equals(val) == _op) { if (_returnType == RETURN_CURRENT) return returnNode(node); else return returnNode(getParent(node)); } } return END; } public NodeIterator setStartNode(int node) { if (_isRestartable) { _source.setStartNode(_startNode = node); return resetPosition(); } return this; } public void setMark() { _source.setMark(); } public void gotoMark() { _source.gotoMark(); } } public MultiDOM(DOM main) { _size = INITIAL_SIZE; _free = 1; _adapters = new DOM[INITIAL_SIZE]; _adapters[0] = main; } public int nextMask() { return(_free << 24); } public void setupMapping(String[] names, String[] namespaces) { // This method only has a function in DOM adapters } public int addDOMAdapter(DOMAdapter dom) { // Add the DOM adapter to the array of DOMs final int domNo = _free++; if (domNo == _size) { final DOMAdapter[] newArray = new DOMAdapter[_size *= 2]; System.arraycopy(_adapters, 0, newArray, 0, domNo); _adapters = newArray; } _adapters[domNo] = dom; // Store reference to document (URI) in hashtable String uri = dom.getDocumentURI(0); _documents.put(uri, new Integer(domNo)); // Store mask in DOMAdapter dom.setMultiDOMMask(domNo << 24); return (domNo << 24); } public int getDocumentMask(String uri) { Integer domIdx = (Integer)_documents.get(uri); if (domIdx == null) return(-1); else return((domIdx.intValue() << 24)); } /** * Returns singleton iterator containg the document root */ public NodeIterator getIterator() { // main source document @ 0 return _adapters[0].getIterator(); } public String getStringValue() { return _adapters[0].getStringValue(); } public String getTreeString() { return _adapters[0].getTreeString(); } public NodeIterator getChildren(final int node) { return (node & SET) == 0 ? _adapters[0].getChildren(node) : getAxisIterator(Axis.CHILD).setStartNode(node); } public NodeIterator getTypedChildren(final int type) { return new AxisIterator(Axis.CHILD, type); } public NodeIterator getAxisIterator(final int axis) { return new AxisIterator(axis, NO_TYPE); } public NodeIterator getTypedAxisIterator(final int axis, final int type) { return new AxisIterator(axis, type); } public NodeIterator getNthDescendant(int node, int n, boolean includeself) { return _adapters[node>>>24].getNthDescendant(node & CLR,n,includeself); } public NodeIterator getNodeValueIterator(NodeIterator iterator, int type, String value, boolean op) { return(new NodeValueIterator(iterator, type, value, op)); } public NodeIterator getNamespaceAxisIterator(final int axis, final int ns) { NodeIterator iterator = _adapters[0].getNamespaceAxisIterator(axis,ns); return(iterator); } public NodeIterator orderNodes(NodeIterator source, int node) { return _adapters[node>>>24].orderNodes(source, node & CLR); } public int getType(final int node) { return _adapters[node>>>24].getType(node & CLR); } public int getNamespaceType(final int node) { return _adapters[node>>>24].getNamespaceType(node & CLR); } public int getParent(final int node) { return _adapters[node>>>24].getParent(node & CLR) | node&SET; } public int getTypedPosition(int type, int node) { return _adapters[node>>>24].getTypedPosition(type, node&CLR); } public int getTypedLast(int type, int node) { return _adapters[node>>>24].getTypedLast(type, node&CLR); } public int getAttributeNode(final int type, final int el) { return _adapters[el>>>24].getAttributeNode(type, el&CLR) | el&SET; } public String getNodeName(final int node) { return _adapters[node>>>24].getNodeName(node & CLR); } public String getNamespaceName(final int node) { return _adapters[node>>>24].getNamespaceName(node & CLR); } public String getNodeValue(final int node) { return _adapters[node>>>24].getNodeValue(node & CLR); } public void copy(final int node, TransletOutputHandler handler) throws TransletException { _adapters[node>>>24].copy(node & CLR, handler); } public void copy(NodeIterator nodes, TransletOutputHandler handler) throws TransletException { int node; while ((node = nodes.next()) != DOM.NULL) { _adapters[node>>>24].copy(node & CLR, handler); } } public String shallowCopy(final int node, TransletOutputHandler handler) throws TransletException { return _adapters[node>>>24].shallowCopy(node & CLR, handler); } public boolean lessThan(final int node1, final int node2) { final int dom1 = node1>>>24; final int dom2 = node2>>>24; return dom1 == dom2 ? _adapters[dom1].lessThan(node1 & CLR, node2 & CLR) : dom1 < dom2; } public void characters(final int textNode, TransletOutputHandler handler) throws TransletException { _adapters[textNode>>>24].characters(textNode & CLR, handler); } public void setFilter(StripFilter filter) { for (int dom=0; dom<_free; dom++) { _adapters[dom].setFilter(filter); } } public Node makeNode(int index) { return _adapters[index>>>24].makeNode(index & CLR); } public Node makeNode(NodeIterator iter) { // TODO: gather nodes from all DOMs ? return _adapters[0].makeNode(iter); } public NodeList makeNodeList(int index) { return _adapters[index>>>24].makeNodeList(index & CLR); } public NodeList makeNodeList(NodeIterator iter) { // TODO: gather nodes from all DOMs ? return _adapters[0].makeNodeList(iter); } public String getLanguage(int node) { return _adapters[node>>>24].getLanguage(node & CLR); } public int getSize() { int size = 0; for (int i=0; i<_size; i++) size += _adapters[i].getSize(); return(size); } public String getDocumentURI(int node) { return _adapters[node>>>24].getDocumentURI(0); } public boolean isElement(final int node) { return(_adapters[node>>>24].isElement(node & CLR)); } public boolean isAttribute(final int node) { return(_adapters[node>>>24].isAttribute(node & CLR)); } public String lookupNamespace(int node, String prefix) throws TransletException { return _adapters[node>>>24].lookupNamespace(node, prefix); } }
false
true
public NodeIterator setStartNode(final int node) { _mask = node & SET; int dom = node >>> 24; // Get a new source for the first time only if (_source == null) { if (_type == NO_TYPE) { _source = _adapters[dom].getAxisIterator(_axis); } else if (_axis == Axis.CHILD && _type != ELEMENT) { _source = _adapters[dom].getTypedChildren(_type); } else { _source = _adapters[dom].getTypedAxisIterator(_axis, _type); } } _source.setStartNode(node & CLR); return this; }
public NodeIterator setStartNode(final int node) { final int dom = node >>> 24; final int mask = node & SET; // Get a new source first time and when mask changes if (_source == null || _mask != mask) { if (_type == NO_TYPE) { _source = _adapters[dom].getAxisIterator(_axis); } else if (_axis == Axis.CHILD && _type != ELEMENT) { _source = _adapters[dom].getTypedChildren(_type); } else { _source = _adapters[dom].getTypedAxisIterator(_axis, _type); } } _mask = mask; _source.setStartNode(node & CLR); return this; }
diff --git a/cdk-taverna-2-activity-ui/src/main/java/org/openscience/cdk/applications/taverna/ui/qsar/QSARDescriptorConfigurationPanel.java b/cdk-taverna-2-activity-ui/src/main/java/org/openscience/cdk/applications/taverna/ui/qsar/QSARDescriptorConfigurationPanel.java index b8586ef..a78e6af 100644 --- a/cdk-taverna-2-activity-ui/src/main/java/org/openscience/cdk/applications/taverna/ui/qsar/QSARDescriptorConfigurationPanel.java +++ b/cdk-taverna-2-activity-ui/src/main/java/org/openscience/cdk/applications/taverna/ui/qsar/QSARDescriptorConfigurationPanel.java @@ -1,244 +1,245 @@ package org.openscience.cdk.applications.taverna.ui.qsar; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.border.BevelBorder; import javax.swing.border.LineBorder; import javax.swing.border.TitledBorder; import net.sf.taverna.t2.spi.SPIRegistry; import net.sf.taverna.t2.workbench.ui.views.contextualviews.activity.ActivityConfigurationPanel; import org.openscience.cdk.applications.taverna.AbstractCDKActivity; import org.openscience.cdk.applications.taverna.CDKActivityConfigurationBean; import org.openscience.cdk.applications.taverna.CDKTavernaConstants; import org.openscience.cdk.applications.taverna.basicutilities.ErrorLogger; import org.openscience.cdk.applications.taverna.qsar.QSARDescriptorThreadedActivity; public class QSARDescriptorConfigurationPanel extends ActivityConfigurationPanel<AbstractCDKActivity, CDKActivityConfigurationBean> { private static final long serialVersionUID = 3360691883759809971L; private SPIRegistry<AbstractCDKActivity> cdkActivityRegistry = new SPIRegistry<AbstractCDKActivity>(AbstractCDKActivity.class); private AbstractCDKActivity activity; private CDKActivityConfigurationBean configBean; private JButton selectAllButton = null; private JButton clearButton = null; private JTextField threadsTextField = null; private HashMap<Class<? extends AbstractCDKActivity>, JCheckBox> selectionMap = null; private ArrayList<Class<? extends AbstractCDKActivity>> selectedClasses = new ArrayList<Class<? extends AbstractCDKActivity>>(); private JCheckBox showProgressCheckBox = null; public QSARDescriptorConfigurationPanel(AbstractCDKActivity activity) { this.activity = activity; this.configBean = this.activity.getConfiguration(); this.initGUI(); } @SuppressWarnings("unchecked") protected void initGUI() { try { JPanel selectionPanel = new JPanel(new GridLayout(1, 4)); this.setLayout(new BorderLayout()); this.setPreferredSize(new Dimension(1000, 600)); String[] packages = new String[] { "org.openscience.cdk.applications.taverna.qsar.descriptors.atomic", "org.openscience.cdk.applications.taverna.qsar.descriptors.bond", "org.openscience.cdk.applications.taverna.qsar.descriptors.molecular", "org.openscience.cdk.applications.taverna.qsar.descriptors.atompair", "org.openscience.cdk.applications.taverna.qsar.descriptors.protein" }; String[] titles = new String[] { "atomic", "bond", "molecular", "atompair", "protein" }; JPanel[] panels = new JPanel[packages.length]; JScrollPane[] scrollPanes = new JScrollPane[packages.length]; int[] length = new int[packages.length]; for (int i = 0; i < packages.length; i++) { panels[i] = new JPanel(); scrollPanes[i] = new JScrollPane(panels[i]); TitledBorder border = new TitledBorder(new LineBorder(Color.BLACK), titles[i] + " - Package"); scrollPanes[i].setBorder(border); scrollPanes[i].getViewport().setLayout(new FlowLayout()); scrollPanes[i].setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); for (AbstractCDKActivity cdkActivity : cdkActivityRegistry.getInstances()) { if (cdkActivity.getClass().getName().startsWith(packages[i])) { length[i]++; } } selectionPanel.add(scrollPanes[i]); } this.selectionMap = new HashMap<Class<? extends AbstractCDKActivity>, JCheckBox>(); for (int i = 0; i < packages.length; i++) { panels[i].setLayout(new GridLayout(length[i], 1)); for (AbstractCDKActivity cdkActivity : cdkActivityRegistry.getInstances()) { if (cdkActivity.getClass().getName().startsWith(packages[i])) { JCheckBox checkBox = new JCheckBox(cdkActivity.getClass().getSimpleName()); panels[i].add(checkBox); this.selectionMap.put(cdkActivity.getClass(), checkBox); } } } JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING)); buttonPanel.setBorder(new BevelBorder(BevelBorder.LOWERED)); this.selectAllButton = new JButton("Select all"); this.selectAllButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { QSARDescriptorConfigurationPanel.this.selectAll(); } }); this.clearButton = new JButton("Clear"); this.clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { QSARDescriptorConfigurationPanel.this.unselectAll(); } }); buttonPanel.add(this.selectAllButton); buttonPanel.add(this.clearButton); JLabel threadsLabel = new JLabel("Number of used Threads:"); threadsLabel.setHorizontalAlignment(JLabel.RIGHT); threadsLabel.setPreferredSize(new Dimension(150, 25)); int numberOfThreads = (Integer) this.configBean .getAdditionalProperty(CDKTavernaConstants.PROPERTY_NUMBER_OF_USED_THREADS); this.threadsTextField = new JTextField(); this.threadsTextField.setText(String.valueOf(numberOfThreads)); this.threadsTextField.setPreferredSize(new Dimension(40, 25)); if (!(this.activity instanceof QSARDescriptorThreadedActivity)) { threadsLabel.setEnabled(false); threadsTextField.setEnabled(false); } buttonPanel.add(threadsLabel); buttonPanel.add(this.threadsTextField); this.showProgressCheckBox = new JCheckBox("Show progress?"); boolean showProgress = (Boolean) this.configBean.getAdditionalProperty(CDKTavernaConstants.PROPERTY_SHOW_PROGRESS); this.showProgressCheckBox.setSelected(showProgress); + buttonPanel.add(this.showProgressCheckBox); this.add(selectionPanel, BorderLayout.CENTER); this.add(buttonPanel, BorderLayout.SOUTH); for (Entry<Class<? extends AbstractCDKActivity>, JCheckBox> entry : this.selectionMap.entrySet()) { JCheckBox checkBox = entry.getValue(); checkBox.setSelected(false); } ArrayList<Class<? extends AbstractCDKActivity>> classes = (ArrayList<Class<? extends AbstractCDKActivity>>) this.configBean .getAdditionalProperty(CDKTavernaConstants.PROPERTY_CHOSEN_QSARDESCRIPTORS); if (classes != null) { for (Class<? extends AbstractCDKActivity> clazz : classes) { JCheckBox checkBox = this.selectionMap.get(clazz); this.selectedClasses.add(clazz); checkBox.setSelected(true); } } this.repaint(); } catch (Exception e) { ErrorLogger.getInstance().writeError("Error during setting up configuration panel!", this.getClass().getSimpleName(), e); } } private void selectAll() { for (Entry<Class<? extends AbstractCDKActivity>, JCheckBox> entry : this.selectionMap.entrySet()) { JCheckBox checkBox = entry.getValue(); checkBox.setSelected(true); } } private void unselectAll() { for (Entry<Class<? extends AbstractCDKActivity>, JCheckBox> entry : this.selectionMap.entrySet()) { JCheckBox checkBox = entry.getValue(); checkBox.setSelected(false); } } private ArrayList<Class<? extends AbstractCDKActivity>> getSelectedClasses() { ArrayList<Class<? extends AbstractCDKActivity>> classes = new ArrayList<Class<? extends AbstractCDKActivity>>(); for (Entry<Class<? extends AbstractCDKActivity>, JCheckBox> entry : this.selectionMap.entrySet()) { Class<? extends AbstractCDKActivity> clazz = entry.getKey(); JCheckBox checkBox = entry.getValue(); if (checkBox.isSelected()) { classes.add(clazz); } } return classes; } @Override public boolean checkValues() { try { int v = Integer.parseInt(this.threadsTextField.getText()); if (v < 1) { JOptionPane.showMessageDialog(this, "Please enter a valid number!", "Error", JOptionPane.ERROR_MESSAGE); return false; } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Please enter a valid number!", "Error", JOptionPane.ERROR_MESSAGE); return false; } return !this.getSelectedClasses().isEmpty(); } @Override public CDKActivityConfigurationBean getConfiguration() { return this.configBean; } @Override public boolean isConfigurationChanged() { for (Entry<Class<? extends AbstractCDKActivity>, JCheckBox> entry : this.selectionMap.entrySet()) { Class<? extends AbstractCDKActivity> clazz = entry.getKey(); JCheckBox checkBox = entry.getValue(); if (checkBox.isSelected()) { if (!this.selectedClasses.contains(clazz)) { return true; } } else { if (this.selectedClasses.contains(clazz)) { return true; } } } int numberOfThreads = (Integer) this.configBean .getAdditionalProperty(CDKTavernaConstants.PROPERTY_NUMBER_OF_USED_THREADS); int newValue = Integer.parseInt(this.threadsTextField.getText()); if (numberOfThreads != newValue) { return true; } boolean showProgress = (Boolean) this.configBean.getAdditionalProperty(CDKTavernaConstants.PROPERTY_SHOW_PROGRESS); if(showProgress != this.showProgressCheckBox.isSelected()) { return true; } return false; } @Override public void noteConfiguration() { this.configBean = (CDKActivityConfigurationBean) this.cloneBean(this.configBean); this.configBean.addAdditionalProperty(CDKTavernaConstants.PROPERTY_CHOSEN_QSARDESCRIPTORS, this.getSelectedClasses()); int newValue = Integer.parseInt(this.threadsTextField.getText()); this.configBean.addAdditionalProperty(CDKTavernaConstants.PROPERTY_NUMBER_OF_USED_THREADS, newValue); boolean showProgress = this.showProgressCheckBox.isSelected(); this.configBean.addAdditionalProperty(CDKTavernaConstants.PROPERTY_SHOW_PROGRESS, showProgress); } @Override public void refreshConfiguration() { this.selectedClasses = this.getSelectedClasses(); } }
true
true
protected void initGUI() { try { JPanel selectionPanel = new JPanel(new GridLayout(1, 4)); this.setLayout(new BorderLayout()); this.setPreferredSize(new Dimension(1000, 600)); String[] packages = new String[] { "org.openscience.cdk.applications.taverna.qsar.descriptors.atomic", "org.openscience.cdk.applications.taverna.qsar.descriptors.bond", "org.openscience.cdk.applications.taverna.qsar.descriptors.molecular", "org.openscience.cdk.applications.taverna.qsar.descriptors.atompair", "org.openscience.cdk.applications.taverna.qsar.descriptors.protein" }; String[] titles = new String[] { "atomic", "bond", "molecular", "atompair", "protein" }; JPanel[] panels = new JPanel[packages.length]; JScrollPane[] scrollPanes = new JScrollPane[packages.length]; int[] length = new int[packages.length]; for (int i = 0; i < packages.length; i++) { panels[i] = new JPanel(); scrollPanes[i] = new JScrollPane(panels[i]); TitledBorder border = new TitledBorder(new LineBorder(Color.BLACK), titles[i] + " - Package"); scrollPanes[i].setBorder(border); scrollPanes[i].getViewport().setLayout(new FlowLayout()); scrollPanes[i].setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); for (AbstractCDKActivity cdkActivity : cdkActivityRegistry.getInstances()) { if (cdkActivity.getClass().getName().startsWith(packages[i])) { length[i]++; } } selectionPanel.add(scrollPanes[i]); } this.selectionMap = new HashMap<Class<? extends AbstractCDKActivity>, JCheckBox>(); for (int i = 0; i < packages.length; i++) { panels[i].setLayout(new GridLayout(length[i], 1)); for (AbstractCDKActivity cdkActivity : cdkActivityRegistry.getInstances()) { if (cdkActivity.getClass().getName().startsWith(packages[i])) { JCheckBox checkBox = new JCheckBox(cdkActivity.getClass().getSimpleName()); panels[i].add(checkBox); this.selectionMap.put(cdkActivity.getClass(), checkBox); } } } JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING)); buttonPanel.setBorder(new BevelBorder(BevelBorder.LOWERED)); this.selectAllButton = new JButton("Select all"); this.selectAllButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { QSARDescriptorConfigurationPanel.this.selectAll(); } }); this.clearButton = new JButton("Clear"); this.clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { QSARDescriptorConfigurationPanel.this.unselectAll(); } }); buttonPanel.add(this.selectAllButton); buttonPanel.add(this.clearButton); JLabel threadsLabel = new JLabel("Number of used Threads:"); threadsLabel.setHorizontalAlignment(JLabel.RIGHT); threadsLabel.setPreferredSize(new Dimension(150, 25)); int numberOfThreads = (Integer) this.configBean .getAdditionalProperty(CDKTavernaConstants.PROPERTY_NUMBER_OF_USED_THREADS); this.threadsTextField = new JTextField(); this.threadsTextField.setText(String.valueOf(numberOfThreads)); this.threadsTextField.setPreferredSize(new Dimension(40, 25)); if (!(this.activity instanceof QSARDescriptorThreadedActivity)) { threadsLabel.setEnabled(false); threadsTextField.setEnabled(false); } buttonPanel.add(threadsLabel); buttonPanel.add(this.threadsTextField); this.showProgressCheckBox = new JCheckBox("Show progress?"); boolean showProgress = (Boolean) this.configBean.getAdditionalProperty(CDKTavernaConstants.PROPERTY_SHOW_PROGRESS); this.showProgressCheckBox.setSelected(showProgress); this.add(selectionPanel, BorderLayout.CENTER); this.add(buttonPanel, BorderLayout.SOUTH); for (Entry<Class<? extends AbstractCDKActivity>, JCheckBox> entry : this.selectionMap.entrySet()) { JCheckBox checkBox = entry.getValue(); checkBox.setSelected(false); } ArrayList<Class<? extends AbstractCDKActivity>> classes = (ArrayList<Class<? extends AbstractCDKActivity>>) this.configBean .getAdditionalProperty(CDKTavernaConstants.PROPERTY_CHOSEN_QSARDESCRIPTORS); if (classes != null) { for (Class<? extends AbstractCDKActivity> clazz : classes) { JCheckBox checkBox = this.selectionMap.get(clazz); this.selectedClasses.add(clazz); checkBox.setSelected(true); } } this.repaint(); } catch (Exception e) { ErrorLogger.getInstance().writeError("Error during setting up configuration panel!", this.getClass().getSimpleName(), e); } }
protected void initGUI() { try { JPanel selectionPanel = new JPanel(new GridLayout(1, 4)); this.setLayout(new BorderLayout()); this.setPreferredSize(new Dimension(1000, 600)); String[] packages = new String[] { "org.openscience.cdk.applications.taverna.qsar.descriptors.atomic", "org.openscience.cdk.applications.taverna.qsar.descriptors.bond", "org.openscience.cdk.applications.taverna.qsar.descriptors.molecular", "org.openscience.cdk.applications.taverna.qsar.descriptors.atompair", "org.openscience.cdk.applications.taverna.qsar.descriptors.protein" }; String[] titles = new String[] { "atomic", "bond", "molecular", "atompair", "protein" }; JPanel[] panels = new JPanel[packages.length]; JScrollPane[] scrollPanes = new JScrollPane[packages.length]; int[] length = new int[packages.length]; for (int i = 0; i < packages.length; i++) { panels[i] = new JPanel(); scrollPanes[i] = new JScrollPane(panels[i]); TitledBorder border = new TitledBorder(new LineBorder(Color.BLACK), titles[i] + " - Package"); scrollPanes[i].setBorder(border); scrollPanes[i].getViewport().setLayout(new FlowLayout()); scrollPanes[i].setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); for (AbstractCDKActivity cdkActivity : cdkActivityRegistry.getInstances()) { if (cdkActivity.getClass().getName().startsWith(packages[i])) { length[i]++; } } selectionPanel.add(scrollPanes[i]); } this.selectionMap = new HashMap<Class<? extends AbstractCDKActivity>, JCheckBox>(); for (int i = 0; i < packages.length; i++) { panels[i].setLayout(new GridLayout(length[i], 1)); for (AbstractCDKActivity cdkActivity : cdkActivityRegistry.getInstances()) { if (cdkActivity.getClass().getName().startsWith(packages[i])) { JCheckBox checkBox = new JCheckBox(cdkActivity.getClass().getSimpleName()); panels[i].add(checkBox); this.selectionMap.put(cdkActivity.getClass(), checkBox); } } } JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING)); buttonPanel.setBorder(new BevelBorder(BevelBorder.LOWERED)); this.selectAllButton = new JButton("Select all"); this.selectAllButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { QSARDescriptorConfigurationPanel.this.selectAll(); } }); this.clearButton = new JButton("Clear"); this.clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { QSARDescriptorConfigurationPanel.this.unselectAll(); } }); buttonPanel.add(this.selectAllButton); buttonPanel.add(this.clearButton); JLabel threadsLabel = new JLabel("Number of used Threads:"); threadsLabel.setHorizontalAlignment(JLabel.RIGHT); threadsLabel.setPreferredSize(new Dimension(150, 25)); int numberOfThreads = (Integer) this.configBean .getAdditionalProperty(CDKTavernaConstants.PROPERTY_NUMBER_OF_USED_THREADS); this.threadsTextField = new JTextField(); this.threadsTextField.setText(String.valueOf(numberOfThreads)); this.threadsTextField.setPreferredSize(new Dimension(40, 25)); if (!(this.activity instanceof QSARDescriptorThreadedActivity)) { threadsLabel.setEnabled(false); threadsTextField.setEnabled(false); } buttonPanel.add(threadsLabel); buttonPanel.add(this.threadsTextField); this.showProgressCheckBox = new JCheckBox("Show progress?"); boolean showProgress = (Boolean) this.configBean.getAdditionalProperty(CDKTavernaConstants.PROPERTY_SHOW_PROGRESS); this.showProgressCheckBox.setSelected(showProgress); buttonPanel.add(this.showProgressCheckBox); this.add(selectionPanel, BorderLayout.CENTER); this.add(buttonPanel, BorderLayout.SOUTH); for (Entry<Class<? extends AbstractCDKActivity>, JCheckBox> entry : this.selectionMap.entrySet()) { JCheckBox checkBox = entry.getValue(); checkBox.setSelected(false); } ArrayList<Class<? extends AbstractCDKActivity>> classes = (ArrayList<Class<? extends AbstractCDKActivity>>) this.configBean .getAdditionalProperty(CDKTavernaConstants.PROPERTY_CHOSEN_QSARDESCRIPTORS); if (classes != null) { for (Class<? extends AbstractCDKActivity> clazz : classes) { JCheckBox checkBox = this.selectionMap.get(clazz); this.selectedClasses.add(clazz); checkBox.setSelected(true); } } this.repaint(); } catch (Exception e) { ErrorLogger.getInstance().writeError("Error during setting up configuration panel!", this.getClass().getSimpleName(), e); } }
diff --git a/src/main/java/org/geoserver/shell/PostGISCommands.java b/src/main/java/org/geoserver/shell/PostGISCommands.java index 6c0f398..8ff2bbb 100644 --- a/src/main/java/org/geoserver/shell/PostGISCommands.java +++ b/src/main/java/org/geoserver/shell/PostGISCommands.java @@ -1,59 +1,59 @@ package org.geoserver.shell; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.shell.core.CommandMarker; import org.springframework.shell.core.annotation.CliAvailabilityIndicator; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.springframework.stereotype.Component; @Component public class PostGISCommands implements CommandMarker { @Autowired private Geoserver geoserver; public void setGeoserver(Geoserver gs) { this.geoserver = gs; } @CliAvailabilityIndicator({"postgis datastore create", "postgis featuretype publish"}) public boolean isCommandAvailable() { return geoserver.isSet(); } @CliCommand(value = "postgis datastore create", help = "Create a PostGIS DataStore.") public boolean createDataStore( @CliOption(key = "workspace", mandatory = true, help = "The workspace") String workspace, @CliOption(key = "datastore", mandatory = true, help = "The datastore") String datastore, @CliOption(key = "host", mandatory = true, help = "The host") String host, @CliOption(key = "port", mandatory = false, unspecifiedDefaultValue = "5432", help = "The port") String port, @CliOption(key = "database", mandatory = true, help = "The database name") String database, @CliOption(key = "schema", mandatory = false, unspecifiedDefaultValue = "public", help = "The schema") String schema, @CliOption(key = "user", mandatory = true, help = "The user name") String user, @CliOption(key = "password", mandatory = true, help = "The password") String password ) throws Exception { StringBuilder connectionStringBuilder = new StringBuilder(); connectionStringBuilder.append("dbtype=postgis").append(" "); connectionStringBuilder.append("host=").append(host).append(" "); connectionStringBuilder.append("port=").append(port).append(" "); connectionStringBuilder.append("database='").append(database).append("' "); connectionStringBuilder.append("schema='").append(schema).append("' "); connectionStringBuilder.append("user='").append(user).append("' "); - connectionStringBuilder.append("password='").append(password).append("'"); + connectionStringBuilder.append("passwd='").append(password).append("'"); DataStoreCommands dataStoreCommands = new DataStoreCommands(); dataStoreCommands.setGeoserver(geoserver); return dataStoreCommands.create(workspace, datastore, connectionStringBuilder.toString(), null, true); } @CliCommand(value = "postgis featuretype publish", help = "Publish a PostGIS Table.") public boolean publishLayer( @CliOption(key = "workspace", mandatory = true, help = "The workspace") String workspace, @CliOption(key = "datastore", mandatory = true, help = "The datastore") String datastore, @CliOption(key = "table", mandatory = true, help = "The table") String table ) throws Exception { FeatureTypeCommands featureTypeCommands = new FeatureTypeCommands(); featureTypeCommands.setGeoserver(geoserver); return featureTypeCommands.publish(workspace, datastore, table); } }
true
true
public boolean createDataStore( @CliOption(key = "workspace", mandatory = true, help = "The workspace") String workspace, @CliOption(key = "datastore", mandatory = true, help = "The datastore") String datastore, @CliOption(key = "host", mandatory = true, help = "The host") String host, @CliOption(key = "port", mandatory = false, unspecifiedDefaultValue = "5432", help = "The port") String port, @CliOption(key = "database", mandatory = true, help = "The database name") String database, @CliOption(key = "schema", mandatory = false, unspecifiedDefaultValue = "public", help = "The schema") String schema, @CliOption(key = "user", mandatory = true, help = "The user name") String user, @CliOption(key = "password", mandatory = true, help = "The password") String password ) throws Exception { StringBuilder connectionStringBuilder = new StringBuilder(); connectionStringBuilder.append("dbtype=postgis").append(" "); connectionStringBuilder.append("host=").append(host).append(" "); connectionStringBuilder.append("port=").append(port).append(" "); connectionStringBuilder.append("database='").append(database).append("' "); connectionStringBuilder.append("schema='").append(schema).append("' "); connectionStringBuilder.append("user='").append(user).append("' "); connectionStringBuilder.append("password='").append(password).append("'"); DataStoreCommands dataStoreCommands = new DataStoreCommands(); dataStoreCommands.setGeoserver(geoserver); return dataStoreCommands.create(workspace, datastore, connectionStringBuilder.toString(), null, true); }
public boolean createDataStore( @CliOption(key = "workspace", mandatory = true, help = "The workspace") String workspace, @CliOption(key = "datastore", mandatory = true, help = "The datastore") String datastore, @CliOption(key = "host", mandatory = true, help = "The host") String host, @CliOption(key = "port", mandatory = false, unspecifiedDefaultValue = "5432", help = "The port") String port, @CliOption(key = "database", mandatory = true, help = "The database name") String database, @CliOption(key = "schema", mandatory = false, unspecifiedDefaultValue = "public", help = "The schema") String schema, @CliOption(key = "user", mandatory = true, help = "The user name") String user, @CliOption(key = "password", mandatory = true, help = "The password") String password ) throws Exception { StringBuilder connectionStringBuilder = new StringBuilder(); connectionStringBuilder.append("dbtype=postgis").append(" "); connectionStringBuilder.append("host=").append(host).append(" "); connectionStringBuilder.append("port=").append(port).append(" "); connectionStringBuilder.append("database='").append(database).append("' "); connectionStringBuilder.append("schema='").append(schema).append("' "); connectionStringBuilder.append("user='").append(user).append("' "); connectionStringBuilder.append("passwd='").append(password).append("'"); DataStoreCommands dataStoreCommands = new DataStoreCommands(); dataStoreCommands.setGeoserver(geoserver); return dataStoreCommands.create(workspace, datastore, connectionStringBuilder.toString(), null, true); }
diff --git a/src/main/java/de/minestar/FifthElement/commands/home/cmdHome.java b/src/main/java/de/minestar/FifthElement/commands/home/cmdHome.java index 180b134..09b2696 100644 --- a/src/main/java/de/minestar/FifthElement/commands/home/cmdHome.java +++ b/src/main/java/de/minestar/FifthElement/commands/home/cmdHome.java @@ -1,74 +1,75 @@ /* * Copyright (C) 2012 MineStar.de * * This file is part of FifthElement. * * FifthElement is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3 of the License. * * FifthElement 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 FifthElement. If not, see <http://www.gnu.org/licenses/>. */ package de.minestar.FifthElement.commands.home; import org.bukkit.entity.Player; import de.minestar.FifthElement.core.Core; import de.minestar.FifthElement.data.Home; import de.minestar.minestarlibrary.commands.AbstractExtendedCommand; import de.minestar.minestarlibrary.utils.PlayerUtils; public class cmdHome extends AbstractExtendedCommand { private static final String OTHER_HOME_PERMISSION = "fifthelement.command.otherhome"; public cmdHome(String syntax, String arguments, String node) { super(Core.NAME, syntax, arguments, node); } @Override public void execute(String[] args, Player player) { Home home = null; // OWN HOME if (args.length == 0) { home = Core.homeManager.getHome(player.getName()); if (home == null) { PlayerUtils.sendError(player, pluginName, "Du hast kein Zuhause erstellt!"); PlayerUtils.sendInfo(player, "Mit '/setHome' erstellst du dir ein Zuhause."); + return; } player.teleport(home.getLocation()); PlayerUtils.sendSuccess(player, pluginName, "Willkommen zu Hause."); } // HOME OF OTHER PLAYER else if (args.length == 1) { // CAN PLAYER USE OTHER HOMES if (checkSpecialPermission(player, OTHER_HOME_PERMISSION)) { // FIND THE CORRECT PLAYER NAME String targetName = PlayerUtils.getCorrectPlayerName(args[0]); if (targetName == null) { PlayerUtils.sendError(player, targetName, "Kann den Spieler '" + args[0] + "' nicht finden!"); return; } home = Core.homeManager.getHome(targetName); if (home == null) { PlayerUtils.sendError(player, pluginName, "Der Spieler '" + targetName + "'hat kein Zuhause erstellt!"); return; } PlayerUtils.sendSuccess(player, pluginName, "Haus von '" + home.getOwner() + "'."); } } // WRONG COMMAND SYNTAX else { PlayerUtils.sendError(player, pluginName, getHelpMessage()); return; } } }
true
true
public void execute(String[] args, Player player) { Home home = null; // OWN HOME if (args.length == 0) { home = Core.homeManager.getHome(player.getName()); if (home == null) { PlayerUtils.sendError(player, pluginName, "Du hast kein Zuhause erstellt!"); PlayerUtils.sendInfo(player, "Mit '/setHome' erstellst du dir ein Zuhause."); } player.teleport(home.getLocation()); PlayerUtils.sendSuccess(player, pluginName, "Willkommen zu Hause."); } // HOME OF OTHER PLAYER else if (args.length == 1) { // CAN PLAYER USE OTHER HOMES if (checkSpecialPermission(player, OTHER_HOME_PERMISSION)) { // FIND THE CORRECT PLAYER NAME String targetName = PlayerUtils.getCorrectPlayerName(args[0]); if (targetName == null) { PlayerUtils.sendError(player, targetName, "Kann den Spieler '" + args[0] + "' nicht finden!"); return; } home = Core.homeManager.getHome(targetName); if (home == null) { PlayerUtils.sendError(player, pluginName, "Der Spieler '" + targetName + "'hat kein Zuhause erstellt!"); return; } PlayerUtils.sendSuccess(player, pluginName, "Haus von '" + home.getOwner() + "'."); } } // WRONG COMMAND SYNTAX else { PlayerUtils.sendError(player, pluginName, getHelpMessage()); return; } }
public void execute(String[] args, Player player) { Home home = null; // OWN HOME if (args.length == 0) { home = Core.homeManager.getHome(player.getName()); if (home == null) { PlayerUtils.sendError(player, pluginName, "Du hast kein Zuhause erstellt!"); PlayerUtils.sendInfo(player, "Mit '/setHome' erstellst du dir ein Zuhause."); return; } player.teleport(home.getLocation()); PlayerUtils.sendSuccess(player, pluginName, "Willkommen zu Hause."); } // HOME OF OTHER PLAYER else if (args.length == 1) { // CAN PLAYER USE OTHER HOMES if (checkSpecialPermission(player, OTHER_HOME_PERMISSION)) { // FIND THE CORRECT PLAYER NAME String targetName = PlayerUtils.getCorrectPlayerName(args[0]); if (targetName == null) { PlayerUtils.sendError(player, targetName, "Kann den Spieler '" + args[0] + "' nicht finden!"); return; } home = Core.homeManager.getHome(targetName); if (home == null) { PlayerUtils.sendError(player, pluginName, "Der Spieler '" + targetName + "'hat kein Zuhause erstellt!"); return; } PlayerUtils.sendSuccess(player, pluginName, "Haus von '" + home.getOwner() + "'."); } } // WRONG COMMAND SYNTAX else { PlayerUtils.sendError(player, pluginName, getHelpMessage()); return; } }
diff --git a/languages/DeCypher/source_gen/DeCypher/textGen/WhereClause_TextGen.java b/languages/DeCypher/source_gen/DeCypher/textGen/WhereClause_TextGen.java index 04dff67..4c96092 100644 --- a/languages/DeCypher/source_gen/DeCypher/textGen/WhereClause_TextGen.java +++ b/languages/DeCypher/source_gen/DeCypher/textGen/WhereClause_TextGen.java @@ -1,21 +1,21 @@ package DeCypher.textGen; /*Generated by MPS */ import jetbrains.mps.textGen.SNodeTextGen; import jetbrains.mps.smodel.SNode; import jetbrains.mps.internal.collections.runtime.ListSequence; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations; import jetbrains.mps.textGen.TextGenManager; public class WhereClause_TextGen extends SNodeTextGen { public void doGenerateText(SNode node) { - this.append("\"WHxxERE "); + this.append("\"WHxxxxxxxERE "); if (ListSequence.fromList(SLinkOperations.getTargets(node, "term", true)).isNotEmpty()) { for (SNode item : SLinkOperations.getTargets(node, "term", true)) { TextGenManager.instance().appendNodeText(this.getContext(), this.getBuffer(), item, this.getSNode()); } } this.append("\""); } }
true
true
public void doGenerateText(SNode node) { this.append("\"WHxxERE "); if (ListSequence.fromList(SLinkOperations.getTargets(node, "term", true)).isNotEmpty()) { for (SNode item : SLinkOperations.getTargets(node, "term", true)) { TextGenManager.instance().appendNodeText(this.getContext(), this.getBuffer(), item, this.getSNode()); } } this.append("\""); }
public void doGenerateText(SNode node) { this.append("\"WHxxxxxxxERE "); if (ListSequence.fromList(SLinkOperations.getTargets(node, "term", true)).isNotEmpty()) { for (SNode item : SLinkOperations.getTargets(node, "term", true)) { TextGenManager.instance().appendNodeText(this.getContext(), this.getBuffer(), item, this.getSNode()); } } this.append("\""); }
diff --git a/activemq-optional/src/main/java/org/apache/activemq/transport/http/HttpTunnelServlet.java b/activemq-optional/src/main/java/org/apache/activemq/transport/http/HttpTunnelServlet.java index 957fa9386..538f4a3bd 100755 --- a/activemq-optional/src/main/java/org/apache/activemq/transport/http/HttpTunnelServlet.java +++ b/activemq-optional/src/main/java/org/apache/activemq/transport/http/HttpTunnelServlet.java @@ -1,219 +1,220 @@ /** * 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.activemq.transport.http; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.activemq.command.Command; import org.apache.activemq.command.WireFormatInfo; import org.apache.activemq.transport.InactivityMonitor; import org.apache.activemq.transport.Transport; import org.apache.activemq.transport.TransportAcceptListener; import org.apache.activemq.transport.util.TextWireFormat; import org.apache.activemq.transport.xstream.XStreamWireFormat; import org.apache.activemq.util.IOExceptionSupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A servlet which handles server side HTTP transport, delegating to the * ActiveMQ broker. This servlet is designed for being embedded inside an * ActiveMQ Broker using an embedded Jetty or Tomcat instance. * * @version $Revision$ */ public class HttpTunnelServlet extends HttpServlet { private static final long serialVersionUID = -3826714430767484333L; private static final Log LOG = LogFactory.getLog(HttpTunnelServlet.class); private TransportAcceptListener listener; private HttpTransportFactory transportFactory; private TextWireFormat wireFormat; private final Map<String, BlockingQueueTransport> clients = new HashMap<String, BlockingQueueTransport>(); private final long requestTimeout = 30000L; private HashMap transportOptions; @Override public void init() throws ServletException { super.init(); listener = (TransportAcceptListener)getServletContext().getAttribute("acceptListener"); if (listener == null) { throw new ServletException("No such attribute 'acceptListener' available in the ServletContext"); } transportFactory = (HttpTransportFactory)getServletContext().getAttribute("transportFactory"); if (transportFactory == null) { throw new ServletException("No such attribute 'transportFactory' available in the ServletContext"); } transportOptions = (HashMap)getServletContext().getAttribute("transportOptions"); wireFormat = (TextWireFormat)getServletContext().getAttribute("wireFormat"); if (wireFormat == null) { wireFormat = createWireFormat(); } } @Override protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { createTransportChannel(request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // lets return the next response Command packet = null; int count = 0; try { BlockingQueueTransport transportChannel = getTransportChannel(request, response); if (transportChannel == null) { return; } packet = (Command)transportChannel.getQueue().poll(requestTimeout, TimeUnit.MILLISECONDS); DataOutputStream stream = new DataOutputStream(response.getOutputStream()); // while( packet !=null ) { wireFormat.marshal(packet, stream); count++; // packet = (Command) transportChannel.getQueue().poll(0, // TimeUnit.MILLISECONDS); // } } catch (InterruptedException ignore) { } if (count == 0) { response.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Read the command directly from the reader, assuming UTF8 encoding ServletInputStream sis = request.getInputStream(); Command command = (Command) wireFormat.unmarshalText(new InputStreamReader(sis, "UTF-8")); if (command instanceof WireFormatInfo) { WireFormatInfo info = (WireFormatInfo) command; if (!canProcessWireFormatVersion(info.getVersion())) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Cannot process wire format of version: " + info.getVersion()); } } else { BlockingQueueTransport transport = getTransportChannel(request, response); if (transport == null) { return; } transport.doConsume(command); } } private boolean canProcessWireFormatVersion(int version) { // TODO: return true; } protected String readRequestBody(HttpServletRequest request) throws IOException { StringBuffer buffer = new StringBuffer(); BufferedReader reader = request.getReader(); while (true) { String line = reader.readLine(); if (line == null) { break; } else { buffer.append(line); buffer.append("\n"); } } return buffer.toString(); } protected BlockingQueueTransport getTransportChannel(HttpServletRequest request, HttpServletResponse response) throws IOException { String clientID = request.getHeader("clientID"); if (clientID == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No clientID header specified"); LOG.warn("No clientID header specified"); return null; } synchronized (this) { BlockingQueueTransport answer = clients.get(clientID); if (answer == null) { LOG.warn("The clientID header specified is invalid. Client sesion has not yet been established for it: " + clientID); return null; } return answer; } } protected BlockingQueueTransport createTransportChannel(HttpServletRequest request, HttpServletResponse response) throws IOException { String clientID = request.getHeader("clientID"); if (clientID == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No clientID header specified"); LOG.warn("No clientID header specified"); return null; } synchronized (this) { BlockingQueueTransport answer = clients.get(clientID); if (answer != null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "A session for clientID '" + clientID + "' has already been established"); LOG.warn("A session for clientID '" + clientID + "' has already been established"); return null; } answer = createTransportChannel(); clients.put(clientID, answer); Transport transport = answer; try { - transport = transportFactory.serverConfigure(answer, null, transportOptions); + HashMap options = new HashMap(transportOptions); + transport = transportFactory.serverConfigure(answer, null, options); } catch (Exception e) { IOExceptionSupport.create(e); } listener.onAccept(transport); //wait for the transport to connect while (!answer.isConnected()) { try { Thread.sleep(100); } catch (InterruptedException ignore) { } } return answer; } } protected BlockingQueueTransport createTransportChannel() { return new BlockingQueueTransport(new LinkedBlockingQueue<Object>()); } protected TextWireFormat createWireFormat() { return new XStreamWireFormat(); } }
true
true
protected BlockingQueueTransport createTransportChannel(HttpServletRequest request, HttpServletResponse response) throws IOException { String clientID = request.getHeader("clientID"); if (clientID == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No clientID header specified"); LOG.warn("No clientID header specified"); return null; } synchronized (this) { BlockingQueueTransport answer = clients.get(clientID); if (answer != null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "A session for clientID '" + clientID + "' has already been established"); LOG.warn("A session for clientID '" + clientID + "' has already been established"); return null; } answer = createTransportChannel(); clients.put(clientID, answer); Transport transport = answer; try { transport = transportFactory.serverConfigure(answer, null, transportOptions); } catch (Exception e) { IOExceptionSupport.create(e); } listener.onAccept(transport); //wait for the transport to connect while (!answer.isConnected()) { try { Thread.sleep(100); } catch (InterruptedException ignore) { } } return answer; } }
protected BlockingQueueTransport createTransportChannel(HttpServletRequest request, HttpServletResponse response) throws IOException { String clientID = request.getHeader("clientID"); if (clientID == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No clientID header specified"); LOG.warn("No clientID header specified"); return null; } synchronized (this) { BlockingQueueTransport answer = clients.get(clientID); if (answer != null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "A session for clientID '" + clientID + "' has already been established"); LOG.warn("A session for clientID '" + clientID + "' has already been established"); return null; } answer = createTransportChannel(); clients.put(clientID, answer); Transport transport = answer; try { HashMap options = new HashMap(transportOptions); transport = transportFactory.serverConfigure(answer, null, options); } catch (Exception e) { IOExceptionSupport.create(e); } listener.onAccept(transport); //wait for the transport to connect while (!answer.isConnected()) { try { Thread.sleep(100); } catch (InterruptedException ignore) { } } return answer; } }
diff --git a/src/org/sc/annotator/adaptive/client/WebClient.java b/src/org/sc/annotator/adaptive/client/WebClient.java index 7f27c73..00d7d95 100644 --- a/src/org/sc/annotator/adaptive/client/WebClient.java +++ b/src/org/sc/annotator/adaptive/client/WebClient.java @@ -1,113 +1,112 @@ package org.sc.annotator.adaptive.client; import java.net.*; import java.util.*; import java.io.*; import org.sc.annotator.adaptive.AdaptiveMatcher; import org.sc.annotator.adaptive.Context; import org.sc.annotator.adaptive.Match; import org.sc.annotator.adaptive.exceptions.MatcherCloseException; import org.sc.annotator.adaptive.exceptions.MatcherException; public class WebClient implements AdaptiveMatcher { private String base; public WebClient(String b) { base = b; } public Collection<Match> findMatches(Context c, String blockText) throws MatcherException { try { URL url = new URL(String.format("%s?context=%s&text=%s", base, URLEncoder.encode(c.toString(), "UTF-8"), URLEncoder.encode(blockText, "UTF-8"))); LinkedList<Match> matches = new LinkedList<Match>(); HttpURLConnection cxn = (HttpURLConnection)url.openConnection(); cxn.setRequestMethod("GET"); cxn.connect(); int status = cxn.getResponseCode(); if(status == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(cxn.getInputStream())); String line; while((line = reader.readLine()) != null) { String value = line; Match m = new Match(c, blockText, value); matches.add(m); } reader.close(); } else { String msg = String.format("%d : %s", status, cxn.getResponseMessage()); throw new MatcherException(msg); } return matches; } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new MatcherException(e); } } public Context registerMatch(Match m) throws MatcherException { try { URL url = new URL(base); Context matched = null; HttpURLConnection cxn = (HttpURLConnection)url.openConnection(); cxn.setRequestMethod("POST"); cxn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); cxn.setDoOutput(true); OutputStream os = cxn.getOutputStream(); PrintStream ps = new PrintStream(os); ps.print(String.format("context=%s", URLEncoder.encode(m.context().toString(), "UTF-8"))); ps.print(String.format("&text=%s", URLEncoder.encode(m.match(), "UTF-8"))); ps.print(String.format("&value=%s", URLEncoder.encode(m.value(), "UTF-8"))); - ps.println(); cxn.connect(); int status = cxn.getResponseCode(); if(status == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(cxn.getInputStream())); String line = reader.readLine(); matched = new Context(line); reader.close(); } else { String msg = String.format("%d : %s", status, cxn.getResponseMessage()); throw new MatcherException(msg); } return matched; } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new MatcherException(e); } } public void close() throws MatcherCloseException { } }
true
true
public Context registerMatch(Match m) throws MatcherException { try { URL url = new URL(base); Context matched = null; HttpURLConnection cxn = (HttpURLConnection)url.openConnection(); cxn.setRequestMethod("POST"); cxn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); cxn.setDoOutput(true); OutputStream os = cxn.getOutputStream(); PrintStream ps = new PrintStream(os); ps.print(String.format("context=%s", URLEncoder.encode(m.context().toString(), "UTF-8"))); ps.print(String.format("&text=%s", URLEncoder.encode(m.match(), "UTF-8"))); ps.print(String.format("&value=%s", URLEncoder.encode(m.value(), "UTF-8"))); ps.println(); cxn.connect(); int status = cxn.getResponseCode(); if(status == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(cxn.getInputStream())); String line = reader.readLine(); matched = new Context(line); reader.close(); } else { String msg = String.format("%d : %s", status, cxn.getResponseMessage()); throw new MatcherException(msg); } return matched; } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new MatcherException(e); } }
public Context registerMatch(Match m) throws MatcherException { try { URL url = new URL(base); Context matched = null; HttpURLConnection cxn = (HttpURLConnection)url.openConnection(); cxn.setRequestMethod("POST"); cxn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); cxn.setDoOutput(true); OutputStream os = cxn.getOutputStream(); PrintStream ps = new PrintStream(os); ps.print(String.format("context=%s", URLEncoder.encode(m.context().toString(), "UTF-8"))); ps.print(String.format("&text=%s", URLEncoder.encode(m.match(), "UTF-8"))); ps.print(String.format("&value=%s", URLEncoder.encode(m.value(), "UTF-8"))); cxn.connect(); int status = cxn.getResponseCode(); if(status == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(cxn.getInputStream())); String line = reader.readLine(); matched = new Context(line); reader.close(); } else { String msg = String.format("%d : %s", status, cxn.getResponseMessage()); throw new MatcherException(msg); } return matched; } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new MatcherException(e); } }
diff --git a/src/org/apache/xerces/util/URI.java b/src/org/apache/xerces/util/URI.java index 950310fc..9285416d 100644 --- a/src/org/apache/xerces/util/URI.java +++ b/src/org/apache/xerces/util/URI.java @@ -1,1994 +1,1994 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2003 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 "Xerces" 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, iClick Inc., * http://www.apache.org. For more information on the Apache Software * Foundation, please see <http://www.apache.org/>. */ package org.apache.xerces.util; import java.io.IOException; import java.io.Serializable; /********************************************************************** * A class to represent a Uniform Resource Identifier (URI). This class * is designed to handle the parsing of URIs and provide access to * the various components (scheme, host, port, userinfo, path, query * string and fragment) that may constitute a URI. * <p> * Parsing of a URI specification is done according to the URI * syntax described in * <a href="http://www.ietf.org/rfc/rfc2396.txt?number=2396">RFC 2396</a>, * and amended by * <a href="http://www.ietf.org/rfc/rfc2732.txt?number=2732">RFC 2732</a>. * <p> * Every absolute URI consists of a scheme, followed by a colon (':'), * followed by a scheme-specific part. For URIs that follow the * "generic URI" syntax, the scheme-specific part begins with two * slashes ("//") and may be followed by an authority segment (comprised * of user information, host, and port), path segment, query segment * and fragment. Note that RFC 2396 no longer specifies the use of the * parameters segment and excludes the "user:password" syntax as part of * the authority segment. If "user:password" appears in a URI, the entire * user/password string is stored as userinfo. * <p> * For URIs that do not follow the "generic URI" syntax (e.g. mailto), * the entire scheme-specific part is treated as the "path" portion * of the URI. * <p> * Note that, unlike the java.net.URL class, this class does not provide * any built-in network access functionality nor does it provide any * scheme-specific functionality (for example, it does not know a * default port for a specific scheme). Rather, it only knows the * grammar and basic set of operations that can be applied to a URI. * * @version $Id$ * **********************************************************************/ public class URI implements Serializable { /******************************************************************* * MalformedURIExceptions are thrown in the process of building a URI * or setting fields on a URI when an operation would result in an * invalid URI specification. * ********************************************************************/ public static class MalformedURIException extends IOException { /****************************************************************** * Constructs a <code>MalformedURIException</code> with no specified * detail message. ******************************************************************/ public MalformedURIException() { super(); } /***************************************************************** * Constructs a <code>MalformedURIException</code> with the * specified detail message. * * @param p_msg the detail message. ******************************************************************/ public MalformedURIException(String p_msg) { super(p_msg); } } private static final byte [] fgLookupTable = new byte[128]; /** * Character Classes */ /** reserved characters ;/?:@&=+$,[] */ //RFC 2732 added '[' and ']' as reserved characters private static final int RESERVED_CHARACTERS = 0x01; /** URI punctuation mark characters: -_.!~*'() - these, combined with alphanumerics, constitute the "unreserved" characters */ private static final int MARK_CHARACTERS = 0x02; /** scheme can be composed of alphanumerics and these characters: +-. */ private static final int SCHEME_CHARACTERS = 0x04; /** userinfo can be composed of unreserved, escaped and these characters: ;:&=+$, */ private static final int USERINFO_CHARACTERS = 0x08; /** ASCII letter characters */ private static final int ASCII_ALPHA_CHARACTERS = 0x10; /** ASCII digit characters */ private static final int ASCII_DIGIT_CHARACTERS = 0x20; /** ASCII hex characters */ private static final int ASCII_HEX_CHARACTERS = 0x40; /** Path characters */ private static final int PATH_CHARACTERS = 0x80; /** Mask for alpha-numeric characters */ private static final int MASK_ALPHA_NUMERIC = ASCII_ALPHA_CHARACTERS | ASCII_DIGIT_CHARACTERS; /** Mask for unreserved characters */ private static final int MASK_UNRESERVED_MASK = MASK_ALPHA_NUMERIC | MARK_CHARACTERS; /** Mask for URI allowable characters except for % */ private static final int MASK_URI_CHARACTER = MASK_UNRESERVED_MASK | RESERVED_CHARACTERS; /** Mask for scheme characters */ private static final int MASK_SCHEME_CHARACTER = MASK_ALPHA_NUMERIC | SCHEME_CHARACTERS; /** Mask for userinfo characters */ private static final int MASK_USERINFO_CHARACTER = MASK_UNRESERVED_MASK | USERINFO_CHARACTERS; /** Mask for path characters */ private static final int MASK_PATH_CHARACTER = MASK_UNRESERVED_MASK | PATH_CHARACTERS; static { // Add ASCII Digits and ASCII Hex Numbers for (int i = '0'; i <= '9'; ++i) { fgLookupTable[i] |= ASCII_DIGIT_CHARACTERS | ASCII_HEX_CHARACTERS; } // Add ASCII Letters and ASCII Hex Numbers for (int i = 'A'; i <= 'F'; ++i) { fgLookupTable[i] |= ASCII_ALPHA_CHARACTERS | ASCII_HEX_CHARACTERS; fgLookupTable[i+0x00000020] |= ASCII_ALPHA_CHARACTERS | ASCII_HEX_CHARACTERS; } // Add ASCII Letters for (int i = 'G'; i <= 'Z'; ++i) { fgLookupTable[i] |= ASCII_ALPHA_CHARACTERS; fgLookupTable[i+0x00000020] |= ASCII_ALPHA_CHARACTERS; } // Add Reserved Characters fgLookupTable[';'] |= RESERVED_CHARACTERS; fgLookupTable['/'] |= RESERVED_CHARACTERS; fgLookupTable['?'] |= RESERVED_CHARACTERS; fgLookupTable[':'] |= RESERVED_CHARACTERS; fgLookupTable['@'] |= RESERVED_CHARACTERS; fgLookupTable['&'] |= RESERVED_CHARACTERS; fgLookupTable['='] |= RESERVED_CHARACTERS; fgLookupTable['+'] |= RESERVED_CHARACTERS; fgLookupTable['$'] |= RESERVED_CHARACTERS; fgLookupTable[','] |= RESERVED_CHARACTERS; fgLookupTable['['] |= RESERVED_CHARACTERS; fgLookupTable[']'] |= RESERVED_CHARACTERS; // Add Mark Characters fgLookupTable['-'] |= MARK_CHARACTERS; fgLookupTable['_'] |= MARK_CHARACTERS; fgLookupTable['.'] |= MARK_CHARACTERS; fgLookupTable['!'] |= MARK_CHARACTERS; fgLookupTable['~'] |= MARK_CHARACTERS; fgLookupTable['*'] |= MARK_CHARACTERS; fgLookupTable['\''] |= MARK_CHARACTERS; fgLookupTable['('] |= MARK_CHARACTERS; fgLookupTable[')'] |= MARK_CHARACTERS; // Add Scheme Characters fgLookupTable['+'] |= SCHEME_CHARACTERS; fgLookupTable['-'] |= SCHEME_CHARACTERS; fgLookupTable['.'] |= SCHEME_CHARACTERS; // Add Userinfo Characters fgLookupTable[';'] |= USERINFO_CHARACTERS; fgLookupTable[':'] |= USERINFO_CHARACTERS; fgLookupTable['&'] |= USERINFO_CHARACTERS; fgLookupTable['='] |= USERINFO_CHARACTERS; fgLookupTable['+'] |= USERINFO_CHARACTERS; fgLookupTable['$'] |= USERINFO_CHARACTERS; fgLookupTable[','] |= USERINFO_CHARACTERS; // Add Path Characters fgLookupTable[';'] |= PATH_CHARACTERS; fgLookupTable['/'] |= PATH_CHARACTERS; fgLookupTable[':'] |= PATH_CHARACTERS; fgLookupTable['@'] |= PATH_CHARACTERS; fgLookupTable['&'] |= PATH_CHARACTERS; fgLookupTable['='] |= PATH_CHARACTERS; fgLookupTable['+'] |= PATH_CHARACTERS; fgLookupTable['$'] |= PATH_CHARACTERS; fgLookupTable[','] |= PATH_CHARACTERS; } /** Stores the scheme (usually the protocol) for this URI. */ private String m_scheme = null; /** If specified, stores the userinfo for this URI; otherwise null */ private String m_userinfo = null; /** If specified, stores the host for this URI; otherwise null */ private String m_host = null; /** If specified, stores the port for this URI; otherwise -1 */ private int m_port = -1; /** If specified, stores the registry based authority for this URI; otherwise -1 */ private String m_regAuthority = null; /** If specified, stores the path for this URI; otherwise null */ private String m_path = null; /** If specified, stores the query string for this URI; otherwise null. */ private String m_queryString = null; /** If specified, stores the fragment for this URI; otherwise null */ private String m_fragment = null; private static boolean DEBUG = false; /** * Construct a new and uninitialized URI. */ public URI() { } /** * Construct a new URI from another URI. All fields for this URI are * set equal to the fields of the URI passed in. * * @param p_other the URI to copy (cannot be null) */ public URI(URI p_other) { initialize(p_other); } /** * Construct a new URI from a URI specification string. If the * specification follows the "generic URI" syntax, (two slashes * following the first colon), the specification will be parsed * accordingly - setting the scheme, userinfo, host,port, path, query * string and fragment fields as necessary. If the specification does * not follow the "generic URI" syntax, the specification is parsed * into a scheme and scheme-specific part (stored as the path) only. * * @param p_uriSpec the URI specification string (cannot be null or * empty) * * @exception MalformedURIException if p_uriSpec violates any syntax * rules */ public URI(String p_uriSpec) throws MalformedURIException { this((URI)null, p_uriSpec); } /** * Construct a new URI from a base URI and a URI specification string. * The URI specification string may be a relative URI. * * @param p_base the base URI (cannot be null if p_uriSpec is null or * empty) * @param p_uriSpec the URI specification string (cannot be null or * empty if p_base is null) * * @exception MalformedURIException if p_uriSpec violates any syntax * rules */ public URI(URI p_base, String p_uriSpec) throws MalformedURIException { initialize(p_base, p_uriSpec); } /** * Construct a new URI that does not follow the generic URI syntax. * Only the scheme and scheme-specific part (stored as the path) are * initialized. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_schemeSpecificPart the scheme-specific part (cannot be * null or empty) * * @exception MalformedURIException if p_scheme violates any * syntax rules */ public URI(String p_scheme, String p_schemeSpecificPart) throws MalformedURIException { if (p_scheme == null || p_scheme.trim().length() == 0) { throw new MalformedURIException( "Cannot construct URI with null/empty scheme!"); } if (p_schemeSpecificPart == null || p_schemeSpecificPart.trim().length() == 0) { throw new MalformedURIException( "Cannot construct URI with null/empty scheme-specific part!"); } setScheme(p_scheme); setPath(p_schemeSpecificPart); } /** * Construct a new URI that follows the generic URI syntax from its * component parts. Each component is validated for syntax and some * basic semantic checks are performed as well. See the individual * setter methods for specifics. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_host the hostname, IPv4 address or IPv6 reference for the URI * @param p_path the URI path - if the path contains '?' or '#', * then the query string and/or fragment will be * set from the path; however, if the query and * fragment are specified both in the path and as * separate parameters, an exception is thrown * @param p_queryString the URI query string (cannot be specified * if path is null) * @param p_fragment the URI fragment (cannot be specified if path * is null) * * @exception MalformedURIException if any of the parameters violates * syntax rules or semantic rules */ public URI(String p_scheme, String p_host, String p_path, String p_queryString, String p_fragment) throws MalformedURIException { this(p_scheme, null, p_host, -1, p_path, p_queryString, p_fragment); } /** * Construct a new URI that follows the generic URI syntax from its * component parts. Each component is validated for syntax and some * basic semantic checks are performed as well. See the individual * setter methods for specifics. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_userinfo the URI userinfo (cannot be specified if host * is null) * @param p_host the hostname, IPv4 address or IPv6 reference for the URI * @param p_port the URI port (may be -1 for "unspecified"; cannot * be specified if host is null) * @param p_path the URI path - if the path contains '?' or '#', * then the query string and/or fragment will be * set from the path; however, if the query and * fragment are specified both in the path and as * separate parameters, an exception is thrown * @param p_queryString the URI query string (cannot be specified * if path is null) * @param p_fragment the URI fragment (cannot be specified if path * is null) * * @exception MalformedURIException if any of the parameters violates * syntax rules or semantic rules */ public URI(String p_scheme, String p_userinfo, String p_host, int p_port, String p_path, String p_queryString, String p_fragment) throws MalformedURIException { if (p_scheme == null || p_scheme.trim().length() == 0) { throw new MalformedURIException("Scheme is required!"); } if (p_host == null) { if (p_userinfo != null) { throw new MalformedURIException( "Userinfo may not be specified if host is not specified!"); } if (p_port != -1) { throw new MalformedURIException( "Port may not be specified if host is not specified!"); } } if (p_path != null) { if (p_path.indexOf('?') != -1 && p_queryString != null) { throw new MalformedURIException( "Query string cannot be specified in path and query string!"); } if (p_path.indexOf('#') != -1 && p_fragment != null) { throw new MalformedURIException( "Fragment cannot be specified in both the path and fragment!"); } } setScheme(p_scheme); setHost(p_host); setPort(p_port); setUserinfo(p_userinfo); setPath(p_path); setQueryString(p_queryString); setFragment(p_fragment); } /** * Initialize all fields of this URI from another URI. * * @param p_other the URI to copy (cannot be null) */ private void initialize(URI p_other) { m_scheme = p_other.getScheme(); m_userinfo = p_other.getUserinfo(); m_host = p_other.getHost(); m_port = p_other.getPort(); m_regAuthority = p_other.getRegBasedAuthority(); m_path = p_other.getPath(); m_queryString = p_other.getQueryString(); m_fragment = p_other.getFragment(); } /** * Initializes this URI from a base URI and a URI specification string. * See RFC 2396 Section 4 and Appendix B for specifications on parsing * the URI and Section 5 for specifications on resolving relative URIs * and relative paths. * * @param p_base the base URI (may be null if p_uriSpec is an absolute * URI) * @param p_uriSpec the URI spec string which may be an absolute or * relative URI (can only be null/empty if p_base * is not null) * * @exception MalformedURIException if p_base is null and p_uriSpec * is not an absolute URI or if * p_uriSpec violates syntax rules */ private void initialize(URI p_base, String p_uriSpec) throws MalformedURIException { - String uriSpec = (p_uriSpec != null) ? p_uriSpec.trim() : null; + String uriSpec = p_uriSpec; int uriSpecLen = (uriSpec != null) ? uriSpec.length() : 0; if (p_base == null && uriSpecLen == 0) { throw new MalformedURIException( "Cannot initialize URI with empty parameters."); } // just make a copy of the base if spec is empty if (uriSpecLen == 0) { initialize(p_base); return; } int index = 0; // Check for scheme, which must be before '/', '?' or '#'. Also handle // names with DOS drive letters ('D:'), so 1-character schemes are not // allowed. int colonIdx = uriSpec.indexOf(':'); int slashIdx = uriSpec.indexOf('/'); int queryIdx = uriSpec.indexOf('?'); int fragmentIdx = uriSpec.indexOf('#'); if ((colonIdx < 2) || (colonIdx > slashIdx && slashIdx != -1) || (colonIdx > queryIdx && queryIdx != -1) || (colonIdx > fragmentIdx && fragmentIdx != -1)) { // A standalone base is a valid URI according to spec if (colonIdx == 0 || (p_base == null && fragmentIdx != 0)) { throw new MalformedURIException("No scheme found in URI."); } } else { initializeScheme(uriSpec); index = m_scheme.length()+1; // Neither 'scheme:' or 'scheme:#fragment' are valid URIs. if (colonIdx == uriSpecLen - 1 || uriSpec.charAt(colonIdx+1) == '#') { throw new MalformedURIException("Scheme specific part cannot be empty."); } } // Two slashes means we may have authority, but definitely means we're either // matching net_path or abs_path. These two productions are ambiguous in that // every net_path (except those containing an IPv6Reference) is an abs_path. // RFC 2396 resolves this ambiguity by applying a greedy left most matching rule. // Try matching net_path first, and if that fails we don't have authority so // then attempt to match abs_path. // // net_path = "//" authority [ abs_path ] // abs_path = "/" path_segments if (((index+1) < uriSpecLen) && (uriSpec.charAt(index) == '/' && uriSpec.charAt(index+1) == '/')) { index += 2; int startPos = index; // Authority will be everything up to path, query or fragment char testChar = '\0'; while (index < uriSpecLen) { testChar = uriSpec.charAt(index); if (testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } // Attempt to parse authority. If the section is an empty string // this is a valid server based authority, so set the host to this // value. if (index > startPos) { // If we didn't find authority we need to back up. Attempt to // match against abs_path next. if (!initializeAuthority(uriSpec.substring(startPos, index))) { index = startPos - 2; } } else { m_host = ""; } } initializePath(uriSpec, index); // Resolve relative URI to base URI - see RFC 2396 Section 5.2 // In some cases, it might make more sense to throw an exception // (when scheme is specified is the string spec and the base URI // is also specified, for example), but we're just following the // RFC specifications if (p_base != null) { // check to see if this is the current doc - RFC 2396 5.2 #2 // note that this is slightly different from the RFC spec in that // we don't include the check for query string being null // - this handles cases where the urispec is just a query // string or a fragment (e.g. "?y" or "#s") - // see <http://www.ics.uci.edu/~fielding/url/test1.html> which // identified this as a bug in the RFC if (m_path.length() == 0 && m_scheme == null && m_host == null && m_regAuthority == null) { m_scheme = p_base.getScheme(); m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_regAuthority = p_base.getRegBasedAuthority(); m_path = p_base.getPath(); if (m_queryString == null) { m_queryString = p_base.getQueryString(); } return; } // check for scheme - RFC 2396 5.2 #3 // if we found a scheme, it means absolute URI, so we're done if (m_scheme == null) { m_scheme = p_base.getScheme(); } else { return; } // check for authority - RFC 2396 5.2 #4 // if we found a host, then we've got a network path, so we're done if (m_host == null && m_regAuthority == null) { m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_regAuthority = p_base.getRegBasedAuthority(); } else { return; } // check for absolute path - RFC 2396 5.2 #5 if (m_path.length() > 0 && m_path.startsWith("/")) { return; } // if we get to this point, we need to resolve relative path // RFC 2396 5.2 #6 String path = ""; String basePath = p_base.getPath(); // 6a - get all but the last segment of the base URI path if (basePath != null && basePath.length() > 0) { int lastSlash = basePath.lastIndexOf('/'); if (lastSlash != -1) { path = basePath.substring(0, lastSlash+1); } } else if (m_path.length() > 0) { path = "/"; } // 6b - append the relative URI path path = path.concat(m_path); // 6c - remove all "./" where "." is a complete path segment index = -1; while ((index = path.indexOf("/./")) != -1) { path = path.substring(0, index+1).concat(path.substring(index+3)); } // 6d - remove "." if path ends with "." as a complete path segment if (path.endsWith("/.")) { path = path.substring(0, path.length()-1); } // 6e - remove all "<segment>/../" where "<segment>" is a complete // path segment not equal to ".." index = 1; int segIndex = -1; String tempString = null; while ((index = path.indexOf("/../", index)) > 0) { tempString = path.substring(0, path.indexOf("/../")); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { if (!tempString.substring(segIndex).equals("..")) { path = path.substring(0, segIndex+1).concat(path.substring(index+4)); index = segIndex; } else index += 4; } else index += 4; } // 6f - remove ending "<segment>/.." where "<segment>" is a // complete path segment if (path.endsWith("/..")) { tempString = path.substring(0, path.length()-3); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { path = path.substring(0, segIndex+1); } } m_path = path; } } /** * Initialize the scheme for this URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * * @exception MalformedURIException if URI does not have a conformant * scheme */ private void initializeScheme(String p_uriSpec) throws MalformedURIException { int uriSpecLen = p_uriSpec.length(); int index = 0; String scheme = null; char testChar = '\0'; while (index < uriSpecLen) { testChar = p_uriSpec.charAt(index); if (testChar == ':' || testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } scheme = p_uriSpec.substring(0, index); if (scheme.length() == 0) { throw new MalformedURIException("No scheme found in URI."); } else { setScheme(scheme); } } /** * Initialize the authority (either server or registry based) * for this URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * * @return true if the given string matched server or registry * based authority */ private boolean initializeAuthority(String p_uriSpec) { int index = 0; int start = 0; int end = p_uriSpec.length(); char testChar = '\0'; String userinfo = null; // userinfo is everything up to @ if (p_uriSpec.indexOf('@', start) != -1) { while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '@') { break; } index++; } userinfo = p_uriSpec.substring(start, index); index++; } // host is everything up to last ':', or up to // and including ']' if followed by ':'. String host = null; start = index; boolean hasPort = false; if (index < end) { if (p_uriSpec.charAt(start) == '[') { int bracketIndex = p_uriSpec.indexOf(']', start); index = (bracketIndex != -1) ? bracketIndex : end; if (index+1 < end && p_uriSpec.charAt(index+1) == ':') { ++index; hasPort = true; } else { index = end; } } else { int colonIndex = p_uriSpec.lastIndexOf(':', end); index = (colonIndex > start) ? colonIndex : end; hasPort = (index != end); } } host = p_uriSpec.substring(start, index); int port = -1; if (host.length() > 0) { // port if (hasPort) { index++; start = index; while (index < end) { index++; } String portStr = p_uriSpec.substring(start, index); if (portStr.length() > 0) { // REVISIT: Remove this code. /** for (int i = 0; i < portStr.length(); i++) { if (!isDigit(portStr.charAt(i))) { throw new MalformedURIException( portStr + " is invalid. Port should only contain digits!"); } }**/ // REVISIT: Remove this code. // Store port value as string instead of integer. try { port = Integer.parseInt(portStr); if (port == -1) --port; } catch (NumberFormatException nfe) { port = -2; } } } } if (isValidServerBasedAuthority(host, port, userinfo)) { m_host = host; m_port = port; m_userinfo = userinfo; return true; } // Note: Registry based authority is being removed from a // new spec for URI which would obsolete RFC 2396. If the // spec is added to XML errata, processing of reg_name // needs to be removed. - mrglavas. else if (isValidRegistryBasedAuthority(p_uriSpec)) { m_regAuthority = p_uriSpec; return true; } return false; } /** * Determines whether the components host, port, and user info * are valid as a server authority. * * @param host the host component of authority * @param port the port number component of authority * @param userinfo the user info component of authority * * @return true if the given host, port, and userinfo compose * a valid server authority */ private boolean isValidServerBasedAuthority(String host, int port, String userinfo) { // Check if the host is well formed. if (!isWellFormedAddress(host)) { return false; } // Check that port is well formed if it exists. // REVISIT: There's no restriction on port value ranges, but // perform the same check as in setPort to be consistent. Pass // in a string to this method instead of an integer. if (port < -1 || port > 65535) { return false; } // Check that userinfo is well formed if it exists. if (userinfo != null) { // Userinfo can contain alphanumerics, mark characters, escaped // and ';',':','&','=','+','$',',' int index = 0; int end = userinfo.length(); char testChar = '\0'; while (index < end) { testChar = userinfo.charAt(index); if (testChar == '%') { if (index+2 >= end || !isHex(userinfo.charAt(index+1)) || !isHex(userinfo.charAt(index+2))) { return false; } index += 2; } else if (!isUserinfoCharacter(testChar)) { return false; } ++index; } } return true; } /** * Determines whether the given string is a registry based authority. * * @param authority the authority component of a URI * * @return true if the given string is a registry based authority */ private boolean isValidRegistryBasedAuthority(String authority) { int index = 0; int end = authority.length(); char testChar; while (index < end) { testChar = authority.charAt(index); // check for valid escape sequence if (testChar == '%') { if (index+2 >= end || !isHex(authority.charAt(index+1)) || !isHex(authority.charAt(index+2))) { return false; } index += 2; } // can check against path characters because the set // is the same except for '/' which we've already excluded. else if (!isPathCharacter(testChar)) { return false; } ++index; } return true; } /** * Initialize the path for this URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * @param p_nStartIndex the index to begin scanning from * * @exception MalformedURIException if p_uriSpec violates syntax rules */ private void initializePath(String p_uriSpec, int p_nStartIndex) throws MalformedURIException { if (p_uriSpec == null) { throw new MalformedURIException( "Cannot initialize path from null string!"); } int index = p_nStartIndex; int start = p_nStartIndex; int end = p_uriSpec.length(); char testChar = '\0'; // path - everything up to query string or fragment if (start < end) { // RFC 2732 only allows '[' and ']' to appear in the opaque part. if (getScheme() == null || p_uriSpec.charAt(start) == '/') { // Scan path. // abs_path = "/" path_segments // rel_path = rel_segment [ abs_path ] while (index < end) { testChar = p_uriSpec.charAt(index); // check for valid escape sequence if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Path contains invalid escape sequence!"); } index += 2; } // Path segments cannot contain '[' or ']' since pchar // production was not changed by RFC 2732. else if (!isPathCharacter(testChar)) { if (testChar == '?' || testChar == '#') { break; } throw new MalformedURIException( "Path contains invalid character: " + testChar); } ++index; } } else { // Scan opaque part. // opaque_part = uric_no_slash *uric while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '?' || testChar == '#') { break; } // check for valid escape sequence if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Opaque part contains invalid escape sequence!"); } index += 2; } // If the scheme specific part is opaque, it can contain '[' // and ']'. uric_no_slash wasn't modified by RFC 2732, which // I've interpreted as an error in the spec, since the // production should be equivalent to (uric - '/'), and uric // contains '[' and ']'. - mrglavas else if (!isURICharacter(testChar)) { throw new MalformedURIException( "Opaque part contains invalid character: " + testChar); } ++index; } } } m_path = p_uriSpec.substring(start, index); // query - starts with ? and up to fragment or end if (testChar == '?') { index++; start = index; while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '#') { break; } if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Query string contains invalid escape sequence!"); } index += 2; } else if (!isURICharacter(testChar)) { throw new MalformedURIException( "Query string contains invalid character: " + testChar); } index++; } m_queryString = p_uriSpec.substring(start, index); } // fragment - starts with # if (testChar == '#') { index++; start = index; while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Fragment contains invalid escape sequence!"); } index += 2; } else if (!isURICharacter(testChar)) { throw new MalformedURIException( "Fragment contains invalid character: "+testChar); } index++; } m_fragment = p_uriSpec.substring(start, index); } } /** * Get the scheme for this URI. * * @return the scheme for this URI */ public String getScheme() { return m_scheme; } /** * Get the scheme-specific part for this URI (everything following the * scheme and the first colon). See RFC 2396 Section 5.2 for spec. * * @return the scheme-specific part for this URI */ public String getSchemeSpecificPart() { StringBuffer schemespec = new StringBuffer(); if (m_host != null || m_regAuthority != null) { schemespec.append("//"); // Server based authority. if (m_host != null) { if (m_userinfo != null) { schemespec.append(m_userinfo); schemespec.append('@'); } schemespec.append(m_host); if (m_port != -1) { schemespec.append(':'); schemespec.append(m_port); } } // Registry based authority. else { schemespec.append(m_regAuthority); } } if (m_path != null) { schemespec.append((m_path)); } if (m_queryString != null) { schemespec.append('?'); schemespec.append(m_queryString); } if (m_fragment != null) { schemespec.append('#'); schemespec.append(m_fragment); } return schemespec.toString(); } /** * Get the userinfo for this URI. * * @return the userinfo for this URI (null if not specified). */ public String getUserinfo() { return m_userinfo; } /** * Get the host for this URI. * * @return the host for this URI (null if not specified). */ public String getHost() { return m_host; } /** * Get the port for this URI. * * @return the port for this URI (-1 if not specified). */ public int getPort() { return m_port; } /** * Get the registry based authority for this URI. * * @return the registry based authority (null if not specified). */ public String getRegBasedAuthority() { return m_regAuthority; } /** * Get the path for this URI (optionally with the query string and * fragment). * * @param p_includeQueryString if true (and query string is not null), * then a "?" followed by the query string * will be appended * @param p_includeFragment if true (and fragment is not null), * then a "#" followed by the fragment * will be appended * * @return the path for this URI possibly including the query string * and fragment */ public String getPath(boolean p_includeQueryString, boolean p_includeFragment) { StringBuffer pathString = new StringBuffer(m_path); if (p_includeQueryString && m_queryString != null) { pathString.append('?'); pathString.append(m_queryString); } if (p_includeFragment && m_fragment != null) { pathString.append('#'); pathString.append(m_fragment); } return pathString.toString(); } /** * Get the path for this URI. Note that the value returned is the path * only and does not include the query string or fragment. * * @return the path for this URI. */ public String getPath() { return m_path; } /** * Get the query string for this URI. * * @return the query string for this URI. Null is returned if there * was no "?" in the URI spec, empty string if there was a * "?" but no query string following it. */ public String getQueryString() { return m_queryString; } /** * Get the fragment for this URI. * * @return the fragment for this URI. Null is returned if there * was no "#" in the URI spec, empty string if there was a * "#" but no fragment following it. */ public String getFragment() { return m_fragment; } /** * Set the scheme for this URI. The scheme is converted to lowercase * before it is set. * * @param p_scheme the scheme for this URI (cannot be null) * * @exception MalformedURIException if p_scheme is not a conformant * scheme name */ public void setScheme(String p_scheme) throws MalformedURIException { if (p_scheme == null) { throw new MalformedURIException( "Cannot set scheme from null string!"); } if (!isConformantSchemeName(p_scheme)) { throw new MalformedURIException("The scheme is not conformant."); } m_scheme = p_scheme.toLowerCase(); } /** * Set the userinfo for this URI. If a non-null value is passed in and * the host value is null, then an exception is thrown. * * @param p_userinfo the userinfo for this URI * * @exception MalformedURIException if p_userinfo contains invalid * characters */ public void setUserinfo(String p_userinfo) throws MalformedURIException { if (p_userinfo == null) { m_userinfo = null; return; } else { if (m_host == null) { throw new MalformedURIException( "Userinfo cannot be set when host is null!"); } // userinfo can contain alphanumerics, mark characters, escaped // and ';',':','&','=','+','$',',' int index = 0; int end = p_userinfo.length(); char testChar = '\0'; while (index < end) { testChar = p_userinfo.charAt(index); if (testChar == '%') { if (index+2 >= end || !isHex(p_userinfo.charAt(index+1)) || !isHex(p_userinfo.charAt(index+2))) { throw new MalformedURIException( "Userinfo contains invalid escape sequence!"); } } else if (!isUserinfoCharacter(testChar)) { throw new MalformedURIException( "Userinfo contains invalid character:"+testChar); } index++; } } m_userinfo = p_userinfo; } /** * <p>Set the host for this URI. If null is passed in, the userinfo * field is also set to null and the port is set to -1.</p> * * <p>Note: This method overwrites registry based authority if it * previously existed in this URI.</p> * * @param p_host the host for this URI * * @exception MalformedURIException if p_host is not a valid IP * address or DNS hostname. */ public void setHost(String p_host) throws MalformedURIException { if (p_host == null || p_host.length() == 0) { if (p_host != null) { m_regAuthority = null; } m_host = p_host; m_userinfo = null; m_port = -1; return; } else if (!isWellFormedAddress(p_host)) { throw new MalformedURIException("Host is not a well formed address!"); } m_host = p_host; m_regAuthority = null; } /** * Set the port for this URI. -1 is used to indicate that the port is * not specified, otherwise valid port numbers are between 0 and 65535. * If a valid port number is passed in and the host field is null, * an exception is thrown. * * @param p_port the port number for this URI * * @exception MalformedURIException if p_port is not -1 and not a * valid port number */ public void setPort(int p_port) throws MalformedURIException { if (p_port >= 0 && p_port <= 65535) { if (m_host == null) { throw new MalformedURIException( "Port cannot be set when host is null!"); } } else if (p_port != -1) { throw new MalformedURIException("Invalid port number!"); } m_port = p_port; } /** * <p>Sets the registry based authority for this URI.</p> * * <p>Note: This method overwrites server based authority * if it previously existed in this URI.</p> * * @param authority the registry based authority for this URI * * @exception MalformedURIException it authority is not a * well formed registry based authority */ public void setRegBasedAuthority(String authority) throws MalformedURIException { if (authority == null) { m_regAuthority = null; return; } // reg_name = 1*( unreserved | escaped | "$" | "," | // ";" | ":" | "@" | "&" | "=" | "+" ) else if (authority.length() < 1 || !isValidRegistryBasedAuthority(authority) || authority.indexOf('/') != -1) { throw new MalformedURIException("Registry based authority is not well formed."); } m_regAuthority = authority; m_host = null; m_userinfo = null; m_port = -1; } /** * Set the path for this URI. If the supplied path is null, then the * query string and fragment are set to null as well. If the supplied * path includes a query string and/or fragment, these fields will be * parsed and set as well. Note that, for URIs following the "generic * URI" syntax, the path specified should start with a slash. * For URIs that do not follow the generic URI syntax, this method * sets the scheme-specific part. * * @param p_path the path for this URI (may be null) * * @exception MalformedURIException if p_path contains invalid * characters */ public void setPath(String p_path) throws MalformedURIException { if (p_path == null) { m_path = null; m_queryString = null; m_fragment = null; } else { initializePath(p_path, 0); } } /** * Append to the end of the path of this URI. If the current path does * not end in a slash and the path to be appended does not begin with * a slash, a slash will be appended to the current path before the * new segment is added. Also, if the current path ends in a slash * and the new segment begins with a slash, the extra slash will be * removed before the new segment is appended. * * @param p_addToPath the new segment to be added to the current path * * @exception MalformedURIException if p_addToPath contains syntax * errors */ public void appendPath(String p_addToPath) throws MalformedURIException { if (p_addToPath == null || p_addToPath.trim().length() == 0) { return; } if (!isURIString(p_addToPath)) { throw new MalformedURIException( "Path contains invalid character!"); } if (m_path == null || m_path.trim().length() == 0) { if (p_addToPath.startsWith("/")) { m_path = p_addToPath; } else { m_path = "/" + p_addToPath; } } else if (m_path.endsWith("/")) { if (p_addToPath.startsWith("/")) { m_path = m_path.concat(p_addToPath.substring(1)); } else { m_path = m_path.concat(p_addToPath); } } else { if (p_addToPath.startsWith("/")) { m_path = m_path.concat(p_addToPath); } else { m_path = m_path.concat("/" + p_addToPath); } } } /** * Set the query string for this URI. A non-null value is valid only * if this is an URI conforming to the generic URI syntax and * the path value is not null. * * @param p_queryString the query string for this URI * * @exception MalformedURIException if p_queryString is not null and this * URI does not conform to the generic * URI syntax or if the path is null */ public void setQueryString(String p_queryString) throws MalformedURIException { if (p_queryString == null) { m_queryString = null; } else if (!isGenericURI()) { throw new MalformedURIException( "Query string can only be set for a generic URI!"); } else if (getPath() == null) { throw new MalformedURIException( "Query string cannot be set when path is null!"); } else if (!isURIString(p_queryString)) { throw new MalformedURIException( "Query string contains invalid character!"); } else { m_queryString = p_queryString; } } /** * Set the fragment for this URI. A non-null value is valid only * if this is a URI conforming to the generic URI syntax and * the path value is not null. * * @param p_fragment the fragment for this URI * * @exception MalformedURIException if p_fragment is not null and this * URI does not conform to the generic * URI syntax or if the path is null */ public void setFragment(String p_fragment) throws MalformedURIException { if (p_fragment == null) { m_fragment = null; } else if (!isGenericURI()) { throw new MalformedURIException( "Fragment can only be set for a generic URI!"); } else if (getPath() == null) { throw new MalformedURIException( "Fragment cannot be set when path is null!"); } else if (!isURIString(p_fragment)) { throw new MalformedURIException( "Fragment contains invalid character!"); } else { m_fragment = p_fragment; } } /** * Determines if the passed-in Object is equivalent to this URI. * * @param p_test the Object to test for equality. * * @return true if p_test is a URI with all values equal to this * URI, false otherwise */ public boolean equals(Object p_test) { if (p_test instanceof URI) { URI testURI = (URI) p_test; if (((m_scheme == null && testURI.m_scheme == null) || (m_scheme != null && testURI.m_scheme != null && m_scheme.equals(testURI.m_scheme))) && ((m_userinfo == null && testURI.m_userinfo == null) || (m_userinfo != null && testURI.m_userinfo != null && m_userinfo.equals(testURI.m_userinfo))) && ((m_host == null && testURI.m_host == null) || (m_host != null && testURI.m_host != null && m_host.equals(testURI.m_host))) && m_port == testURI.m_port && ((m_path == null && testURI.m_path == null) || (m_path != null && testURI.m_path != null && m_path.equals(testURI.m_path))) && ((m_queryString == null && testURI.m_queryString == null) || (m_queryString != null && testURI.m_queryString != null && m_queryString.equals(testURI.m_queryString))) && ((m_fragment == null && testURI.m_fragment == null) || (m_fragment != null && testURI.m_fragment != null && m_fragment.equals(testURI.m_fragment)))) { return true; } } return false; } /** * Get the URI as a string specification. See RFC 2396 Section 5.2. * * @return the URI string specification */ public String toString() { StringBuffer uriSpecString = new StringBuffer(); if (m_scheme != null) { uriSpecString.append(m_scheme); uriSpecString.append(':'); } uriSpecString.append(getSchemeSpecificPart()); return uriSpecString.toString(); } /** * Get the indicator as to whether this URI uses the "generic URI" * syntax. * * @return true if this URI uses the "generic URI" syntax, false * otherwise */ public boolean isGenericURI() { // presence of the host (whether valid or empty) means // double-slashes which means generic uri return (m_host != null); } /** * Determine whether a scheme conforms to the rules for a scheme name. * A scheme is conformant if it starts with an alphanumeric, and * contains only alphanumerics, '+','-' and '.'. * * @return true if the scheme is conformant, false otherwise */ public static boolean isConformantSchemeName(String p_scheme) { if (p_scheme == null || p_scheme.trim().length() == 0) { return false; } if (!isAlpha(p_scheme.charAt(0))) { return false; } char testChar; int schemeLength = p_scheme.length(); for (int i = 1; i < schemeLength; ++i) { testChar = p_scheme.charAt(i); if (!isSchemeCharacter(testChar)) { return false; } } return true; } /** * Determine whether a string is syntactically capable of representing * a valid IPv4 address, IPv6 reference or the domain name of a network host. * A valid IPv4 address consists of four decimal digit groups separated by a * '.'. Each group must consist of one to three digits. See RFC 2732 Section 3, * and RFC 2373 Section 2.2, for the definition of IPv6 references. A hostname * consists of domain labels (each of which must begin and end with an alphanumeric * but may contain '-') separated & by a '.'. See RFC 2396 Section 3.2.2. * * @return true if the string is a syntactically valid IPv4 address, * IPv6 reference or hostname */ public static boolean isWellFormedAddress(String address) { if (address == null) { return false; } int addrLength = address.length(); if (addrLength == 0) { return false; } // Check if the host is a valid IPv6reference. if (address.startsWith("[")) { return isWellFormedIPv6Reference(address); } // Cannot start with a '.', '-', or end with a '-'. if (address.startsWith(".") || address.startsWith("-") || address.endsWith("-")) { return false; } // rightmost domain label starting with digit indicates IP address // since top level domain label can only start with an alpha // see RFC 2396 Section 3.2.2 int index = address.lastIndexOf('.'); if (address.endsWith(".")) { index = address.substring(0, index).lastIndexOf('.'); } if (index+1 < addrLength && isDigit(address.charAt(index+1))) { return isWellFormedIPv4Address(address); } else { // hostname = *( domainlabel "." ) toplabel [ "." ] // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum // toplabel = alpha | alpha *( alphanum | "-" ) alphanum // RFC 2396 states that hostnames take the form described in // RFC 1034 (Section 3) and RFC 1123 (Section 2.1). According // to RFC 1034, hostnames are limited to 255 characters. if (addrLength > 255) { return false; } // domain labels can contain alphanumerics and '-" // but must start and end with an alphanumeric char testChar; int labelCharCount = 0; for (int i = 0; i < addrLength; i++) { testChar = address.charAt(i); if (testChar == '.') { if (!isAlphanum(address.charAt(i-1))) { return false; } if (i+1 < addrLength && !isAlphanum(address.charAt(i+1))) { return false; } labelCharCount = 0; } else if (!isAlphanum(testChar) && testChar != '-') { return false; } // RFC 1034: Labels must be 63 characters or less. else if (++labelCharCount > 63) { return false; } } } return true; } /** * <p>Determines whether a string is an IPv4 address as defined by * RFC 2373, and under the further constraint that it must be a 32-bit * address. Though not expressed in the grammar, in order to satisfy * the 32-bit address constraint, each segment of the address cannot * be greater than 255 (8 bits of information).</p> * * <p><code>IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT</code></p> * * @return true if the string is a syntactically valid IPv4 address */ public static boolean isWellFormedIPv4Address(String address) { int addrLength = address.length(); char testChar; int numDots = 0; int numDigits = 0; // make sure that 1) we see only digits and dot separators, 2) that // any dot separator is preceded and followed by a digit and // 3) that we find 3 dots // // RFC 2732 amended RFC 2396 by replacing the definition // of IPv4address with the one defined by RFC 2373. - mrglavas // // IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT // // One to three digits must be in each segment. for (int i = 0; i < addrLength; i++) { testChar = address.charAt(i); if (testChar == '.') { if ((i > 0 && !isDigit(address.charAt(i-1))) || (i+1 < addrLength && !isDigit(address.charAt(i+1)))) { return false; } numDigits = 0; if (++numDots > 3) { return false; } } else if (!isDigit(testChar)) { return false; } // Check that that there are no more than three digits // in this segment. else if (++numDigits > 3) { return false; } // Check that this segment is not greater than 255. else if (numDigits == 3) { char first = address.charAt(i-2); char second = address.charAt(i-1); if (!(first < '2' || (first == '2' && (second < '5' || (second == '5' && testChar <= '5'))))) { return false; } } } return (numDots == 3); } /** * <p>Determines whether a string is an IPv6 reference as defined * by RFC 2732, where IPv6address is defined in RFC 2373. The * IPv6 address is parsed according to Section 2.2 of RFC 2373, * with the additional constraint that the address be composed of * 128 bits of information.</p> * * <p><code>IPv6reference = "[" IPv6address "]"</code></p> * * <p>Note: The BNF expressed in RFC 2373 Appendix B does not * accurately describe section 2.2, and was in fact removed from * RFC 3513, the successor of RFC 2373.</p> * * @return true if the string is a syntactically valid IPv6 reference */ public static boolean isWellFormedIPv6Reference(String address) { int addrLength = address.length(); int index = 1; int end = addrLength-1; // Check if string is a potential match for IPv6reference. if (!(addrLength > 2 && address.charAt(0) == '[' && address.charAt(end) == ']')) { return false; } // Counter for the number of 16-bit sections read in the address. int [] counter = new int[1]; // Scan hex sequence before possible '::' or IPv4 address. index = scanHexSequence(address, index, end, counter); if (index == -1) { return false; } // Address must contain 128-bits of information. else if (index == end) { return (counter[0] == 8); } if (index+1 < end && address.charAt(index) == ':') { if (address.charAt(index+1) == ':') { // '::' represents at least one 16-bit group of zeros. if (++counter[0] > 8) { return false; } index += 2; // Trailing zeros will fill out the rest of the address. if (index == end) { return true; } } // If the second character wasn't ':', in order to be valid, // the remainder of the string must match IPv4Address, // and we must have read exactly 6 16-bit groups. else { return (counter[0] == 6) && isWellFormedIPv4Address(address.substring(index+1, end)); } } else { return false; } // 3. Scan hex sequence after '::'. int prevCount = counter[0]; index = scanHexSequence(address, index, end, counter); // We've either reached the end of the string, the address ends in // an IPv4 address, or it is invalid. scanHexSequence has already // made sure that we have the right number of bits. return (index == end) || (index != -1 && isWellFormedIPv4Address( address.substring((counter[0] > prevCount) ? index+1 : index, end))); } /** * Helper method for isWellFormedIPv6Reference which scans the * hex sequences of an IPv6 address. It returns the index of the * next character to scan in the address, or -1 if the string * cannot match a valid IPv6 address. * * @param address the string to be scanned * @param index the beginning index (inclusive) * @param end the ending index (exclusive) * @param counter a counter for the number of 16-bit sections read * in the address * * @return the index of the next character to scan, or -1 if the * string cannot match a valid IPv6 address */ private static int scanHexSequence (String address, int index, int end, int [] counter) { char testChar; int numDigits = 0; int start = index; // Trying to match the following productions: // hexseq = hex4 *( ":" hex4) // hex4 = 1*4HEXDIG for (; index < end; ++index) { testChar = address.charAt(index); if (testChar == ':') { // IPv6 addresses are 128-bit, so there can be at most eight sections. if (numDigits > 0 && ++counter[0] > 8) { return -1; } // This could be '::'. if (numDigits == 0 || ((index+1 < end) && address.charAt(index+1) == ':')) { return index; } numDigits = 0; } // This might be invalid or an IPv4address. If it's potentially an IPv4address, // backup to just after the last valid character that matches hexseq. else if (!isHex(testChar)) { if (testChar == '.' && numDigits < 4 && numDigits > 0 && counter[0] <= 6) { int back = index - numDigits - 1; return (back >= start) ? back : (back+1); } return -1; } // There can be at most 4 hex digits per group. else if (++numDigits > 4) { return -1; } } return (numDigits > 0 && ++counter[0] <= 8) ? end : -1; } /** * Determine whether a char is a digit. * * @return true if the char is betweeen '0' and '9', false otherwise */ private static boolean isDigit(char p_char) { return p_char >= '0' && p_char <= '9'; } /** * Determine whether a character is a hexadecimal character. * * @return true if the char is betweeen '0' and '9', 'a' and 'f' * or 'A' and 'F', false otherwise */ private static boolean isHex(char p_char) { return (p_char <= 'f' && (fgLookupTable[p_char] & ASCII_HEX_CHARACTERS) != 0); } /** * Determine whether a char is an alphabetic character: a-z or A-Z * * @return true if the char is alphabetic, false otherwise */ private static boolean isAlpha(char p_char) { return ((p_char >= 'a' && p_char <= 'z') || (p_char >= 'A' && p_char <= 'Z' )); } /** * Determine whether a char is an alphanumeric: 0-9, a-z or A-Z * * @return true if the char is alphanumeric, false otherwise */ private static boolean isAlphanum(char p_char) { return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_ALPHA_NUMERIC) != 0); } /** * Determine whether a character is a reserved character: * ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '[', or ']' * * @return true if the string contains any reserved characters */ private static boolean isReservedCharacter(char p_char) { return (p_char <= ']' && (fgLookupTable[p_char] & RESERVED_CHARACTERS) != 0); } /** * Determine whether a char is an unreserved character. * * @return true if the char is unreserved, false otherwise */ private static boolean isUnreservedCharacter(char p_char) { return (p_char <= '~' && (fgLookupTable[p_char] & MASK_UNRESERVED_MASK) != 0); } /** * Determine whether a char is a URI character (reserved or * unreserved, not including '%' for escaped octets). * * @return true if the char is a URI character, false otherwise */ private static boolean isURICharacter (char p_char) { return (p_char <= '~' && (fgLookupTable[p_char] & MASK_URI_CHARACTER) != 0); } /** * Determine whether a char is a scheme character. * * @return true if the char is a scheme character, false otherwise */ private static boolean isSchemeCharacter (char p_char) { return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_SCHEME_CHARACTER) != 0); } /** * Determine whether a char is a userinfo character. * * @return true if the char is a userinfo character, false otherwise */ private static boolean isUserinfoCharacter (char p_char) { return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_USERINFO_CHARACTER) != 0); } /** * Determine whether a char is a path character. * * @return true if the char is a path character, false otherwise */ private static boolean isPathCharacter (char p_char) { return (p_char <= '~' && (fgLookupTable[p_char] & MASK_PATH_CHARACTER) != 0); } /** * Determine whether a given string contains only URI characters (also * called "uric" in RFC 2396). uric consist of all reserved * characters, unreserved characters and escaped characters. * * @return true if the string is comprised of uric, false otherwise */ private static boolean isURIString(String p_uric) { if (p_uric == null) { return false; } int end = p_uric.length(); char testChar = '\0'; for (int i = 0; i < end; i++) { testChar = p_uric.charAt(i); if (testChar == '%') { if (i+2 >= end || !isHex(p_uric.charAt(i+1)) || !isHex(p_uric.charAt(i+2))) { return false; } else { i += 2; continue; } } if (isURICharacter(testChar)) { continue; } else { return false; } } return true; } }
true
true
private void initialize(URI p_base, String p_uriSpec) throws MalformedURIException { String uriSpec = (p_uriSpec != null) ? p_uriSpec.trim() : null; int uriSpecLen = (uriSpec != null) ? uriSpec.length() : 0; if (p_base == null && uriSpecLen == 0) { throw new MalformedURIException( "Cannot initialize URI with empty parameters."); } // just make a copy of the base if spec is empty if (uriSpecLen == 0) { initialize(p_base); return; } int index = 0; // Check for scheme, which must be before '/', '?' or '#'. Also handle // names with DOS drive letters ('D:'), so 1-character schemes are not // allowed. int colonIdx = uriSpec.indexOf(':'); int slashIdx = uriSpec.indexOf('/'); int queryIdx = uriSpec.indexOf('?'); int fragmentIdx = uriSpec.indexOf('#'); if ((colonIdx < 2) || (colonIdx > slashIdx && slashIdx != -1) || (colonIdx > queryIdx && queryIdx != -1) || (colonIdx > fragmentIdx && fragmentIdx != -1)) { // A standalone base is a valid URI according to spec if (colonIdx == 0 || (p_base == null && fragmentIdx != 0)) { throw new MalformedURIException("No scheme found in URI."); } } else { initializeScheme(uriSpec); index = m_scheme.length()+1; // Neither 'scheme:' or 'scheme:#fragment' are valid URIs. if (colonIdx == uriSpecLen - 1 || uriSpec.charAt(colonIdx+1) == '#') { throw new MalformedURIException("Scheme specific part cannot be empty."); } } // Two slashes means we may have authority, but definitely means we're either // matching net_path or abs_path. These two productions are ambiguous in that // every net_path (except those containing an IPv6Reference) is an abs_path. // RFC 2396 resolves this ambiguity by applying a greedy left most matching rule. // Try matching net_path first, and if that fails we don't have authority so // then attempt to match abs_path. // // net_path = "//" authority [ abs_path ] // abs_path = "/" path_segments if (((index+1) < uriSpecLen) && (uriSpec.charAt(index) == '/' && uriSpec.charAt(index+1) == '/')) { index += 2; int startPos = index; // Authority will be everything up to path, query or fragment char testChar = '\0'; while (index < uriSpecLen) { testChar = uriSpec.charAt(index); if (testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } // Attempt to parse authority. If the section is an empty string // this is a valid server based authority, so set the host to this // value. if (index > startPos) { // If we didn't find authority we need to back up. Attempt to // match against abs_path next. if (!initializeAuthority(uriSpec.substring(startPos, index))) { index = startPos - 2; } } else { m_host = ""; } } initializePath(uriSpec, index); // Resolve relative URI to base URI - see RFC 2396 Section 5.2 // In some cases, it might make more sense to throw an exception // (when scheme is specified is the string spec and the base URI // is also specified, for example), but we're just following the // RFC specifications if (p_base != null) { // check to see if this is the current doc - RFC 2396 5.2 #2 // note that this is slightly different from the RFC spec in that // we don't include the check for query string being null // - this handles cases where the urispec is just a query // string or a fragment (e.g. "?y" or "#s") - // see <http://www.ics.uci.edu/~fielding/url/test1.html> which // identified this as a bug in the RFC if (m_path.length() == 0 && m_scheme == null && m_host == null && m_regAuthority == null) { m_scheme = p_base.getScheme(); m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_regAuthority = p_base.getRegBasedAuthority(); m_path = p_base.getPath(); if (m_queryString == null) { m_queryString = p_base.getQueryString(); } return; } // check for scheme - RFC 2396 5.2 #3 // if we found a scheme, it means absolute URI, so we're done if (m_scheme == null) { m_scheme = p_base.getScheme(); } else { return; } // check for authority - RFC 2396 5.2 #4 // if we found a host, then we've got a network path, so we're done if (m_host == null && m_regAuthority == null) { m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_regAuthority = p_base.getRegBasedAuthority(); } else { return; } // check for absolute path - RFC 2396 5.2 #5 if (m_path.length() > 0 && m_path.startsWith("/")) { return; } // if we get to this point, we need to resolve relative path // RFC 2396 5.2 #6 String path = ""; String basePath = p_base.getPath(); // 6a - get all but the last segment of the base URI path if (basePath != null && basePath.length() > 0) { int lastSlash = basePath.lastIndexOf('/'); if (lastSlash != -1) { path = basePath.substring(0, lastSlash+1); } } else if (m_path.length() > 0) { path = "/"; } // 6b - append the relative URI path path = path.concat(m_path); // 6c - remove all "./" where "." is a complete path segment index = -1; while ((index = path.indexOf("/./")) != -1) { path = path.substring(0, index+1).concat(path.substring(index+3)); } // 6d - remove "." if path ends with "." as a complete path segment if (path.endsWith("/.")) { path = path.substring(0, path.length()-1); } // 6e - remove all "<segment>/../" where "<segment>" is a complete // path segment not equal to ".." index = 1; int segIndex = -1; String tempString = null; while ((index = path.indexOf("/../", index)) > 0) { tempString = path.substring(0, path.indexOf("/../")); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { if (!tempString.substring(segIndex).equals("..")) { path = path.substring(0, segIndex+1).concat(path.substring(index+4)); index = segIndex; } else index += 4; } else index += 4; } // 6f - remove ending "<segment>/.." where "<segment>" is a // complete path segment if (path.endsWith("/..")) { tempString = path.substring(0, path.length()-3); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { path = path.substring(0, segIndex+1); } } m_path = path; } }
private void initialize(URI p_base, String p_uriSpec) throws MalformedURIException { String uriSpec = p_uriSpec; int uriSpecLen = (uriSpec != null) ? uriSpec.length() : 0; if (p_base == null && uriSpecLen == 0) { throw new MalformedURIException( "Cannot initialize URI with empty parameters."); } // just make a copy of the base if spec is empty if (uriSpecLen == 0) { initialize(p_base); return; } int index = 0; // Check for scheme, which must be before '/', '?' or '#'. Also handle // names with DOS drive letters ('D:'), so 1-character schemes are not // allowed. int colonIdx = uriSpec.indexOf(':'); int slashIdx = uriSpec.indexOf('/'); int queryIdx = uriSpec.indexOf('?'); int fragmentIdx = uriSpec.indexOf('#'); if ((colonIdx < 2) || (colonIdx > slashIdx && slashIdx != -1) || (colonIdx > queryIdx && queryIdx != -1) || (colonIdx > fragmentIdx && fragmentIdx != -1)) { // A standalone base is a valid URI according to spec if (colonIdx == 0 || (p_base == null && fragmentIdx != 0)) { throw new MalformedURIException("No scheme found in URI."); } } else { initializeScheme(uriSpec); index = m_scheme.length()+1; // Neither 'scheme:' or 'scheme:#fragment' are valid URIs. if (colonIdx == uriSpecLen - 1 || uriSpec.charAt(colonIdx+1) == '#') { throw new MalformedURIException("Scheme specific part cannot be empty."); } } // Two slashes means we may have authority, but definitely means we're either // matching net_path or abs_path. These two productions are ambiguous in that // every net_path (except those containing an IPv6Reference) is an abs_path. // RFC 2396 resolves this ambiguity by applying a greedy left most matching rule. // Try matching net_path first, and if that fails we don't have authority so // then attempt to match abs_path. // // net_path = "//" authority [ abs_path ] // abs_path = "/" path_segments if (((index+1) < uriSpecLen) && (uriSpec.charAt(index) == '/' && uriSpec.charAt(index+1) == '/')) { index += 2; int startPos = index; // Authority will be everything up to path, query or fragment char testChar = '\0'; while (index < uriSpecLen) { testChar = uriSpec.charAt(index); if (testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } // Attempt to parse authority. If the section is an empty string // this is a valid server based authority, so set the host to this // value. if (index > startPos) { // If we didn't find authority we need to back up. Attempt to // match against abs_path next. if (!initializeAuthority(uriSpec.substring(startPos, index))) { index = startPos - 2; } } else { m_host = ""; } } initializePath(uriSpec, index); // Resolve relative URI to base URI - see RFC 2396 Section 5.2 // In some cases, it might make more sense to throw an exception // (when scheme is specified is the string spec and the base URI // is also specified, for example), but we're just following the // RFC specifications if (p_base != null) { // check to see if this is the current doc - RFC 2396 5.2 #2 // note that this is slightly different from the RFC spec in that // we don't include the check for query string being null // - this handles cases where the urispec is just a query // string or a fragment (e.g. "?y" or "#s") - // see <http://www.ics.uci.edu/~fielding/url/test1.html> which // identified this as a bug in the RFC if (m_path.length() == 0 && m_scheme == null && m_host == null && m_regAuthority == null) { m_scheme = p_base.getScheme(); m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_regAuthority = p_base.getRegBasedAuthority(); m_path = p_base.getPath(); if (m_queryString == null) { m_queryString = p_base.getQueryString(); } return; } // check for scheme - RFC 2396 5.2 #3 // if we found a scheme, it means absolute URI, so we're done if (m_scheme == null) { m_scheme = p_base.getScheme(); } else { return; } // check for authority - RFC 2396 5.2 #4 // if we found a host, then we've got a network path, so we're done if (m_host == null && m_regAuthority == null) { m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_regAuthority = p_base.getRegBasedAuthority(); } else { return; } // check for absolute path - RFC 2396 5.2 #5 if (m_path.length() > 0 && m_path.startsWith("/")) { return; } // if we get to this point, we need to resolve relative path // RFC 2396 5.2 #6 String path = ""; String basePath = p_base.getPath(); // 6a - get all but the last segment of the base URI path if (basePath != null && basePath.length() > 0) { int lastSlash = basePath.lastIndexOf('/'); if (lastSlash != -1) { path = basePath.substring(0, lastSlash+1); } } else if (m_path.length() > 0) { path = "/"; } // 6b - append the relative URI path path = path.concat(m_path); // 6c - remove all "./" where "." is a complete path segment index = -1; while ((index = path.indexOf("/./")) != -1) { path = path.substring(0, index+1).concat(path.substring(index+3)); } // 6d - remove "." if path ends with "." as a complete path segment if (path.endsWith("/.")) { path = path.substring(0, path.length()-1); } // 6e - remove all "<segment>/../" where "<segment>" is a complete // path segment not equal to ".." index = 1; int segIndex = -1; String tempString = null; while ((index = path.indexOf("/../", index)) > 0) { tempString = path.substring(0, path.indexOf("/../")); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { if (!tempString.substring(segIndex).equals("..")) { path = path.substring(0, segIndex+1).concat(path.substring(index+4)); index = segIndex; } else index += 4; } else index += 4; } // 6f - remove ending "<segment>/.." where "<segment>" is a // complete path segment if (path.endsWith("/..")) { tempString = path.substring(0, path.length()-3); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { path = path.substring(0, segIndex+1); } } m_path = path; } }
diff --git a/org.inmemprofiler/src/org/inmemprofiler/runtime/data/AllBucketData.java b/org.inmemprofiler/src/org/inmemprofiler/runtime/data/AllBucketData.java index d935528..9db113c 100644 --- a/org.inmemprofiler/src/org/inmemprofiler/runtime/data/AllBucketData.java +++ b/org.inmemprofiler/src/org/inmemprofiler/runtime/data/AllBucketData.java @@ -1,83 +1,83 @@ package org.inmemprofiler.runtime.data; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class AllBucketData { private final BucketData liveInstances = new BucketData(); private Map<Long,BucketData> collectedInstances = new ConcurrentHashMap<Long, BucketData>(); private final long[] bucketIntervals; public AllBucketData(long[] buckets) { this.bucketIntervals = buckets; for (long bucketInterval : buckets) { collectedInstances.put(bucketInterval, new BucketData()); } } public synchronized void addLiveInstance(String className) { liveInstances.addData(className); } public synchronized void addCollectedInstance(String className, long instanceLifetime) { liveInstances.removeData(className); long bucketIndex = getBucketIndex(instanceLifetime); BucketData bucket = collectedInstances.get(bucketIndex); bucket.addData(className); } private long getBucketIndex(long instanceLifetime) { for (long bucketInterval : bucketIntervals) { if (instanceLifetime < bucketInterval) { return bucketInterval; } } return bucketIntervals[bucketIntervals.length - 1]; } public String toString() { StringBuilder str = new StringBuilder("\nSummary:\n"); long lastLong = 0; for (long bucketInterval : bucketIntervals) { BucketData data = collectedInstances.get(bucketInterval); if (data.totalContents.get() > 0) { str.append(data.totalContents); str.append("\t: " + lastLong + "s - " + bucketInterval + "s"); str.append("\n"); } lastLong = bucketInterval; } - str.append(liveInstances.totalContents + "\t: live objects\n"); + str.append(liveInstances.totalContents + "\t: live instances\n"); str.append("\n"); lastLong = 0; for (long bucketInterval : bucketIntervals) { BucketData data = collectedInstances.get(bucketInterval); if (data.totalContents.get() > 0) { - str.append(data.totalContents + " objects in bucket " + lastLong + "s to " + bucketInterval + "s:\n"); + str.append(data.totalContents + " instances in bucket " + lastLong + "s to " + bucketInterval + "s:\n"); str.append(data); str.append("\n"); } lastLong = bucketInterval; } if (liveInstances.totalContents.get() > 0) { - str.append(liveInstances.totalContents + " live objects:\n"); + str.append(liveInstances.totalContents + " live instances:\n"); str.append(liveInstances); str.append("\n"); } return str.toString(); } }
false
true
public String toString() { StringBuilder str = new StringBuilder("\nSummary:\n"); long lastLong = 0; for (long bucketInterval : bucketIntervals) { BucketData data = collectedInstances.get(bucketInterval); if (data.totalContents.get() > 0) { str.append(data.totalContents); str.append("\t: " + lastLong + "s - " + bucketInterval + "s"); str.append("\n"); } lastLong = bucketInterval; } str.append(liveInstances.totalContents + "\t: live objects\n"); str.append("\n"); lastLong = 0; for (long bucketInterval : bucketIntervals) { BucketData data = collectedInstances.get(bucketInterval); if (data.totalContents.get() > 0) { str.append(data.totalContents + " objects in bucket " + lastLong + "s to " + bucketInterval + "s:\n"); str.append(data); str.append("\n"); } lastLong = bucketInterval; } if (liveInstances.totalContents.get() > 0) { str.append(liveInstances.totalContents + " live objects:\n"); str.append(liveInstances); str.append("\n"); } return str.toString(); }
public String toString() { StringBuilder str = new StringBuilder("\nSummary:\n"); long lastLong = 0; for (long bucketInterval : bucketIntervals) { BucketData data = collectedInstances.get(bucketInterval); if (data.totalContents.get() > 0) { str.append(data.totalContents); str.append("\t: " + lastLong + "s - " + bucketInterval + "s"); str.append("\n"); } lastLong = bucketInterval; } str.append(liveInstances.totalContents + "\t: live instances\n"); str.append("\n"); lastLong = 0; for (long bucketInterval : bucketIntervals) { BucketData data = collectedInstances.get(bucketInterval); if (data.totalContents.get() > 0) { str.append(data.totalContents + " instances in bucket " + lastLong + "s to " + bucketInterval + "s:\n"); str.append(data); str.append("\n"); } lastLong = bucketInterval; } if (liveInstances.totalContents.get() > 0) { str.append(liveInstances.totalContents + " live instances:\n"); str.append(liveInstances); str.append("\n"); } return str.toString(); }
diff --git a/core/src/main/java/xdi2/core/xri3/impl/XRI3.java b/core/src/main/java/xdi2/core/xri3/impl/XRI3.java index 554a65316..384132e21 100644 --- a/core/src/main/java/xdi2/core/xri3/impl/XRI3.java +++ b/core/src/main/java/xdi2/core/xri3/impl/XRI3.java @@ -1,426 +1,426 @@ package xdi2.core.xri3.impl; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import xdi2.core.xri3.XRI; import xdi2.core.xri3.XRIAuthority; import xdi2.core.xri3.XRIFragment; import xdi2.core.xri3.XRIPath; import xdi2.core.xri3.XRIQuery; import xdi2.core.xri3.XRIReference; import xdi2.core.xri3.XRISyntaxComponent; import xdi2.core.xri3.impl.parser.Parser; import xdi2.core.xri3.impl.parser.ParserException; import xdi2.core.xri3.impl.parser.Rule; import xdi2.core.xri3.impl.parser.Rule$ifragment; import xdi2.core.xri3.impl.parser.Rule$iquery; import xdi2.core.xri3.impl.parser.Rule$xri; import xdi2.core.xri3.impl.parser.Rule$xri_authority; import xdi2.core.xri3.impl.parser.Rule$xri_hier_part; import xdi2.core.xri3.impl.parser.Rule$xri_path_abempty; public class XRI3 extends XRI3SyntaxComponent implements XRI { private static final long serialVersionUID = 1556756335913091713L; private static final Set reserved = new HashSet(Arrays.asList( new String[] { "user", "users", "individual", "individuals", "person", "persons", "personal", "personal.name", "personal.names", "organization", "organizations", "organizational", "organizational.name", "organizational.names", "name", "names", "iname", "inames", "i-name", "i-names", "i.name", "i.names", "number", "numbers", "inumber", "inumbers", "i-number", "i-numbers", "i.number", "i.numbers", "broker", "brokers", "i-broker", "i-brokers", "i.broker", "i.brokers", "gsp", "grsp", "global.service", "global.services", "global.service.provider", "global.service.providers", "public", "trust", "federation", "federations", "global", "service", "services", "provider", "providers", "registry", "registries", "registrant", "registrants", "aero", "biz", "cat", "com", "coop", "info", "jobs", "mobi", "museum", "net", "org", "pro", "travel", "gov", "edu", "mil", "int", "www", "ftp", "mail", "xdi", "xdiorg", "xdi-org", "xdi.org", "xri", "xriorg", "xri-org", "xri.org", "xri.xdi", "xdi.xri", "xri-xdi", "xdi-xri", "itrust", "i-trust", "i.trust", "cordance", "cordance.corp", "cordance.corporation", "cordance.net" })); private Rule rule; private XRI3Authority authority; private XRI3Path path; private XRI3Query query; private XRI3Fragment fragment; public XRI3(String string) throws ParserException { this.rule = Parser.parse("xri", string); this.read(); } public XRI3(XRI xri, XRISyntaxComponent xriPart) throws ParserException { StringBuffer buffer = new StringBuffer(); buffer.append(xri.toString()); buffer.append(xriPart.toString()); this.rule = Parser.parse("xri", buffer.toString()); this.read(); } public XRI3(XRI xri, String xriPart) throws ParserException { StringBuffer buffer = new StringBuffer(); buffer.append(xri.toString()); buffer.append(xriPart); this.rule = Parser.parse("xri", buffer.toString()); this.read(); } public XRI3(Character gcs, String uri) throws ParserException { StringBuffer buffer = new StringBuffer(); buffer.append(gcs.toString()); buffer.append(XRI3Constants.XREF_START); buffer.append(uri); buffer.append(XRI3Constants.XREF_END); this.rule = Parser.parse("xri", buffer.toString()); this.read(); } XRI3(Rule rule) { this.rule = rule; this.read(); } private void reset() { this.authority = null; this.path = null; this.query = null; this.fragment = null; } private void read() { this.reset(); Object object = this.rule; // xri // read xri_hier_part from xri - List list_xri_noscheme = ((Rule$xri) object).rules; - if (list_xri_noscheme.size() < 1) return; - object = list_xri_noscheme.get(0); // xri_hier_part + List list_xri = ((Rule$xri) object).rules; + if (list_xri.size() < 1) return; + object = list_xri.get(0); // xri_hier_part // read xri_authority from xri_hier_part List list_xri_hier_part = ((Rule$xri_hier_part) object).rules; if (list_xri_hier_part.size() < 1) return; object = list_xri_hier_part.get(0); // xri_authority this.authority = new XRI3Authority((Rule$xri_authority) object); if (this.authority.getParserObject().spelling.length() < 1) this.authority = null; // read xri_path_abempty from xri_hier_part if (list_xri_hier_part.size() < 2) return; object = list_xri_hier_part.get(1); // xri_path_abempty this.path = new XRI3Path((Rule$xri_path_abempty) object); if (this.path.getParserObject().spelling.length() < 1) this.path = null; // read iquery or ifragment from xri - if (list_xri_noscheme.size() < 3) return; - object = list_xri_noscheme.get(2); // iquery or ifragment + if (list_xri.size() < 3) return; + object = list_xri.get(2); // iquery or ifragment // iquery or ifragment ? if (object instanceof Rule$iquery) { this.query = new XRI3Query((Rule$iquery) object); if (this.query.getParserObject().spelling.length() < 1) this.query = null; // read ifragment from xri - if (list_xri_noscheme.size() < 5) return; - object = list_xri_noscheme.get(4); // ifragment + if (list_xri.size() < 5) return; + object = list_xri.get(4); // ifragment this.fragment = new XRI3Fragment((Rule$ifragment) object); if (this.fragment.getParserObject().spelling.length() < 1) this.fragment = null; } else if (object instanceof Rule$ifragment) { this.fragment = new XRI3Fragment((Rule$ifragment) object); if (this.fragment.getParserObject().spelling.length() < 1) this.fragment = null; } else { throw new ClassCastException(object.getClass().getName()); } } public Rule getParserObject() { return(this.rule); } public boolean hasAuthority() { return(this.authority != null); } public boolean hasPath() { return(this.path != null); } public boolean hasQuery() { return(this.query != null); } public boolean hasFragment() { return(this.fragment != null); } public XRIAuthority getAuthority() { return(this.authority); } public XRIPath getPath() { return(this.path); } public XRIQuery getQuery() { return(this.query); } public XRIFragment getFragment() { return(this.fragment); } public boolean isIName() { List subSegments = this.authority.getSubSegments(); // all subsegments must be reassignable for (int i=0; i<subSegments.size(); i++) { XRI3SubSegment subSegment = (XRI3SubSegment) subSegments.get(i); if (! subSegment.isReassignable()) return(false); } // some additional rules for i-names String spelling = this.authority.toString(); if (spelling.startsWith(".")) return(false); if (spelling.endsWith(".")) return(false); if (spelling.startsWith("-")) return(false); if (spelling.endsWith("-")) return(false); if (spelling.indexOf("..") >= 0) return(false); if (spelling.indexOf("--") >= 0) return(false); if (spelling.indexOf(".-") >= 0) return(false); if (spelling.indexOf("-.") >= 0) return(false); if (spelling.indexOf('%') >= 0) return(false); if (spelling.indexOf('_') >= 0) return(false); if (spelling.length() > 254) return(false); return(true); } public boolean isINumber() { List subSegments = this.authority.getSubSegments(); // all subsegments must be persistent for (int i=0; i<subSegments.size(); i++) { XRI3SubSegment subSegment = (XRI3SubSegment) subSegments.get(i); if (! subSegment.isPersistent()) return(false); } return(true); } public boolean isReserved() { String spelling = this.authority.toString(); return(reserved.contains(spelling.substring(1)) | reserved.contains(spelling.substring(1))); } public String toIRINormalForm() { StringBuffer iri = new StringBuffer(); // authority if (this.authority != null) { iri.append(XRI3Constants.XRI_SCHEME); iri.append(XRI3Constants.AUTHORITY_PREFIX).append(this.authority.toIRINormalForm()); } // path if (this.path != null) { iri.append(XRI3Constants.PATH_PREFIX).append(this.path.toIRINormalForm()); } // query if (this.query != null) { iri.append(XRI3Constants.QUERY_PREFIX).append(this.query.toIRINormalForm()); } // fragment if (this.fragment != null) { iri.append(XRI3Constants.FRAGMENT_PREFIX).append(this.fragment.toIRINormalForm()); } // done return(iri.toString()); } public boolean isValidXRIReference() { XRIReference xriReference; try { xriReference = this.toXRIReference(); } catch (Exception ex) { return(false); } return(xriReference != null); } public XRIReference toXRIReference() throws ParserException { return(new XRI3Reference(this.toString())); } public XRI3Reference toXRI3Reference() throws ParserException { return(new XRI3Reference(this.toString())); } public boolean startsWith(XRI xri) { if (xri.getAuthority() == null) return(true); if (xri.getAuthority() != null && this.getAuthority() == null) return(false); if (! this.getAuthority().equals(xri.getAuthority())) return(false); if (xri.getPath() == null) return(true); if (xri.getPath() != null && this.getPath() == null) return(false); List thisSegments = this.getPath().getSegments(); List xriSegments = xri.getPath().getSegments(); if (thisSegments.size() < xriSegments.size()) return(false); for (int i=0; i<xriSegments.size(); i++) { if (! (thisSegments.get(i).equals(xriSegments.get(i)))) return(false); } return(true); } }
false
true
private void read() { this.reset(); Object object = this.rule; // xri // read xri_hier_part from xri List list_xri_noscheme = ((Rule$xri) object).rules; if (list_xri_noscheme.size() < 1) return; object = list_xri_noscheme.get(0); // xri_hier_part // read xri_authority from xri_hier_part List list_xri_hier_part = ((Rule$xri_hier_part) object).rules; if (list_xri_hier_part.size() < 1) return; object = list_xri_hier_part.get(0); // xri_authority this.authority = new XRI3Authority((Rule$xri_authority) object); if (this.authority.getParserObject().spelling.length() < 1) this.authority = null; // read xri_path_abempty from xri_hier_part if (list_xri_hier_part.size() < 2) return; object = list_xri_hier_part.get(1); // xri_path_abempty this.path = new XRI3Path((Rule$xri_path_abempty) object); if (this.path.getParserObject().spelling.length() < 1) this.path = null; // read iquery or ifragment from xri if (list_xri_noscheme.size() < 3) return; object = list_xri_noscheme.get(2); // iquery or ifragment // iquery or ifragment ? if (object instanceof Rule$iquery) { this.query = new XRI3Query((Rule$iquery) object); if (this.query.getParserObject().spelling.length() < 1) this.query = null; // read ifragment from xri if (list_xri_noscheme.size() < 5) return; object = list_xri_noscheme.get(4); // ifragment this.fragment = new XRI3Fragment((Rule$ifragment) object); if (this.fragment.getParserObject().spelling.length() < 1) this.fragment = null; } else if (object instanceof Rule$ifragment) { this.fragment = new XRI3Fragment((Rule$ifragment) object); if (this.fragment.getParserObject().spelling.length() < 1) this.fragment = null; } else { throw new ClassCastException(object.getClass().getName()); } }
private void read() { this.reset(); Object object = this.rule; // xri // read xri_hier_part from xri List list_xri = ((Rule$xri) object).rules; if (list_xri.size() < 1) return; object = list_xri.get(0); // xri_hier_part // read xri_authority from xri_hier_part List list_xri_hier_part = ((Rule$xri_hier_part) object).rules; if (list_xri_hier_part.size() < 1) return; object = list_xri_hier_part.get(0); // xri_authority this.authority = new XRI3Authority((Rule$xri_authority) object); if (this.authority.getParserObject().spelling.length() < 1) this.authority = null; // read xri_path_abempty from xri_hier_part if (list_xri_hier_part.size() < 2) return; object = list_xri_hier_part.get(1); // xri_path_abempty this.path = new XRI3Path((Rule$xri_path_abempty) object); if (this.path.getParserObject().spelling.length() < 1) this.path = null; // read iquery or ifragment from xri if (list_xri.size() < 3) return; object = list_xri.get(2); // iquery or ifragment // iquery or ifragment ? if (object instanceof Rule$iquery) { this.query = new XRI3Query((Rule$iquery) object); if (this.query.getParserObject().spelling.length() < 1) this.query = null; // read ifragment from xri if (list_xri.size() < 5) return; object = list_xri.get(4); // ifragment this.fragment = new XRI3Fragment((Rule$ifragment) object); if (this.fragment.getParserObject().spelling.length() < 1) this.fragment = null; } else if (object instanceof Rule$ifragment) { this.fragment = new XRI3Fragment((Rule$ifragment) object); if (this.fragment.getParserObject().spelling.length() < 1) this.fragment = null; } else { throw new ClassCastException(object.getClass().getName()); } }
diff --git a/src/com/android/browser/CombinedBookmarkHistoryActivity.java b/src/com/android/browser/CombinedBookmarkHistoryActivity.java index dd29121b..a079ccea 100644 --- a/src/com/android/browser/CombinedBookmarkHistoryActivity.java +++ b/src/com/android/browser/CombinedBookmarkHistoryActivity.java @@ -1,186 +1,189 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.browser; import android.app.Activity; import android.app.TabActivity; import android.content.ContentResolver; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Browser; import android.view.Window; import android.webkit.WebIconDatabase.IconListener; import android.widget.TabHost; import android.widget.TabHost.TabSpec; import java.util.HashMap; import java.util.Vector; public class CombinedBookmarkHistoryActivity extends TabActivity implements TabHost.OnTabChangeListener { /** * Used to inform BrowserActivity to remove the parent/child relationships * from all the tabs. */ private String mExtraData; /** * Intent to be passed to calling Activity when finished. Keep a pointer to * it locally so mExtraData can be added. */ private Intent mResultData; /** * Result code to pass back to calling Activity when finished. */ private int mResultCode; /* package */ static String BOOKMARKS_TAB = "bookmark"; /* package */ static String VISITED_TAB = "visited"; /* package */ static String HISTORY_TAB = "history"; /* package */ static String STARTING_TAB = "tab"; static class IconListenerSet implements IconListener { // Used to store favicons as we get them from the database // FIXME: We use a different method to get the Favicons in // BrowserBookmarksAdapter. They should probably be unified. private HashMap<String, Bitmap> mUrlsToIcons; private Vector<IconListener> mListeners; public IconListenerSet() { mUrlsToIcons = new HashMap<String, Bitmap>(); mListeners = new Vector<IconListener>(); } public void onReceivedIcon(String url, Bitmap icon) { mUrlsToIcons.put(url, icon); for (IconListener listener : mListeners) { listener.onReceivedIcon(url, icon); } } public void addListener(IconListener listener) { mListeners.add(listener); } public void removeListener(IconListener listener) { mListeners.remove(listener); } public Bitmap getFavicon(String url) { return (Bitmap) mUrlsToIcons.get(url); } } private static IconListenerSet sIconListenerSet; static IconListenerSet getIconListenerSet() { if (null == sIconListenerSet) { sIconListenerSet = new IconListenerSet(); } return sIconListenerSet; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tabs); setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); getTabHost().setOnTabChangedListener(this); Bundle extras = getIntent().getExtras(); Intent bookmarksIntent = new Intent(this, BrowserBookmarksPage.class); bookmarksIntent.putExtras(extras); createTab(bookmarksIntent, R.string.tab_bookmarks, R.drawable.browser_bookmark_tab, BOOKMARKS_TAB); Intent visitedIntent = new Intent(this, BrowserBookmarksPage.class); // Need to copy extras so the bookmarks activity and this one will be // different Bundle visitedExtras = new Bundle(extras); visitedExtras.putBoolean("mostVisited", true); visitedIntent.putExtras(visitedExtras); createTab(visitedIntent, R.string.tab_most_visited, R.drawable.browser_visited_tab, VISITED_TAB); Intent historyIntent = new Intent(this, BrowserHistoryPage.class); historyIntent.putExtras(extras); createTab(historyIntent, R.string.tab_history, R.drawable.browser_history_tab, HISTORY_TAB); String defaultTab = extras.getString(STARTING_TAB); if (defaultTab != null) { getTabHost().setCurrentTab(2); } + // XXX: Must do this before launching the AsyncTask to avoid a + // potential crash if the icon database has not been created. + WebIconDatabase.getInstance(); // Do this every time we launch the activity in case a new favicon was // added to the webkit db. (new AsyncTask<Void, Void, Void>() { public Void doInBackground(Void... v) { Browser.requestAllIcons(getContentResolver(), Browser.BookmarkColumns.FAVICON + " is NULL", getIconListenerSet()); return null; } }).execute(); } private void createTab(Intent intent, int labelResId, int iconResId, String tab) { Resources resources = getResources(); TabHost tabHost = getTabHost(); tabHost.addTab(tabHost.newTabSpec(tab).setIndicator( resources.getText(labelResId), resources.getDrawable(iconResId)) .setContent(intent)); } // Copied from DialTacts Activity /** {@inheritDoc} */ public void onTabChanged(String tabId) { Activity activity = getLocalActivityManager().getActivity(tabId); if (activity != null) { activity.onWindowFocusChanged(true); } } /** * Store extra data in the Intent to return to the calling Activity to tell * it to clear the parent/child relationships from all tabs. */ /* package */ void removeParentChildRelationShips() { mExtraData = BrowserSettings.PREF_CLEAR_HISTORY; } /** * Custom setResult() method so that the Intent can have extra data attached * if necessary. * @param resultCode Uses same codes as Activity.setResult * @param data Intent returned to onActivityResult. */ /* package */ void setResultFromChild(int resultCode, Intent data) { mResultCode = resultCode; mResultData = data; } @Override public void finish() { if (mExtraData != null) { mResultCode = RESULT_OK; if (mResultData == null) mResultData = new Intent(); mResultData.putExtra(Intent.EXTRA_TEXT, mExtraData); } setResult(mResultCode, mResultData); super.finish(); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tabs); setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); getTabHost().setOnTabChangedListener(this); Bundle extras = getIntent().getExtras(); Intent bookmarksIntent = new Intent(this, BrowserBookmarksPage.class); bookmarksIntent.putExtras(extras); createTab(bookmarksIntent, R.string.tab_bookmarks, R.drawable.browser_bookmark_tab, BOOKMARKS_TAB); Intent visitedIntent = new Intent(this, BrowserBookmarksPage.class); // Need to copy extras so the bookmarks activity and this one will be // different Bundle visitedExtras = new Bundle(extras); visitedExtras.putBoolean("mostVisited", true); visitedIntent.putExtras(visitedExtras); createTab(visitedIntent, R.string.tab_most_visited, R.drawable.browser_visited_tab, VISITED_TAB); Intent historyIntent = new Intent(this, BrowserHistoryPage.class); historyIntent.putExtras(extras); createTab(historyIntent, R.string.tab_history, R.drawable.browser_history_tab, HISTORY_TAB); String defaultTab = extras.getString(STARTING_TAB); if (defaultTab != null) { getTabHost().setCurrentTab(2); } // Do this every time we launch the activity in case a new favicon was // added to the webkit db. (new AsyncTask<Void, Void, Void>() { public Void doInBackground(Void... v) { Browser.requestAllIcons(getContentResolver(), Browser.BookmarkColumns.FAVICON + " is NULL", getIconListenerSet()); return null; } }).execute(); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tabs); setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); getTabHost().setOnTabChangedListener(this); Bundle extras = getIntent().getExtras(); Intent bookmarksIntent = new Intent(this, BrowserBookmarksPage.class); bookmarksIntent.putExtras(extras); createTab(bookmarksIntent, R.string.tab_bookmarks, R.drawable.browser_bookmark_tab, BOOKMARKS_TAB); Intent visitedIntent = new Intent(this, BrowserBookmarksPage.class); // Need to copy extras so the bookmarks activity and this one will be // different Bundle visitedExtras = new Bundle(extras); visitedExtras.putBoolean("mostVisited", true); visitedIntent.putExtras(visitedExtras); createTab(visitedIntent, R.string.tab_most_visited, R.drawable.browser_visited_tab, VISITED_TAB); Intent historyIntent = new Intent(this, BrowserHistoryPage.class); historyIntent.putExtras(extras); createTab(historyIntent, R.string.tab_history, R.drawable.browser_history_tab, HISTORY_TAB); String defaultTab = extras.getString(STARTING_TAB); if (defaultTab != null) { getTabHost().setCurrentTab(2); } // XXX: Must do this before launching the AsyncTask to avoid a // potential crash if the icon database has not been created. WebIconDatabase.getInstance(); // Do this every time we launch the activity in case a new favicon was // added to the webkit db. (new AsyncTask<Void, Void, Void>() { public Void doInBackground(Void... v) { Browser.requestAllIcons(getContentResolver(), Browser.BookmarkColumns.FAVICON + " is NULL", getIconListenerSet()); return null; } }).execute(); }
diff --git a/examples/jms/automatic-failover/src/org/jboss/jms/example/AutomaticFailoverExample.java b/examples/jms/automatic-failover/src/org/jboss/jms/example/AutomaticFailoverExample.java index 8285283e5..65c96f4da 100644 --- a/examples/jms/automatic-failover/src/org/jboss/jms/example/AutomaticFailoverExample.java +++ b/examples/jms/automatic-failover/src/org/jboss/jms/example/AutomaticFailoverExample.java @@ -1,140 +1,140 @@ /* * JBoss, Home of Professional Open Source * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.jms.example; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.InitialContext; /** * A simple example that demonstrates automatic failover of the JMS connection from one node to another * when the live server crashes * * @author <a href="[email protected]>Tim Fox</a> */ public class AutomaticFailoverExample extends JMSExample { public static void main(String[] args) { new AutomaticFailoverExample().run(args); } public boolean runExample() throws Exception { Connection connection = null; InitialContext initialContext = null; try { // Step 1. Get an initial context for looking up JNDI from the server initialContext = getContext(1); // Step 2. Look-up the JMS Queue object from JNDI Queue queue = (Queue)initialContext.lookup("/queue/exampleQueue"); // Step 3. Look-up a JMS Connection Factory object from JNDI on server 1 ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("/ConnectionFactory"); // Step 6. We create a JMS Connection connection0 connection = connectionFactory.createConnection(); // Step 8. We create a JMS Session Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Step 10. We start the connections to ensure delivery occurs on them connection.start(); // Step 11. We create a JMS MessageConsumer object MessageConsumer consumer = session.createConsumer(queue); // Step 12. We create a JMS MessageProducer object MessageProducer producer = session.createProducer(queue); // Step 13. We send some messages to server 1 final int numMessages = 10; for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); } // We now cause the server to crash - //killServer(1); + killServer(1); // Step 14. for (int i = 0; i < numMessages; i++) { TextMessage message0 = (TextMessage)consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } // Now send some more messages for (int i = numMessages; i < numMessages * 2; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); } for (int i = 0; i < numMessages; i++) { TextMessage message0 = (TextMessage)consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } return true; } finally { // Step 15. Be sure to close our resources! if (connection != null) { connection.close(); } if (initialContext != null) { initialContext.close(); } } } }
true
true
public boolean runExample() throws Exception { Connection connection = null; InitialContext initialContext = null; try { // Step 1. Get an initial context for looking up JNDI from the server initialContext = getContext(1); // Step 2. Look-up the JMS Queue object from JNDI Queue queue = (Queue)initialContext.lookup("/queue/exampleQueue"); // Step 3. Look-up a JMS Connection Factory object from JNDI on server 1 ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("/ConnectionFactory"); // Step 6. We create a JMS Connection connection0 connection = connectionFactory.createConnection(); // Step 8. We create a JMS Session Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Step 10. We start the connections to ensure delivery occurs on them connection.start(); // Step 11. We create a JMS MessageConsumer object MessageConsumer consumer = session.createConsumer(queue); // Step 12. We create a JMS MessageProducer object MessageProducer producer = session.createProducer(queue); // Step 13. We send some messages to server 1 final int numMessages = 10; for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); } // We now cause the server to crash //killServer(1); // Step 14. for (int i = 0; i < numMessages; i++) { TextMessage message0 = (TextMessage)consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } // Now send some more messages for (int i = numMessages; i < numMessages * 2; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); } for (int i = 0; i < numMessages; i++) { TextMessage message0 = (TextMessage)consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } return true; } finally { // Step 15. Be sure to close our resources! if (connection != null) { connection.close(); } if (initialContext != null) { initialContext.close(); } } }
public boolean runExample() throws Exception { Connection connection = null; InitialContext initialContext = null; try { // Step 1. Get an initial context for looking up JNDI from the server initialContext = getContext(1); // Step 2. Look-up the JMS Queue object from JNDI Queue queue = (Queue)initialContext.lookup("/queue/exampleQueue"); // Step 3. Look-up a JMS Connection Factory object from JNDI on server 1 ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("/ConnectionFactory"); // Step 6. We create a JMS Connection connection0 connection = connectionFactory.createConnection(); // Step 8. We create a JMS Session Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Step 10. We start the connections to ensure delivery occurs on them connection.start(); // Step 11. We create a JMS MessageConsumer object MessageConsumer consumer = session.createConsumer(queue); // Step 12. We create a JMS MessageProducer object MessageProducer producer = session.createProducer(queue); // Step 13. We send some messages to server 1 final int numMessages = 10; for (int i = 0; i < numMessages; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); } // We now cause the server to crash killServer(1); // Step 14. for (int i = 0; i < numMessages; i++) { TextMessage message0 = (TextMessage)consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } // Now send some more messages for (int i = numMessages; i < numMessages * 2; i++) { TextMessage message = session.createTextMessage("This is text message " + i); producer.send(message); System.out.println("Sent message: " + message.getText()); } for (int i = 0; i < numMessages; i++) { TextMessage message0 = (TextMessage)consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } return true; } finally { // Step 15. Be sure to close our resources! if (connection != null) { connection.close(); } if (initialContext != null) { initialContext.close(); } } }
diff --git a/atlas-analytics/src/main/java/uk/ac/ebi/gxa/analytics/generator/service/ExperimentAnalyticsGeneratorService.java b/atlas-analytics/src/main/java/uk/ac/ebi/gxa/analytics/generator/service/ExperimentAnalyticsGeneratorService.java index fe665fd1d..daebb0a70 100644 --- a/atlas-analytics/src/main/java/uk/ac/ebi/gxa/analytics/generator/service/ExperimentAnalyticsGeneratorService.java +++ b/atlas-analytics/src/main/java/uk/ac/ebi/gxa/analytics/generator/service/ExperimentAnalyticsGeneratorService.java @@ -1,338 +1,339 @@ /* * Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * 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. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.analytics.generator.service; import uk.ac.ebi.gxa.analytics.compute.AtlasComputeService; import uk.ac.ebi.gxa.analytics.compute.ComputeException; import uk.ac.ebi.gxa.analytics.compute.ComputeTask; import uk.ac.ebi.gxa.analytics.generator.AnalyticsGeneratorException; import uk.ac.ebi.gxa.analytics.generator.listener.AnalyticsGeneratorListener; import uk.ac.ebi.gxa.dao.AtlasDAO; import uk.ac.ebi.gxa.dao.LoadStage; import uk.ac.ebi.gxa.dao.LoadStatus; import uk.ac.ebi.gxa.netcdf.reader.AtlasNetCDFDAO; import uk.ac.ebi.gxa.netcdf.reader.NetCDFProxy; import uk.ac.ebi.microarray.atlas.model.Experiment; import uk.ac.ebi.rcloud.server.RServices; import uk.ac.ebi.rcloud.server.RType.RChar; import uk.ac.ebi.rcloud.server.RType.RObject; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.rmi.RemoteException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; import static com.google.common.io.Closeables.closeQuietly; public class ExperimentAnalyticsGeneratorService extends AnalyticsGeneratorService { private static final int NUM_THREADS = 32; // http://download.oracle.com/docs/cd/B12037_01/java.101/b10979/ref.htm - jdbc NUMBER type does not // comply with the IEEE 754 standard for floating-point arithmetic, hence float precision in jdbc is // lower tha nthat used in java. To prevent pValues inserted from NetCDFs via java/JDBC into Oracle // loosing their precision in JDBC (i.e. being turned to 0), we use this constant to set them a reasonably low // (form Atlas statistics point of view) low enough value that is acceptable to both java and jdbc. private static final Float MIN_PVALUE_FOR_SOLR_INDEX = 10E-22f; public ExperimentAnalyticsGeneratorService(AtlasDAO atlasDAO, AtlasNetCDFDAO atlasNetCDFDAO, AtlasComputeService atlasComputeService) { super(atlasDAO, atlasNetCDFDAO, atlasComputeService); } protected void createAnalytics(final AtlasNetCDFDAO atlasNetCDFDAO) throws AnalyticsGeneratorException { // do initial setup - build executor service ExecutorService tpool = Executors.newFixedThreadPool(NUM_THREADS); // fetch experiments - check if we want all or only the pending ones List<Experiment> experiments = getAtlasDAO().getAllExperiments(); for (Experiment experiment : experiments) { getAtlasDAO().writeLoadDetails( experiment.getAccession(), LoadStage.RANKING, LoadStatus.PENDING); } // create a timer, so we can track time to generate analytics final AnalyticsTimer timer = new AnalyticsTimer(experiments); // the list of futures - we need these so we can block until completion List<Future> tasks = new ArrayList<Future>(); // start the timer timer.start(); // the first error encountered whilst generating analytics, if any Exception firstError = null; try { // process each experiment to build the netcdfs for (final Experiment experiment : experiments) { // run each experiment in parallel tasks.add(tpool.<Void>submit(new Callable<Void>() { public Void call() throws Exception { long start = System.currentTimeMillis(); try { generateExperimentAnalytics(experiment.getAccession(), null, atlasNetCDFDAO); } finally { timer.completed(experiment.getExperimentID()); long end = System.currentTimeMillis(); String total = new DecimalFormat("#.##").format((end - start) / 1000); String estimate = new DecimalFormat("#.##").format(timer.getCurrentEstimate() / 60000); getLog().info("\n\tAnalytics for " + experiment.getAccession() + " created in " + total + "s." + "\n\tCompleted " + timer.getCompletedExperimentCount() + "/" + timer.getTotalExperimentCount() + "." + "\n\tEstimated time remaining: " + estimate + " mins."); } return null; } })); } // block until completion, and throw the first error we see for (Future task : tasks) { try { task.get(); } catch (Exception e) { // print the stacktrace, but swallow this exception to rethrow at the very end getLog().error("An error occurred whilst generating analytics:\n{}", e); if (firstError == null) { firstError = e; } } } // if we have encountered an exception, throw the first error if (firstError != null) { throw new AnalyticsGeneratorException("An error occurred whilst generating analytics", firstError); } } finally { // shutdown the service getLog().debug("Shutting down executor service in " + getClass().getSimpleName()); try { tpool.shutdown(); tpool.awaitTermination(60, TimeUnit.SECONDS); if (!tpool.isTerminated()) { //noinspection ThrowFromFinallyBlock throw new AnalyticsGeneratorException( "Failed to terminate service for " + getClass().getSimpleName() + " cleanly - suspended tasks were found"); } else { getLog().debug("Executor service exited cleanly"); } } catch (InterruptedException e) { //noinspection ThrowFromFinallyBlock throw new AnalyticsGeneratorException( "Failed to terminate service for " + getClass().getSimpleName() + " cleanly - suspended tasks were found", e); } } } protected void createAnalyticsForExperiment( String experimentAccession, AnalyticsGeneratorListener listener, AtlasNetCDFDAO atlasNetCDFDAO) throws AnalyticsGeneratorException { // then generateExperimentAnalytics generateExperimentAnalytics(experimentAccession, listener, atlasNetCDFDAO); } private void generateExperimentAnalytics( String experimentAccession, AnalyticsGeneratorListener listener, AtlasNetCDFDAO atlasNetCDFDAO) throws AnalyticsGeneratorException { getLog().info("Generating analytics for experiment " + experimentAccession); // update loadmonitor - experiment is indexing getAtlasDAO().writeLoadDetails( experimentAccession, LoadStage.RANKING, LoadStatus.WORKING); // work out where the NetCDF(s) are located File[] netCDFs = getAtlasNetCDFDAO().listNetCDFs(experimentAccession); if (netCDFs.length == 0) { throw new AnalyticsGeneratorException("No NetCDF files present for " + experimentAccession); } final List<String> analysedEFs = new ArrayList<String>(); int count = 0; for (final File netCDF : netCDFs) { count++; NetCDFProxy proxy = null; try { proxy = atlasNetCDFDAO.getNetCDFProxy(experimentAccession, netCDF.getName()); if (proxy.getFactors().length == 0) { listener.buildWarning("No analytics were computed for " + netCDF.getName() + " as it contained no factors!"); + closeQuietly(proxy); return; } } catch (IOException ioe) { throw new AnalyticsGeneratorException("Failed to open " + netCDF + " to check if it contained factors", ioe); } finally { closeQuietly(proxy); } ComputeTask<Void> computeAnalytics = new ComputeTask<Void>() { public Void compute(RServices rs) throws ComputeException { try { // first, make sure we load the R code that runs the analytics rs.sourceFromBuffer(getRCodeFromResource("R/analytics.R")); // note - the netCDF file MUST be on the same file system where the workers run getLog().debug("Starting compute task for " + netCDF.getAbsolutePath()); RObject r = rs.getObject("computeAnalytics(\"" + netCDF.getAbsolutePath() + "\")"); getLog().debug("Completed compute task for " + netCDF.getAbsolutePath()); if (r instanceof RChar) { String[] efs = ((RChar) r).getNames(); String[] analysedOK = ((RChar) r).getValue(); if (efs != null) for (int i = 0; i < efs.length; i++) { getLog().debug("Performed analytics computation for netcdf {}: {} was {}", new Object[]{netCDF.getAbsolutePath(), efs[i], analysedOK[i]}); if ("OK".equals(analysedOK[i])) analysedEFs.add(efs[i]); } for (String rc : analysedOK) { if (rc.contains("Error")) throw new ComputeException(rc); } } else throw new ComputeException("Analytics returned unrecognized status of class " + r.getClass().getSimpleName() + ", string value: " + r.toString()); } catch (RemoteException e) { throw new ComputeException("Problem communicating with R service", e); } catch (IOException e) { throw new ComputeException("Unable to load R source from R/analytics.R", e); } return null; } }; proxy = null; // now run this compute task try { listener.buildProgress("Computing analytics for " + experimentAccession); // computeAnalytics writes analytics data back to NetCDF getAtlasComputeService().computeTask(computeAnalytics); getLog().debug("Compute task " + count + "/" + netCDFs.length + " for " + experimentAccession + " has completed."); if (analysedEFs.size() == 0) { listener.buildWarning("No analytics were computed for this experiment!"); } } catch (ComputeException e) { throw new AnalyticsGeneratorException("Computation of analytics for " + netCDF.getAbsolutePath() + " failed: " + e.getMessage(), e); } catch (Exception e) { throw new AnalyticsGeneratorException("An error occurred while generating analytics for " + netCDF.getAbsolutePath(), e); } finally { closeQuietly(proxy); } } } private String getRCodeFromResource(String resourcePath) throws ComputeException { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(resourcePath))); StringBuilder sb = new StringBuilder(); for (String line; (line = reader.readLine()) != null;) { sb.append(line).append("\n"); } return sb.toString(); } catch (IOException e) { throw new ComputeException("Error while reading in R code from " + resourcePath, e); } finally { closeQuietly(reader); } } private static class AnalyticsTimer { private long[] experimentIDs; private boolean[] completions; private int completedCount; private long startTime; private long lastEstimate; public AnalyticsTimer(List<Experiment> experiments) { experimentIDs = new long[experiments.size()]; completions = new boolean[experiments.size()]; int i = 0; for (Experiment exp : experiments) { experimentIDs[i] = exp.getExperimentID(); completions[i] = false; i++; } } public synchronized AnalyticsTimer start() { startTime = System.currentTimeMillis(); return this; } public synchronized AnalyticsTimer completed(long experimentID) { for (int i = 0; i < experimentIDs.length; i++) { if (experimentIDs[i] == experimentID) { if (!completions[i]) { completions[i] = true; completedCount++; } break; } } // calculate estimate of time long timeWorking = System.currentTimeMillis() - startTime; lastEstimate = (timeWorking / completedCount) * (completions.length - completedCount); return this; } public synchronized long getCurrentEstimate() { return lastEstimate; } public synchronized int getCompletedExperimentCount() { return completedCount; } public synchronized int getTotalExperimentCount() { return completions.length; } } }
true
true
private void generateExperimentAnalytics( String experimentAccession, AnalyticsGeneratorListener listener, AtlasNetCDFDAO atlasNetCDFDAO) throws AnalyticsGeneratorException { getLog().info("Generating analytics for experiment " + experimentAccession); // update loadmonitor - experiment is indexing getAtlasDAO().writeLoadDetails( experimentAccession, LoadStage.RANKING, LoadStatus.WORKING); // work out where the NetCDF(s) are located File[] netCDFs = getAtlasNetCDFDAO().listNetCDFs(experimentAccession); if (netCDFs.length == 0) { throw new AnalyticsGeneratorException("No NetCDF files present for " + experimentAccession); } final List<String> analysedEFs = new ArrayList<String>(); int count = 0; for (final File netCDF : netCDFs) { count++; NetCDFProxy proxy = null; try { proxy = atlasNetCDFDAO.getNetCDFProxy(experimentAccession, netCDF.getName()); if (proxy.getFactors().length == 0) { listener.buildWarning("No analytics were computed for " + netCDF.getName() + " as it contained no factors!"); return; } } catch (IOException ioe) { throw new AnalyticsGeneratorException("Failed to open " + netCDF + " to check if it contained factors", ioe); } finally { closeQuietly(proxy); } ComputeTask<Void> computeAnalytics = new ComputeTask<Void>() { public Void compute(RServices rs) throws ComputeException { try { // first, make sure we load the R code that runs the analytics rs.sourceFromBuffer(getRCodeFromResource("R/analytics.R")); // note - the netCDF file MUST be on the same file system where the workers run getLog().debug("Starting compute task for " + netCDF.getAbsolutePath()); RObject r = rs.getObject("computeAnalytics(\"" + netCDF.getAbsolutePath() + "\")"); getLog().debug("Completed compute task for " + netCDF.getAbsolutePath()); if (r instanceof RChar) { String[] efs = ((RChar) r).getNames(); String[] analysedOK = ((RChar) r).getValue(); if (efs != null) for (int i = 0; i < efs.length; i++) { getLog().debug("Performed analytics computation for netcdf {}: {} was {}", new Object[]{netCDF.getAbsolutePath(), efs[i], analysedOK[i]}); if ("OK".equals(analysedOK[i])) analysedEFs.add(efs[i]); } for (String rc : analysedOK) { if (rc.contains("Error")) throw new ComputeException(rc); } } else throw new ComputeException("Analytics returned unrecognized status of class " + r.getClass().getSimpleName() + ", string value: " + r.toString()); } catch (RemoteException e) { throw new ComputeException("Problem communicating with R service", e); } catch (IOException e) { throw new ComputeException("Unable to load R source from R/analytics.R", e); } return null; } }; proxy = null; // now run this compute task try { listener.buildProgress("Computing analytics for " + experimentAccession); // computeAnalytics writes analytics data back to NetCDF getAtlasComputeService().computeTask(computeAnalytics); getLog().debug("Compute task " + count + "/" + netCDFs.length + " for " + experimentAccession + " has completed."); if (analysedEFs.size() == 0) { listener.buildWarning("No analytics were computed for this experiment!"); } } catch (ComputeException e) { throw new AnalyticsGeneratorException("Computation of analytics for " + netCDF.getAbsolutePath() + " failed: " + e.getMessage(), e); } catch (Exception e) { throw new AnalyticsGeneratorException("An error occurred while generating analytics for " + netCDF.getAbsolutePath(), e); } finally { closeQuietly(proxy); } } }
private void generateExperimentAnalytics( String experimentAccession, AnalyticsGeneratorListener listener, AtlasNetCDFDAO atlasNetCDFDAO) throws AnalyticsGeneratorException { getLog().info("Generating analytics for experiment " + experimentAccession); // update loadmonitor - experiment is indexing getAtlasDAO().writeLoadDetails( experimentAccession, LoadStage.RANKING, LoadStatus.WORKING); // work out where the NetCDF(s) are located File[] netCDFs = getAtlasNetCDFDAO().listNetCDFs(experimentAccession); if (netCDFs.length == 0) { throw new AnalyticsGeneratorException("No NetCDF files present for " + experimentAccession); } final List<String> analysedEFs = new ArrayList<String>(); int count = 0; for (final File netCDF : netCDFs) { count++; NetCDFProxy proxy = null; try { proxy = atlasNetCDFDAO.getNetCDFProxy(experimentAccession, netCDF.getName()); if (proxy.getFactors().length == 0) { listener.buildWarning("No analytics were computed for " + netCDF.getName() + " as it contained no factors!"); closeQuietly(proxy); return; } } catch (IOException ioe) { throw new AnalyticsGeneratorException("Failed to open " + netCDF + " to check if it contained factors", ioe); } finally { closeQuietly(proxy); } ComputeTask<Void> computeAnalytics = new ComputeTask<Void>() { public Void compute(RServices rs) throws ComputeException { try { // first, make sure we load the R code that runs the analytics rs.sourceFromBuffer(getRCodeFromResource("R/analytics.R")); // note - the netCDF file MUST be on the same file system where the workers run getLog().debug("Starting compute task for " + netCDF.getAbsolutePath()); RObject r = rs.getObject("computeAnalytics(\"" + netCDF.getAbsolutePath() + "\")"); getLog().debug("Completed compute task for " + netCDF.getAbsolutePath()); if (r instanceof RChar) { String[] efs = ((RChar) r).getNames(); String[] analysedOK = ((RChar) r).getValue(); if (efs != null) for (int i = 0; i < efs.length; i++) { getLog().debug("Performed analytics computation for netcdf {}: {} was {}", new Object[]{netCDF.getAbsolutePath(), efs[i], analysedOK[i]}); if ("OK".equals(analysedOK[i])) analysedEFs.add(efs[i]); } for (String rc : analysedOK) { if (rc.contains("Error")) throw new ComputeException(rc); } } else throw new ComputeException("Analytics returned unrecognized status of class " + r.getClass().getSimpleName() + ", string value: " + r.toString()); } catch (RemoteException e) { throw new ComputeException("Problem communicating with R service", e); } catch (IOException e) { throw new ComputeException("Unable to load R source from R/analytics.R", e); } return null; } }; proxy = null; // now run this compute task try { listener.buildProgress("Computing analytics for " + experimentAccession); // computeAnalytics writes analytics data back to NetCDF getAtlasComputeService().computeTask(computeAnalytics); getLog().debug("Compute task " + count + "/" + netCDFs.length + " for " + experimentAccession + " has completed."); if (analysedEFs.size() == 0) { listener.buildWarning("No analytics were computed for this experiment!"); } } catch (ComputeException e) { throw new AnalyticsGeneratorException("Computation of analytics for " + netCDF.getAbsolutePath() + " failed: " + e.getMessage(), e); } catch (Exception e) { throw new AnalyticsGeneratorException("An error occurred while generating analytics for " + netCDF.getAbsolutePath(), e); } finally { closeQuietly(proxy); } } }
diff --git a/mydlp-ui-service/src/main/java/com/mydlp/ui/service/PayloadProcessServiceImpl.java b/mydlp-ui-service/src/main/java/com/mydlp/ui/service/PayloadProcessServiceImpl.java index 6dde74f1..a04ef905 100644 --- a/mydlp-ui-service/src/main/java/com/mydlp/ui/service/PayloadProcessServiceImpl.java +++ b/mydlp-ui-service/src/main/java/com/mydlp/ui/service/PayloadProcessServiceImpl.java @@ -1,127 +1,130 @@ package com.mydlp.ui.service; import java.nio.ByteBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mydlp.ui.dao.EndpointDAO; @Service("payloadProcessService") public class PayloadProcessServiceImpl implements PayloadProcessService { private static Logger logger = LoggerFactory.getLogger(PayloadProcessServiceImpl.class); private static int PROTO_MIN_CHUNK_SIZE = 78; private static int PROTO_SIZE_PART_SIZE = 17; private static String PROTO_HEAD = "MyDLPEPSync_"; private static String PROTO_PAYLOAD_HEAD = "MyDLPEPPayload_"; @Autowired protected EndpointDAO endpointDAO; @Autowired protected EncryptionService encryptionService; @Override public SyncObject toSyncObject(ByteBuffer chunk) throws ImproperPayloadEncapsulationException { try { SyncObject object = new SyncObject(); byte[] buf = null; if (chunk.remaining() < PROTO_MIN_CHUNK_SIZE) throw new ImproperPayloadEncapsulationException("Chunk is too small"); buf = new byte[12]; chunk.get(buf); if (! PROTO_HEAD.equals(new String(buf))) throw new ImproperPayloadEncapsulationException("Chunk does not start with " + PROTO_HEAD); buf = new byte[32]; chunk.get(buf); object.setEndpointId(new String(buf)); String endpointSecret = endpointDAO.getEndpointSecret(object.getEndpointId()); if (endpointSecret == null) throw new ImproperPayloadEncapsulationException("Can not find secret for endpointId"); if (chunk.get() != '_') throw new ImproperPayloadEncapsulationException("Expecting _"); buf = new byte[16]; chunk.get(buf); Integer payloadSize = Integer.parseInt(new String(buf)); if (chunk.get() != '_') throw new ImproperPayloadEncapsulationException("Expecting _"); ByteBuffer payloadChunk = encryptionService.decrypt(endpointSecret, chunk); payloadChunk.limit(payloadSize); + logger.error(payloadChunk.remaining() + ""); + logger.error(payloadSize.toString()); + logger.error(payloadChunk.remaining() + ""); buf = new byte[15]; payloadChunk.get(buf); if (! PROTO_PAYLOAD_HEAD.equals(new String(buf))) throw new ImproperPayloadEncapsulationException("Paylaod chunk does not start with " + PROTO_PAYLOAD_HEAD); payloadChunk.compact(); object.setPayload(payloadChunk); return object; } catch (ImproperPayloadEncapsulationException e) { logger.error("An error occurred", e); throw e; } catch (Throwable e) { logger.error("An error occurred", e); throw new ImproperPayloadEncapsulationException(e); } } @Override public ByteBuffer toByteBuffer(SyncObject object) throws ImproperPayloadEncapsulationException { try { String endpointSecret = endpointDAO.getEndpointSecret(object.getEndpointId()); if (endpointSecret == null) throw new ImproperPayloadEncapsulationException("Can not find secret for endpointId"); Integer endpointSize = object.getPayload().remaining(); endpointSize += PROTO_PAYLOAD_HEAD.length(); Integer zeroLength = 0; if (endpointSize % 8 != 0) { zeroLength = (8 - (endpointSize % 8)); } ByteBuffer payloadChunk = ByteBuffer.allocate(endpointSize + zeroLength); payloadChunk.put(PROTO_PAYLOAD_HEAD.getBytes()); payloadChunk.put(object.getPayload()); for (int i = 0 ; i < zeroLength ; i++) { payloadChunk.put((byte)0); } payloadChunk.flip(); payloadChunk.compact(); ByteBuffer cipher = encryptionService.encrypt(endpointSecret, payloadChunk); Integer byteBufferSize = PROTO_HEAD.length() + PROTO_SIZE_PART_SIZE + cipher.remaining(); ByteBuffer byteBuffer = ByteBuffer.allocate(byteBufferSize); byteBuffer.put(PROTO_HEAD.getBytes()); byteBuffer.put(String.format("%016d", endpointSize).getBytes()); byteBuffer.put((byte)'_'); byteBuffer.put(cipher); byteBuffer.flip(); byteBuffer.compact(); return byteBuffer; } catch (ImproperPayloadEncapsulationException e) { logger.error("An error occurred", e); throw e; } catch (Throwable e) { logger.error("An error occurred", e); throw new ImproperPayloadEncapsulationException(e); } } }
true
true
public SyncObject toSyncObject(ByteBuffer chunk) throws ImproperPayloadEncapsulationException { try { SyncObject object = new SyncObject(); byte[] buf = null; if (chunk.remaining() < PROTO_MIN_CHUNK_SIZE) throw new ImproperPayloadEncapsulationException("Chunk is too small"); buf = new byte[12]; chunk.get(buf); if (! PROTO_HEAD.equals(new String(buf))) throw new ImproperPayloadEncapsulationException("Chunk does not start with " + PROTO_HEAD); buf = new byte[32]; chunk.get(buf); object.setEndpointId(new String(buf)); String endpointSecret = endpointDAO.getEndpointSecret(object.getEndpointId()); if (endpointSecret == null) throw new ImproperPayloadEncapsulationException("Can not find secret for endpointId"); if (chunk.get() != '_') throw new ImproperPayloadEncapsulationException("Expecting _"); buf = new byte[16]; chunk.get(buf); Integer payloadSize = Integer.parseInt(new String(buf)); if (chunk.get() != '_') throw new ImproperPayloadEncapsulationException("Expecting _"); ByteBuffer payloadChunk = encryptionService.decrypt(endpointSecret, chunk); payloadChunk.limit(payloadSize); buf = new byte[15]; payloadChunk.get(buf); if (! PROTO_PAYLOAD_HEAD.equals(new String(buf))) throw new ImproperPayloadEncapsulationException("Paylaod chunk does not start with " + PROTO_PAYLOAD_HEAD); payloadChunk.compact(); object.setPayload(payloadChunk); return object; } catch (ImproperPayloadEncapsulationException e) { logger.error("An error occurred", e); throw e; } catch (Throwable e) { logger.error("An error occurred", e); throw new ImproperPayloadEncapsulationException(e); } }
public SyncObject toSyncObject(ByteBuffer chunk) throws ImproperPayloadEncapsulationException { try { SyncObject object = new SyncObject(); byte[] buf = null; if (chunk.remaining() < PROTO_MIN_CHUNK_SIZE) throw new ImproperPayloadEncapsulationException("Chunk is too small"); buf = new byte[12]; chunk.get(buf); if (! PROTO_HEAD.equals(new String(buf))) throw new ImproperPayloadEncapsulationException("Chunk does not start with " + PROTO_HEAD); buf = new byte[32]; chunk.get(buf); object.setEndpointId(new String(buf)); String endpointSecret = endpointDAO.getEndpointSecret(object.getEndpointId()); if (endpointSecret == null) throw new ImproperPayloadEncapsulationException("Can not find secret for endpointId"); if (chunk.get() != '_') throw new ImproperPayloadEncapsulationException("Expecting _"); buf = new byte[16]; chunk.get(buf); Integer payloadSize = Integer.parseInt(new String(buf)); if (chunk.get() != '_') throw new ImproperPayloadEncapsulationException("Expecting _"); ByteBuffer payloadChunk = encryptionService.decrypt(endpointSecret, chunk); payloadChunk.limit(payloadSize); logger.error(payloadChunk.remaining() + ""); logger.error(payloadSize.toString()); logger.error(payloadChunk.remaining() + ""); buf = new byte[15]; payloadChunk.get(buf); if (! PROTO_PAYLOAD_HEAD.equals(new String(buf))) throw new ImproperPayloadEncapsulationException("Paylaod chunk does not start with " + PROTO_PAYLOAD_HEAD); payloadChunk.compact(); object.setPayload(payloadChunk); return object; } catch (ImproperPayloadEncapsulationException e) { logger.error("An error occurred", e); throw e; } catch (Throwable e) { logger.error("An error occurred", e); throw new ImproperPayloadEncapsulationException(e); } }
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/algorithm/AStar.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/algorithm/AStar.java index 673507755..2c889e446 100644 --- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/algorithm/AStar.java +++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/algorithm/AStar.java @@ -1,348 +1,348 @@ /* 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentripplanner.routing.algorithm; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.opentripplanner.routing.core.Edge; import org.opentripplanner.routing.core.Graph; import org.opentripplanner.routing.core.State; import org.opentripplanner.routing.core.TraverseOptions; import org.opentripplanner.routing.core.TraverseResult; import org.opentripplanner.routing.core.Vertex; import org.opentripplanner.routing.location.StreetLocation; import org.opentripplanner.routing.pqueue.FibHeap; import org.opentripplanner.routing.spt.SPTVertex; import org.opentripplanner.routing.spt.ShortestPathTree; /** * * NullExtraEdges is used to speed up checks for extra edges in the (common) case * where there are none. Extra edges come from StreetLocationFinder, where * they represent the edges between a location on a street segment and the * corners at the ends of that segment. */ class NullExtraEdges implements Map<Vertex, Edge> { @Override public void clear() { } @Override public boolean containsKey(Object arg0) { return false; } @Override public boolean containsValue(Object arg0) { return false; } @Override public Set<java.util.Map.Entry<Vertex, Edge>> entrySet() { return null; } @Override public Edge get(Object arg0) { return null; } @Override public boolean isEmpty() { return false; } @Override public Set<Vertex> keySet() { return null; } @Override public Edge put(Vertex arg0, Edge arg1) { return null; } @Override public void putAll(Map<? extends Vertex, ? extends Edge> arg0) { } @Override public Edge remove(Object arg0) { return null; } @Override public int size() { return 0; } @Override public Collection<Edge> values() { return null; } } /** * Find the shortest path between graph vertices using A*. */ public class AStar { static final double MAX_SPEED = 10.0; /** * Plots a path on graph from origin to target, departing at the time * given in state and with the options options. * * @param graph * @param origin * @param target * @param init * @param options * @return the shortest path, or null if none is found */ public static ShortestPathTree getShortestPathTree(Graph gg, String from_label, String to_label, State init, TraverseOptions options) { // Goal Variables String origin_label = from_label; String target_label = to_label; // Get origin vertex to make sure it exists Vertex origin = gg.getVertex(origin_label); Vertex target = gg.getVertex(target_label); return getShortestPathTree(gg, origin, target, init, options); } public static ShortestPathTree getShortestPathTreeBack(Graph gg, String from_label, String to_label, State init, TraverseOptions options) { // Goal Variables String origin_label = from_label; String target_label = to_label; // Get origin vertex to make sure it exists Vertex origin = gg.getVertex(origin_label); Vertex target = gg.getVertex(target_label); return getShortestPathTreeBack(gg, origin, target, init, options); } /** * Plots a path on graph from origin to target, arriving at the time * given in state and with the options options. * * @param graph * @param origin * @param target * @param init * @param options * @return the shortest path, or null if none is found */ public static ShortestPathTree getShortestPathTreeBack(Graph graph, Vertex origin, Vertex target, State init, TraverseOptions options) { if (origin == null || target == null) { return null; } /* Run backwards from the target to the origin */ Vertex tmp = origin; origin = target; target = tmp; /* generate extra edges for StreetLocations */ Map<Vertex, Edge> extraEdges; if (target instanceof StreetLocation) { extraEdges = new HashMap<Vertex, Edge>(); Iterable<Edge> outgoing = target.getOutgoing(); for (Edge edge : outgoing) { extraEdges.put(edge.getToVertex(), edge); } } else { extraEdges = new NullExtraEdges(); } // Return Tree ShortestPathTree spt = new ShortestPathTree(); double distance = origin.distance(target) / MAX_SPEED; SPTVertex spt_origin = spt.addVertex(origin, init, 0, options); // Priority Queue FibHeap pq = new FibHeap(graph.getVertices().size() + extraEdges.size()); pq.insert(spt_origin, spt_origin.weightSum + distance); // Iteration Variables SPTVertex spt_u, spt_v; while (!pq.empty()) { // Until the priority queue is empty: spt_u = (SPTVertex) pq.extract_min(); // get the lowest-weightSum Vertex 'u', if (spt_u.mirror == target) break; Iterable<Edge> incoming = spt_u.mirror.getIncoming(); if (extraEdges.containsKey(spt_u.mirror)) { List<Edge> newIncoming = new ArrayList<Edge>(); for (Edge edge : spt_u.mirror.getOutgoing()) { newIncoming.add(edge); } newIncoming.add(extraEdges.get(spt_u.mirror)); incoming = newIncoming; } for (Edge edge : incoming) { TraverseResult wr = edge.traverseBack(spt_u.state, options); // When an edge leads nowhere (as indicated by returning NULL), the iteration is // over. if (wr == null) { continue; } if (wr.weight < 0) { - throw new NegativeWeightException(String.valueOf(wr.weight)); + throw new NegativeWeightException(String.valueOf(wr.weight) + " on edge " + edge); } Vertex fromv = edge.getFromVertex(); distance = fromv.distance(target) / MAX_SPEED; double new_w = spt_u.weightSum + wr.weight; double old_w; spt_v = spt.getVertex(fromv); // if this is the first time edge.tov has been visited if (spt_v == null) { old_w = Integer.MAX_VALUE; spt_v = spt.addVertex(fromv, wr.state, new_w, options); } else { old_w = spt_v.weightSum + distance; } // If the new way of getting there is better, if (new_w + distance < old_w) { // Set the State of v in the SPT to the current winner spt_v.state = wr.state; spt_v.weightSum = new_w; if (old_w == Integer.MAX_VALUE) { pq.insert(spt_v, new_w + distance); } else { pq.insert_or_dec_key(spt_v, new_w + distance); } spt_v.setParent(spt_u, edge); } } } return spt; } public static ShortestPathTree getShortestPathTree(Graph graph, Vertex origin, Vertex target, State init, TraverseOptions options) { if (origin == null || target == null) { return null; } /* generate extra edges for StreetLocations */ Map<Vertex, Edge> extraEdges; if (origin instanceof StreetLocation) { extraEdges = new HashMap<Vertex, Edge>(); Iterable<Edge> incoming = target.getIncoming(); for (Edge edge : incoming) { extraEdges.put(edge.getFromVertex(), edge); } } else { extraEdges = new NullExtraEdges(); } // Return Tree ShortestPathTree spt = new ShortestPathTree(); double distance = origin.distance(target) / MAX_SPEED; SPTVertex spt_origin = spt.addVertex(origin, init, 0, options); // Priority Queue FibHeap pq = new FibHeap(graph.getVertices().size() + extraEdges.size()); pq.insert(spt_origin, spt_origin.weightSum + distance); // Iteration Variables SPTVertex spt_u, spt_v; while (!pq.empty()) { // Until the priority queue is empty: spt_u = (SPTVertex) pq.extract_min(); // get the lowest-weightSum Vertex 'u', if (spt_u.mirror == target) break; Iterable<Edge> outgoing = spt_u.mirror.getOutgoing(); if (extraEdges.containsKey(spt_u.mirror)) { List<Edge> newOutgoing = new ArrayList<Edge>(); for (Edge edge : spt_u.mirror.getOutgoing()) newOutgoing.add(edge); newOutgoing.add(extraEdges.get(spt_u.mirror)); outgoing = newOutgoing; } for (Edge edge : outgoing) { TraverseResult wr = edge.traverse(spt_u.state, options); // When an edge leads nowhere (as indicated by returning NULL), the iteration is // over. if (wr == null) { continue; } if (wr.weight < 0) { throw new NegativeWeightException(String.valueOf(wr.weight)); } Vertex tov = edge.getToVertex(); distance = tov.distance(target) / MAX_SPEED; double new_w = spt_u.weightSum + wr.weight; double old_w; spt_v = spt.getVertex(tov); // if this is the first time edge.tov has been visited if (spt_v == null) { old_w = Integer.MAX_VALUE; spt_v = spt.addVertex(tov, wr.state, new_w, options); } else { old_w = spt_v.weightSum + distance; } // If the new way of getting there is better, if (new_w + distance < old_w) { // Set the State of v in the SPT to the current winner spt_v.state = wr.state; spt_v.weightSum = new_w; if (old_w == Integer.MAX_VALUE) { pq.insert(spt_v, new_w + distance); } else { pq.insert_or_dec_key(spt_v, new_w + distance); } spt_v.setParent(spt_u, edge); } } } return spt; } }
true
true
public static ShortestPathTree getShortestPathTreeBack(Graph graph, Vertex origin, Vertex target, State init, TraverseOptions options) { if (origin == null || target == null) { return null; } /* Run backwards from the target to the origin */ Vertex tmp = origin; origin = target; target = tmp; /* generate extra edges for StreetLocations */ Map<Vertex, Edge> extraEdges; if (target instanceof StreetLocation) { extraEdges = new HashMap<Vertex, Edge>(); Iterable<Edge> outgoing = target.getOutgoing(); for (Edge edge : outgoing) { extraEdges.put(edge.getToVertex(), edge); } } else { extraEdges = new NullExtraEdges(); } // Return Tree ShortestPathTree spt = new ShortestPathTree(); double distance = origin.distance(target) / MAX_SPEED; SPTVertex spt_origin = spt.addVertex(origin, init, 0, options); // Priority Queue FibHeap pq = new FibHeap(graph.getVertices().size() + extraEdges.size()); pq.insert(spt_origin, spt_origin.weightSum + distance); // Iteration Variables SPTVertex spt_u, spt_v; while (!pq.empty()) { // Until the priority queue is empty: spt_u = (SPTVertex) pq.extract_min(); // get the lowest-weightSum Vertex 'u', if (spt_u.mirror == target) break; Iterable<Edge> incoming = spt_u.mirror.getIncoming(); if (extraEdges.containsKey(spt_u.mirror)) { List<Edge> newIncoming = new ArrayList<Edge>(); for (Edge edge : spt_u.mirror.getOutgoing()) { newIncoming.add(edge); } newIncoming.add(extraEdges.get(spt_u.mirror)); incoming = newIncoming; } for (Edge edge : incoming) { TraverseResult wr = edge.traverseBack(spt_u.state, options); // When an edge leads nowhere (as indicated by returning NULL), the iteration is // over. if (wr == null) { continue; } if (wr.weight < 0) { throw new NegativeWeightException(String.valueOf(wr.weight)); } Vertex fromv = edge.getFromVertex(); distance = fromv.distance(target) / MAX_SPEED; double new_w = spt_u.weightSum + wr.weight; double old_w; spt_v = spt.getVertex(fromv); // if this is the first time edge.tov has been visited if (spt_v == null) { old_w = Integer.MAX_VALUE; spt_v = spt.addVertex(fromv, wr.state, new_w, options); } else { old_w = spt_v.weightSum + distance; } // If the new way of getting there is better, if (new_w + distance < old_w) { // Set the State of v in the SPT to the current winner spt_v.state = wr.state; spt_v.weightSum = new_w; if (old_w == Integer.MAX_VALUE) { pq.insert(spt_v, new_w + distance); } else { pq.insert_or_dec_key(spt_v, new_w + distance); } spt_v.setParent(spt_u, edge); } } } return spt; }
public static ShortestPathTree getShortestPathTreeBack(Graph graph, Vertex origin, Vertex target, State init, TraverseOptions options) { if (origin == null || target == null) { return null; } /* Run backwards from the target to the origin */ Vertex tmp = origin; origin = target; target = tmp; /* generate extra edges for StreetLocations */ Map<Vertex, Edge> extraEdges; if (target instanceof StreetLocation) { extraEdges = new HashMap<Vertex, Edge>(); Iterable<Edge> outgoing = target.getOutgoing(); for (Edge edge : outgoing) { extraEdges.put(edge.getToVertex(), edge); } } else { extraEdges = new NullExtraEdges(); } // Return Tree ShortestPathTree spt = new ShortestPathTree(); double distance = origin.distance(target) / MAX_SPEED; SPTVertex spt_origin = spt.addVertex(origin, init, 0, options); // Priority Queue FibHeap pq = new FibHeap(graph.getVertices().size() + extraEdges.size()); pq.insert(spt_origin, spt_origin.weightSum + distance); // Iteration Variables SPTVertex spt_u, spt_v; while (!pq.empty()) { // Until the priority queue is empty: spt_u = (SPTVertex) pq.extract_min(); // get the lowest-weightSum Vertex 'u', if (spt_u.mirror == target) break; Iterable<Edge> incoming = spt_u.mirror.getIncoming(); if (extraEdges.containsKey(spt_u.mirror)) { List<Edge> newIncoming = new ArrayList<Edge>(); for (Edge edge : spt_u.mirror.getOutgoing()) { newIncoming.add(edge); } newIncoming.add(extraEdges.get(spt_u.mirror)); incoming = newIncoming; } for (Edge edge : incoming) { TraverseResult wr = edge.traverseBack(spt_u.state, options); // When an edge leads nowhere (as indicated by returning NULL), the iteration is // over. if (wr == null) { continue; } if (wr.weight < 0) { throw new NegativeWeightException(String.valueOf(wr.weight) + " on edge " + edge); } Vertex fromv = edge.getFromVertex(); distance = fromv.distance(target) / MAX_SPEED; double new_w = spt_u.weightSum + wr.weight; double old_w; spt_v = spt.getVertex(fromv); // if this is the first time edge.tov has been visited if (spt_v == null) { old_w = Integer.MAX_VALUE; spt_v = spt.addVertex(fromv, wr.state, new_w, options); } else { old_w = spt_v.weightSum + distance; } // If the new way of getting there is better, if (new_w + distance < old_w) { // Set the State of v in the SPT to the current winner spt_v.state = wr.state; spt_v.weightSum = new_w; if (old_w == Integer.MAX_VALUE) { pq.insert(spt_v, new_w + distance); } else { pq.insert_or_dec_key(spt_v, new_w + distance); } spt_v.setParent(spt_u, edge); } } } return spt; }
diff --git a/org.eclipse.riena.communication.factory.hessian/src/org/eclipse/riena/internal/communication/factory/hessian/BigIntegerSerializerFactory.java b/org.eclipse.riena.communication.factory.hessian/src/org/eclipse/riena/internal/communication/factory/hessian/BigIntegerSerializerFactory.java index 8199dc2c3..7b37e6939 100644 --- a/org.eclipse.riena.communication.factory.hessian/src/org/eclipse/riena/internal/communication/factory/hessian/BigIntegerSerializerFactory.java +++ b/org.eclipse.riena.communication.factory.hessian/src/org/eclipse/riena/internal/communication/factory/hessian/BigIntegerSerializerFactory.java @@ -1,67 +1,69 @@ /******************************************************************************* * Copyright (c) 2007, 2009 compeople AG and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * compeople AG - initial API and implementation *******************************************************************************/ package org.eclipse.riena.internal.communication.factory.hessian; import java.io.IOException; import java.math.BigInteger; import com.caucho.hessian.io.AbstractHessianInput; import com.caucho.hessian.io.AbstractHessianOutput; import com.caucho.hessian.io.Deserializer; import com.caucho.hessian.io.HessianProtocolException; import com.caucho.hessian.io.JavaDeserializer; import com.caucho.hessian.io.JavaSerializer; import com.caucho.hessian.io.Serializer; /** * Deserializer for the {@code BigInteger}. */ public class BigIntegerSerializerFactory extends AbstractRienaSerializerFactory { @SuppressWarnings("unchecked") @Override public Deserializer getDeserializer(final Class cl) throws HessianProtocolException { if (cl == BigInteger.class) { return new JavaDeserializer(cl) { @Override public Class getType() { return BigInteger.class; } @Override public Object readObject(AbstractHessianInput in, String[] fieldNames) throws IOException { - return new BigInteger(in.readString()); + BigInteger result = new BigInteger(in.readString()); + in.addRef(result); + return result; } }; } return null; } @SuppressWarnings("unchecked") @Override public Serializer getSerializer(Class cl) throws HessianProtocolException { if (cl == BigInteger.class) { return new JavaSerializer(cl) { @Override public void writeInstance(Object obj, AbstractHessianOutput out) throws IOException { BigInteger bi = (BigInteger) obj; out.writeString(bi.toString()); } }; } return null; } }
true
true
public Deserializer getDeserializer(final Class cl) throws HessianProtocolException { if (cl == BigInteger.class) { return new JavaDeserializer(cl) { @Override public Class getType() { return BigInteger.class; } @Override public Object readObject(AbstractHessianInput in, String[] fieldNames) throws IOException { return new BigInteger(in.readString()); } }; } return null; }
public Deserializer getDeserializer(final Class cl) throws HessianProtocolException { if (cl == BigInteger.class) { return new JavaDeserializer(cl) { @Override public Class getType() { return BigInteger.class; } @Override public Object readObject(AbstractHessianInput in, String[] fieldNames) throws IOException { BigInteger result = new BigInteger(in.readString()); in.addRef(result); return result; } }; } return null; }
diff --git a/src/de/ueller/midlet/gps/data/Gpx.java b/src/de/ueller/midlet/gps/data/Gpx.java index 1887156..9a11165 100644 --- a/src/de/ueller/midlet/gps/data/Gpx.java +++ b/src/de/ueller/midlet/gps/data/Gpx.java @@ -1,911 +1,912 @@ package de.ueller.midlet.gps.data; /* * GpsMid - Copyright (c) 2008 Kai Krueger apm at users dot sourceforge dot net * See Copying */ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.Math; import java.util.Calendar; import java.util.Date; import javax.microedition.rms.InvalidRecordIDException; import javax.microedition.rms.RecordEnumeration; import javax.microedition.rms.RecordStore; import javax.microedition.rms.RecordStoreException; import javax.microedition.rms.RecordStoreFullException; import javax.microedition.rms.RecordStoreNotFoundException; import javax.microedition.rms.RecordStoreNotOpenException; import de.ueller.gps.data.Configuration; import de.ueller.gps.data.Position; import de.ueller.gpsMid.mapData.GpxTile; import de.ueller.gpsMid.mapData.Tile; import de.ueller.midlet.gps.GpsMid; import de.ueller.midlet.gps.Logger; import de.ueller.midlet.gps.Trace; import de.ueller.midlet.gps.UploadListener; import de.ueller.midlet.gps.importexport.ExportSession; import de.ueller.midlet.gps.importexport.GpxParser; import de.ueller.midlet.gps.tile.PaintContext; public class Gpx extends Tile implements Runnable { private float maxDistance; // statics for user-defined rules for record trackpoint private static long oldMsTime; private static float oldlat; private static float oldlon; private final static Logger logger = Logger.getInstance(Gpx.class,Logger.DEBUG); private RecordStore trackDatabase = null; private RecordStore wayptDatabase = null; public int recorded = 0; public int delay = 0; private float trkOdo; private float trkVertSpd; private float trkVmax; private int trkTimeTot; private Thread processorThread = null; private String url = null; private boolean sendWpt; private boolean sendTrk; private boolean reloadWpt; private boolean applyRecordingRules = true; private String trackName; private PersistEntity currentTrk; private UploadListener feedbackListener; private String importExportMessage; /** * Variables used for transmitting GPX data: */ private InputStream in; private ByteArrayOutputStream baos; private DataOutputStream dos; private boolean trkRecordingSuspended; private GpxTile tile; public Gpx() { tile = new GpxTile(); reloadWpt = true; processorThread = new Thread(this); processorThread.setPriority(Thread.MIN_PRIORITY); processorThread.start(); } public void displayWaypoints(boolean displayWpt) { } public void displayTrk(PersistEntity trk) { if (trk == null) { //TODO: } else { try { tile.dropTrk(); openTrackDatabase(); DataInputStream dis1 = new DataInputStream(new ByteArrayInputStream(trackDatabase.getRecord(trk.id))); trackName = dis1.readUTF(); recorded = dis1.readInt(); int trackSize = dis1.readInt(); byte[] trackArray = new byte[trackSize]; dis1.read(trackArray); DataInputStream trackIS = new DataInputStream(new ByteArrayInputStream(trackArray)); for (int i = 0; i < recorded; i++) { tile.addTrkPt(trackIS.readFloat(), trackIS.readFloat(), false); trackIS.readShort(); //altitude trackIS.readLong(); //Time trackIS.readByte(); //Speed } dis1.close(); dis1 = null; trackDatabase.closeRecordStore(); trackDatabase = null; } catch (IOException e) { logger.exception("IOException displaying track", e); } catch (RecordStoreNotOpenException e) { logger.exception("Exception displaying track (database not open)", e); } catch (InvalidRecordIDException e) { logger.exception("Exception displaying track (ID invalid)", e); } catch (RecordStoreException e) { logger.exception("Exception displaying track", e); } } } public void addWayPt(PositionMark waypt) { byte[] buf = waypt.toByte(); try { openWayPtDatabase(); int id = wayptDatabase.addRecord(buf, 0, buf.length); waypt.id = id; wayptDatabase.closeRecordStore(); wayptDatabase = null; } catch (RecordStoreNotOpenException e) { logger.exception("Exception storing waypoint (database not open)", e); } catch (RecordStoreFullException e) { logger.exception("Record store is full, could not store waypoint", e); } catch (RecordStoreException e) { logger.exception("Exception storing waypoint", e); } tile.addWayPt(waypt); } public boolean existsWayPt(PositionMark newWayPt) { if (tile != null) { return tile.existsWayPt(newWayPt); } return false; } public void addTrkPt(Position trkpt) { if (trkRecordingSuspended) return; //#debug info logger.info("Adding trackpoint: " + trkpt); Configuration config=GpsMid.getInstance().getConfig(); long msTime=trkpt.date.getTime(); float lat=trkpt.latitude*MoreMath.FAC_DECTORAD; float lon=trkpt.longitude*MoreMath.FAC_DECTORAD; float distance = 0.0f; boolean doRecord=false; try { // always record when i.e. receiving or loading tracklogs // or when starting to record if (!applyRecordingRules || recorded==0) { doRecord=true; distance = ProjMath.getDistance(lat, lon, oldlat, oldlon); } // check which record rules to apply else if (config.getGpxRecordRuleMode()==Configuration.GPX_RECORD_ADAPTIVE) { /** adaptive recording * * When saving tracklogs and adaptive recording is enabled, * we reduce the frequency of saved samples if the speed drops * to less than a certain amount. This should increase storage * efficiency if one doesn't need if one doesn't need to repeatedly * store positions if the device is not moving * * Chose the following arbitrary sampling frequency: * Greater 8km/h (2.22 m/s): every sample * Greater 4km/h (1.11 m/s): every second sample * Greater 2km/h (0.55 m/s): every fourth sample * Below 2km/h (0.55 m/s): every tenth sample */ if ( (trkpt.speed > 2.222f) || ((trkpt.speed > 1.111f) && (delay > 0 )) || ((trkpt.speed > 0.556) && delay > 3 ) || (delay > 10)) { doRecord=true; distance = ProjMath.getDistance(lat, lon, oldlat, oldlon); delay = 0; } else { delay++; } } else { /* user-specified recording rules */ distance = ProjMath.getDistance(lat, lon, oldlat, oldlon); if ( // is not always record distance not set // or always record distance reached ( config.getGpxRecordAlwaysDistanceCentimeters()!=0 && 100*distance >= config.getGpxRecordAlwaysDistanceCentimeters() ) || ( ( // is minimum time interval not set // or interval at least minimum interval? config.getGpxRecordMinMilliseconds() == 0 || Math.abs(msTime-oldMsTime) >= config.getGpxRecordMinMilliseconds() ) && ( // is minimum distance not set // or distance at least minimum distance? config.getGpxRecordMinDistanceCentimeters()==0 || 100*distance >= config.getGpxRecordMinDistanceCentimeters() ) ) ) { doRecord=true; } } if(doRecord) { dos.writeFloat(trkpt.latitude); dos.writeFloat(trkpt.longitude); dos.writeShort((short)trkpt.altitude); dos.writeLong(trkpt.date.getTime()); dos.writeByte((byte)(trkpt.speed*3.6f)); //Convert to km/h recorded++; + tile.addTrkPt(trkpt.latitude, trkpt.longitude, false); if ((oldlat != 0.0f) || (oldlon != 0.0f)) { trkOdo += distance; trkTimeTot += msTime - oldMsTime; if (trkVmax < trkpt.speed) trkVmax = trkpt.speed; } oldMsTime=msTime; oldlat=lat; oldlon=lon; } } catch (OutOfMemoryError oome) { try { Trace.getInstance().dropCache(); logger.info("Was out of memory, but we might have recovered"); }catch (OutOfMemoryError oome2) { logger.fatal("Out of memory, can't add trackpoint"); } } catch (IOException e) { logger.exception("Could not add trackpoint", e); } } public void deleteWayPt(PositionMark waypt) { deleteWayPt(waypt, null); } public void deleteWayPt(PositionMark waypt, UploadListener ul) { this.feedbackListener = ul; try { openWayPtDatabase(); wayptDatabase.deleteRecord(waypt.id); wayptDatabase.closeRecordStore(); wayptDatabase = null; } catch (RecordStoreNotOpenException e) { logger.exception("Exception deleting waypoint (database not open)", e); } catch (InvalidRecordIDException e) { logger.exception("Exception deleting waypoint (ID invalid)", e); } catch (RecordStoreException e) { logger.exception("Exception deleting waypoint", e); } } public void reloadWayPts() { if (processorThread != null && processorThread.isAlive()) { /* Already reloading, nothing to do */ return; } reloadWpt = true; processorThread = new Thread(this); processorThread.setPriority(Thread.MIN_PRIORITY); processorThread.start(); } public void newTrk() { logger.debug("Starting a new track recording"); tile.dropTrk(); Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); //Construct a track name from the current time StringBuffer trkName = new StringBuffer(); trkName.append(cal.get(Calendar.YEAR)).append("-").append(formatInt2(cal.get(Calendar.MONTH) + 1)); trkName.append("-").append(formatInt2(cal.get(Calendar.DAY_OF_MONTH))).append("_"); trkName.append(formatInt2(cal.get(Calendar.HOUR_OF_DAY))).append("-").append(formatInt2(cal.get(Calendar.MINUTE))); trackName = trkName .toString(); baos = new ByteArrayOutputStream(); dos = new DataOutputStream(baos); trkOdo = 0.0f; trkVmax = 0.0f; trkVertSpd = 0.0f; trkTimeTot = 0; recorded = 0; trkRecordingSuspended = false; } public void saveTrk() { try { if (dos == null) { logger.debug("Not recording, so no track to save"); return; } dos.flush(); logger.debug("Finishing track with " + recorded + " points"); ByteArrayOutputStream baosDb = new ByteArrayOutputStream(); DataOutputStream dosDb = new DataOutputStream(baosDb); dosDb.writeUTF(trackName); dosDb.writeInt(recorded); dosDb.writeInt(baos.size()); dosDb.write(baos.toByteArray()); dosDb.flush(); openTrackDatabase(); trackDatabase.addRecord(baosDb.toByteArray(), 0, baosDb.size()); trackDatabase.closeRecordStore(); trackDatabase = null; dos.close(); dos = null; baos = null; tile.dropTrk(); } catch (IOException e) { logger.exception("IOException saving track", e); } catch (RecordStoreNotOpenException e) { logger.exception("Exception saving track (database not open)", e); } catch (RecordStoreFullException e) { logger.exception("Exception saving track (database full)", e); } catch (RecordStoreException e) { logger.exception("Exception saving track", e); } catch (OutOfMemoryError oome) { logger.fatal("Out of memory, can't save tracklog"); } } public void suspendTrk() { trkRecordingSuspended = true; try { if(dos != null) { /** * Add a marker to the recording to be able to * break up the GPX file into separate track segments * after each suspend */ dos.writeFloat(0.0f); dos.writeFloat(0.0f); dos.writeShort(0); dos.writeLong(Long.MIN_VALUE); dos.writeByte(0); recorded++; oldlat = 0.0f; oldlon = 0.0f; } } catch (IOException ioe) { logger.exception("Failed to write track segmentation marker", ioe); } } public void resumTrk() { trkRecordingSuspended = false; } public void deleteTrk(PersistEntity trk) { try { openTrackDatabase(); trackDatabase.deleteRecord(trk.id); trackDatabase.closeRecordStore(); trackDatabase = null; tile.dropTrk(); } catch (RecordStoreNotOpenException e) { logger.exception("Exception deleting track (database not open)", e); } catch (InvalidRecordIDException e) { logger.exception("Exception deleting track (ID invalid)", e); } catch (RecordStoreException e) { logger.exception("Exception deleting track", e); } } public void receiveGpx(InputStream in, UploadListener ul, float maxDistance) { this.maxDistance=maxDistance; this.in = in; this.feedbackListener = ul; if (in == null) { logger.error("Could not open input stream to gpx file"); } if ((processorThread != null) && (processorThread.isAlive())) { logger.error("Still processing another gpx file"); } processorThread = new Thread(this); processorThread.setPriority(Thread.MIN_PRIORITY); processorThread.start(); } public void sendTrk(String url, UploadListener ul, PersistEntity trk) { logger.debug("Sending " + trk + " to " + url); feedbackListener = ul; this.url = url; sendTrk = true; tile.dropTrk(); currentTrk = trk; processorThread = new Thread(this); processorThread.setPriority(Thread.MIN_PRIORITY); processorThread.start(); } public void sendTrkAll(String url, UploadListener ul) { logger.debug("Exporting all tracklogs to " + url); feedbackListener = ul; this.url = url; sendTrk = true; tile.dropTrk(); // processorThread = new Thread( new Runnable() { public void run() { PersistEntity [] trks = listTrks(); for (int i = 0; i < trks.length; i++) { currentTrk = trks[i]; boolean success = sendGpx(); if (!success) { logger.error("Failed to export track " + currentTrk); if (feedbackListener != null) { feedbackListener.completedUpload(success, importExportMessage); } return; } } if (feedbackListener != null) { feedbackListener.completedUpload(true, importExportMessage); } feedbackListener = null; sendTrk = false; sendWpt = false; } }); processorThread.setPriority(Thread.MIN_PRIORITY); processorThread.start(); } public void sendWayPt(String url, UploadListener ul) { this.url = url; feedbackListener = ul; sendWpt = true; processorThread = new Thread(this); processorThread.setPriority(Thread.MIN_PRIORITY); processorThread.start(); } public PositionMark [] listWayPt() { return tile.listWayPt(); } /** * Read tracks from the RecordStore to display the names in the list on screen. */ public PersistEntity[] listTrks() { PersistEntity[] trks; byte [] record = new byte[16000]; DataInputStream dis = new DataInputStream(new ByteArrayInputStream(record)); try { openTrackDatabase(); logger.info("GPX database has " + trackDatabase.getNumRecords() + " entries and a size of " + trackDatabase.getSize()); trks = new PersistEntity[trackDatabase.getNumRecords()]; RecordEnumeration p = trackDatabase.enumerateRecords(null, null, false); logger.info("Enumerating tracks: " + p.numRecords()); int i = 0; while (p.hasNextElement()) { int idx = p.nextRecordId(); while (trackDatabase.getRecordSize(idx) > record.length) { record = new byte[record.length + 16000]; dis = new DataInputStream(new ByteArrayInputStream(record)); } trackDatabase.getRecord(idx, record, 0); dis.reset(); String trackName = dis.readUTF(); int noTrackPoints = dis.readInt(); logger.debug("Found track " + trackName + " with " + noTrackPoints + "TrkPoints"); PersistEntity trk = new PersistEntity(); trk.id = idx; trk.displayName = trackName + " (" + noTrackPoints + ")"; trks[i++] = trk; } logger.info("Enumerated tracks"); trackDatabase.closeRecordStore(); trackDatabase = null; return trks; } catch (RecordStoreFullException e) { logger.error("Record Store is full, can't load list" + e.getMessage()); } catch (RecordStoreNotFoundException e) { logger.error("Record Store not found, can't load list" + e.getMessage()); } catch (RecordStoreException e) { logger.error("Record Store exception, can't load list" + e.getMessage()); } catch (IOException e) { logger.error("IO exception, can't load list" + e.getMessage()); } return null; } public void dropCache() { tile.dropTrk(); tile.dropWayPt(); System.gc(); if (isRecordingTrk()) saveTrk(); } public boolean cleanup(int level) { // TODO Auto-generated method stub return false; } public void paint(PaintContext pc, byte layer) { tile.paint(pc, layer); } public boolean isRecordingTrk() { return (dos != null); } public boolean isRecordingTrkSuspended() { return trkRecordingSuspended; } /** * @return current GPX track length in m */ public float currentTrkLength() { return trkOdo; } /** * @return current GPX track's average speed in m/s */ public float currentTrkAvgSpd() { return (1000.0f*trkOdo) / trkTimeTot; } /** * @return current GPX tracks time duration in ms */ public long currentTrkDuration() { return trkTimeTot; } /** * @return current GPX track's maximum speed in m/s */ public float maxTrkSpeed() { return trkVmax; } public void run() { logger.info("GPX processing thread started"); boolean success = false; if (reloadWpt) { try { /** * Sleep for a while to limit the number of reloads happening */ Thread.sleep(300); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } loadWaypointsFromDatabase(); reloadWpt = false; if (feedbackListener != null) { feedbackListener.uploadAborted(); feedbackListener = null; } return; } else if (sendTrk || sendWpt) { success = sendGpx(); } else if (in != null) { success = receiveGpx(); } else { logger.error("Did not know whether to send or receive"); } if (feedbackListener != null) { feedbackListener.completedUpload(success, importExportMessage); } feedbackListener = null; sendTrk = false; sendWpt = false; } private void openWayPtDatabase() { try { if (wayptDatabase == null) { wayptDatabase = RecordStore.openRecordStore("waypoints", true); } } catch (RecordStoreFullException e) { logger.exception("Recordstore full while trying to open waypoints", e); } catch (RecordStoreNotFoundException e) { logger.exception("Waypoint recordstore not found", e); } catch (RecordStoreException e) { logger.exception("RecordStoreException opening waypoints", e); } catch (OutOfMemoryError oome) { logger.error("Out of memory opening waypoints"); } } /** * Read waypoints from the RecordStore and put them in a tile for displaying. */ private void loadWaypointsFromDatabase() { try { tile.dropWayPt(); RecordEnumeration renum; logger.info("Loading waypoints into tile"); openWayPtDatabase(); renum = wayptDatabase.enumerateRecords(null, null, false); while (renum.hasNextElement()) { int id; id = renum.nextRecordId(); PositionMark waypt = new PositionMark(id, wayptDatabase.getRecord(id)); tile.addWayPt(waypt); } wayptDatabase.closeRecordStore(); wayptDatabase = null; } catch (RecordStoreException e) { logger.exception("RecordStoreException loading waypoints", e); } catch (OutOfMemoryError oome) { logger.error("Out of memory loading waypoints"); } } private void openTrackDatabase() { try { if (trackDatabase == null) { logger.info("Opening track database"); trackDatabase = RecordStore.openRecordStore("tracks", true); } } catch (RecordStoreFullException e) { logger.exception("Recordstore is full while trying to open tracks", e); } catch (RecordStoreNotFoundException e) { logger.exception("Tracks recordstore not found", e); } catch (RecordStoreException e) { logger.exception("RecordStoreException opening tracks", e); } catch (OutOfMemoryError oome) { logger.error("Out of memory opening tracks"); } } private void streamTracks (OutputStream oS) throws IOException, RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException{ float lat, lon; short ele; long time; Date d = new Date(); openTrackDatabase(); DataInputStream dis1 = new DataInputStream(new ByteArrayInputStream(trackDatabase.getRecord(currentTrk.id))); trackName = dis1.readUTF(); recorded = dis1.readInt(); int trackSize = dis1.readInt(); byte[] trackArray = new byte[trackSize]; dis1.read(trackArray); DataInputStream trackIS = new DataInputStream(new ByteArrayInputStream(trackArray)); oS.write("<trk>\r\n<trkseg>\r\n".getBytes()); StringBuffer sb = new StringBuffer(128); for (int i = 1; i <= recorded; i++) { lat = trackIS.readFloat(); lon = trackIS.readFloat(); ele = trackIS.readShort(); time = trackIS.readLong(); // Read extra bytes in the buffer, that are currently not written to the GPX file. // Will add these at a later time. trackIS.readByte(); //Speed if (time == Long.MIN_VALUE) { oS.write("</trkseg>\r\n".getBytes()); oS.write("<trkseg>\r\n".getBytes()); } else { sb.setLength(0); sb.append("<trkpt lat='").append(lat).append("' lon='").append(lon).append("' >\r\n"); sb.append("<ele>").append(ele).append("</ele>\r\n"); d.setTime(time); sb.append("<time>").append(formatUTC(d)).append("</time>\r\n"); sb.append("</trkpt>\r\n"); oS.write(sb.toString().getBytes()); } } oS.write("</trkseg>\r\n</trk>\r\n".getBytes()); trackDatabase.closeRecordStore(); trackDatabase = null; } private void streamWayPts (OutputStream oS) throws IOException{ PositionMark[] waypts = tile.listWayPt(); PositionMark wayPt = null; for (int i = 0; i < waypts.length; i++) { wayPt = waypts[i]; StringBuffer sb = new StringBuffer(128); sb.append("<wpt lat='").append(wayPt.lat*MoreMath.FAC_RADTODEC).append("' lon='").append(wayPt.lon*MoreMath.FAC_RADTODEC).append("' >\r\n"); sb.append("<name>").append(wayPt.displayName).append("</name>\r\n"); sb.append("</wpt>\r\n"); oS.write(sb.toString().getBytes()); } } private boolean sendGpx() { try { String name = null; logger.trace("Starting to send a GPX file, about to open a connection to" + url); if (sendTrk) { name = currentTrk.displayName; } else if (sendWpt) { name = "Waypoints"; } if (url == null) { importExportMessage = "No GPX receiver specified. Please select a GPX receiver in the setup menu"; return false; } OutputStream oS = null; ExportSession session = null; try { /** * We jump through hoops here (Class.forName) in order to decouple * the implementation of JSRs. The problem is, that not all phones have all * of the JSRs, and if we simply called the Class directly, it would * cause the whole app to crash. With this method, we can hopefully catch * the missing JSRs and gracefully report an error to the user that the operation * is not available on this phone. */ /** * The Class.forName and the instantiation of the class must be separate * statements, as otherwise this confuses the proguard obfuscator when * rewriting the flattened renamed classes. */ Class tmp = null; if (url.startsWith("file:")) { tmp = Class.forName("de.ueller.midlet.gps.importexport.FileExportSession"); } else if (url.startsWith("comm:")) { tmp = Class.forName("de.ueller.midlet.gps.importexport.CommExportSession"); } else if (url.startsWith("btgoep:")){ tmp = Class.forName("de.ueller.midlet.gps.importexport.ObexExportSession"); } if (tmp != null) logger.info("Got class: " + tmp); Object objTmp = tmp.newInstance(); if (objTmp instanceof ExportSession) { session = (ExportSession)(objTmp); } else { logger.info("objTmp: " + objTmp + "is not part of " + ExportSession.class.getName()); } } catch (ClassNotFoundException cnfe) { importExportMessage = "Your phone does not support this form of exporting, pleas choose a different one"; session = null; return false; } catch (ClassCastException cce) { logger.exception("Could not cast the class", cce); } if (session == null) { importExportMessage = "Your phone does not support this form of exporting, pleas choose a different one"; return false; } oS = session.openSession(url, name); if (oS == null) { importExportMessage = "Could not obtain a valid connection to " + url; return false; } oS.write("<?xml version='1.0' encoding='UTF-8'?>\r\n".getBytes()); oS.write("<gpx version='1.1' creator='GPSMID' xmlns='http://www.topografix.com/GPX/1/1'>\r\n".getBytes()); if (sendWpt) { streamWayPts(oS); } if (sendTrk) { streamTracks(oS); } oS.write("</gpx>\r\n\r\n".getBytes()); oS.flush(); oS.close(); session.closeSession(); importExportMessage = "success"; return true; } catch (IOException e) { logger.error("IOException, can't transmit tracklog: " + e); } catch (OutOfMemoryError oome) { logger.fatal("Out of memory, can't transmit tracklog"); } catch (Exception ee) { logger.error("Error while sending tracklogs: " + ee); } return false; } private boolean receiveGpx() { try { boolean success; // String jsr172Version = null; Class parserClass; Object parserObject; GpxParser parser; // try { // jsr172Version = System.getProperty("xml.jaxp.subset.version"); // } catch (RuntimeException re) { // /** // * Some phones throw exceptions if trying to access properties that don't // * exist, so we have to catch these and just ignore them. // */ // } catch (Exception e) { // /** // * See above // */ // } // if ((jsr172Version != null) && (jsr172Version.length() > 0)) { // logger.info("Using builtin jsr 172 XML parser"); // parserClass = Class.forName("de.ueller.midlet.gps.importexport.Jsr172GpxParser"); // } else { logger.info("Using MinML2 XML parser"); parserClass = Class.forName("de.ueller.midlet.gps.importexport.MinML2GpxParser"); // } parserObject = parserClass.newInstance(); parser = (GpxParser) parserObject; applyRecordingRules = false; success = parser.parse(in, maxDistance, this); applyRecordingRules = true; in.close(); importExportMessage = parser.getMessage(); return success; } catch (ClassNotFoundException cnfe) { importExportMessage = "Your phone does not support XML parsing"; } catch (Exception e) { importExportMessage = "Something went wrong while importing GPX, " + e; } return false; } /** * Formats an integer to 2 digits, as used for example in time. * I.e. a 0 gets printed as 00. **/ private static final String formatInt2(int n) { if (n < 10) { return "0" + n; } else { return Integer.toString(n); } } /** * Date-Time formatter that corresponds to the standard UTC time as used in XML * @param time * @return */ private static final String formatUTC(Date time) { // This function needs optimising. It has a too high object churn. Calendar c = null; if (c == null) c = Calendar.getInstance(); c.setTime(time); return c.get(Calendar.YEAR) + "-" + formatInt2(c.get(Calendar.MONTH) + 1) + "-" + formatInt2(c.get(Calendar.DAY_OF_MONTH)) + "T" + formatInt2(c.get(Calendar.HOUR_OF_DAY)) + ":" + formatInt2(c.get(Calendar.MINUTE)) + ":" + formatInt2(c.get(Calendar.SECOND)) + "Z"; } public void walk(PaintContext pc, int opt) { // TODO Auto-generated method stub } }
true
true
public void addTrkPt(Position trkpt) { if (trkRecordingSuspended) return; //#debug info logger.info("Adding trackpoint: " + trkpt); Configuration config=GpsMid.getInstance().getConfig(); long msTime=trkpt.date.getTime(); float lat=trkpt.latitude*MoreMath.FAC_DECTORAD; float lon=trkpt.longitude*MoreMath.FAC_DECTORAD; float distance = 0.0f; boolean doRecord=false; try { // always record when i.e. receiving or loading tracklogs // or when starting to record if (!applyRecordingRules || recorded==0) { doRecord=true; distance = ProjMath.getDistance(lat, lon, oldlat, oldlon); } // check which record rules to apply else if (config.getGpxRecordRuleMode()==Configuration.GPX_RECORD_ADAPTIVE) { /** adaptive recording * * When saving tracklogs and adaptive recording is enabled, * we reduce the frequency of saved samples if the speed drops * to less than a certain amount. This should increase storage * efficiency if one doesn't need if one doesn't need to repeatedly * store positions if the device is not moving * * Chose the following arbitrary sampling frequency: * Greater 8km/h (2.22 m/s): every sample * Greater 4km/h (1.11 m/s): every second sample * Greater 2km/h (0.55 m/s): every fourth sample * Below 2km/h (0.55 m/s): every tenth sample */ if ( (trkpt.speed > 2.222f) || ((trkpt.speed > 1.111f) && (delay > 0 )) || ((trkpt.speed > 0.556) && delay > 3 ) || (delay > 10)) { doRecord=true; distance = ProjMath.getDistance(lat, lon, oldlat, oldlon); delay = 0; } else { delay++; } } else { /* user-specified recording rules */ distance = ProjMath.getDistance(lat, lon, oldlat, oldlon); if ( // is not always record distance not set // or always record distance reached ( config.getGpxRecordAlwaysDistanceCentimeters()!=0 && 100*distance >= config.getGpxRecordAlwaysDistanceCentimeters() ) || ( ( // is minimum time interval not set // or interval at least minimum interval? config.getGpxRecordMinMilliseconds() == 0 || Math.abs(msTime-oldMsTime) >= config.getGpxRecordMinMilliseconds() ) && ( // is minimum distance not set // or distance at least minimum distance? config.getGpxRecordMinDistanceCentimeters()==0 || 100*distance >= config.getGpxRecordMinDistanceCentimeters() ) ) ) { doRecord=true; } } if(doRecord) { dos.writeFloat(trkpt.latitude); dos.writeFloat(trkpt.longitude); dos.writeShort((short)trkpt.altitude); dos.writeLong(trkpt.date.getTime()); dos.writeByte((byte)(trkpt.speed*3.6f)); //Convert to km/h recorded++; if ((oldlat != 0.0f) || (oldlon != 0.0f)) { trkOdo += distance; trkTimeTot += msTime - oldMsTime; if (trkVmax < trkpt.speed) trkVmax = trkpt.speed; } oldMsTime=msTime; oldlat=lat; oldlon=lon; } } catch (OutOfMemoryError oome) { try { Trace.getInstance().dropCache(); logger.info("Was out of memory, but we might have recovered"); }catch (OutOfMemoryError oome2) { logger.fatal("Out of memory, can't add trackpoint"); } } catch (IOException e) { logger.exception("Could not add trackpoint", e); } }
public void addTrkPt(Position trkpt) { if (trkRecordingSuspended) return; //#debug info logger.info("Adding trackpoint: " + trkpt); Configuration config=GpsMid.getInstance().getConfig(); long msTime=trkpt.date.getTime(); float lat=trkpt.latitude*MoreMath.FAC_DECTORAD; float lon=trkpt.longitude*MoreMath.FAC_DECTORAD; float distance = 0.0f; boolean doRecord=false; try { // always record when i.e. receiving or loading tracklogs // or when starting to record if (!applyRecordingRules || recorded==0) { doRecord=true; distance = ProjMath.getDistance(lat, lon, oldlat, oldlon); } // check which record rules to apply else if (config.getGpxRecordRuleMode()==Configuration.GPX_RECORD_ADAPTIVE) { /** adaptive recording * * When saving tracklogs and adaptive recording is enabled, * we reduce the frequency of saved samples if the speed drops * to less than a certain amount. This should increase storage * efficiency if one doesn't need if one doesn't need to repeatedly * store positions if the device is not moving * * Chose the following arbitrary sampling frequency: * Greater 8km/h (2.22 m/s): every sample * Greater 4km/h (1.11 m/s): every second sample * Greater 2km/h (0.55 m/s): every fourth sample * Below 2km/h (0.55 m/s): every tenth sample */ if ( (trkpt.speed > 2.222f) || ((trkpt.speed > 1.111f) && (delay > 0 )) || ((trkpt.speed > 0.556) && delay > 3 ) || (delay > 10)) { doRecord=true; distance = ProjMath.getDistance(lat, lon, oldlat, oldlon); delay = 0; } else { delay++; } } else { /* user-specified recording rules */ distance = ProjMath.getDistance(lat, lon, oldlat, oldlon); if ( // is not always record distance not set // or always record distance reached ( config.getGpxRecordAlwaysDistanceCentimeters()!=0 && 100*distance >= config.getGpxRecordAlwaysDistanceCentimeters() ) || ( ( // is minimum time interval not set // or interval at least minimum interval? config.getGpxRecordMinMilliseconds() == 0 || Math.abs(msTime-oldMsTime) >= config.getGpxRecordMinMilliseconds() ) && ( // is minimum distance not set // or distance at least minimum distance? config.getGpxRecordMinDistanceCentimeters()==0 || 100*distance >= config.getGpxRecordMinDistanceCentimeters() ) ) ) { doRecord=true; } } if(doRecord) { dos.writeFloat(trkpt.latitude); dos.writeFloat(trkpt.longitude); dos.writeShort((short)trkpt.altitude); dos.writeLong(trkpt.date.getTime()); dos.writeByte((byte)(trkpt.speed*3.6f)); //Convert to km/h recorded++; tile.addTrkPt(trkpt.latitude, trkpt.longitude, false); if ((oldlat != 0.0f) || (oldlon != 0.0f)) { trkOdo += distance; trkTimeTot += msTime - oldMsTime; if (trkVmax < trkpt.speed) trkVmax = trkpt.speed; } oldMsTime=msTime; oldlat=lat; oldlon=lon; } } catch (OutOfMemoryError oome) { try { Trace.getInstance().dropCache(); logger.info("Was out of memory, but we might have recovered"); }catch (OutOfMemoryError oome2) { logger.fatal("Out of memory, can't add trackpoint"); } } catch (IOException e) { logger.exception("Could not add trackpoint", e); } }
diff --git a/plugins/org.eclipse.m2m.atl.engine/src/org/eclipse/m2m/atl/engine/AtlEMFModelHandler.java b/plugins/org.eclipse.m2m.atl.engine/src/org/eclipse/m2m/atl/engine/AtlEMFModelHandler.java index 0c602dfa..90621d03 100644 --- a/plugins/org.eclipse.m2m.atl.engine/src/org/eclipse/m2m/atl/engine/AtlEMFModelHandler.java +++ b/plugins/org.eclipse.m2m.atl.engine/src/org/eclipse/m2m/atl/engine/AtlEMFModelHandler.java @@ -1,313 +1,320 @@ /* * Created on 1 juin 2004 * */ package org.eclipse.m2m.atl.engine; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.logging.Level; import org.atl.engine.injectors.ebnf.EBNFInjector2; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.xmi.XMIResource; import org.eclipse.m2m.atl.drivers.emf4atl.ASMEMFModel; import org.eclipse.m2m.atl.drivers.emf4atl.EMFModelLoader; import org.eclipse.m2m.atl.engine.injectors.xml.XMLInjector; import org.eclipse.m2m.atl.engine.vm.ModelLoader; import org.eclipse.m2m.atl.engine.vm.nativelib.ASMModel; /** * @author JOUAULT * */ public class AtlEMFModelHandler extends AtlModelHandler { protected ASMEMFModel mofmm; protected ASMEMFModel atlmm; // we only use a ModelLoader to make sure ASMString.inject(...) can work protected EMFModelLoader ml; public void saveModel(final ASMModel model, IProject project) { saveModel(model, model.getName() + ".ecore", project); } public void saveModel(final ASMModel model, String fileName, IProject project) { String uri = project.getFullPath().toString() + "/" + fileName; saveModel(model, uri); } public void saveModel(final ASMModel model, String uri) { saveModel(model, URI.createURI(uri), null); } public void saveModel(final ASMModel model, OutputStream out) { saveModel(model, null, out); } protected boolean useIDs = false; protected boolean removeIDs = false; protected String encoding = "ISO-8859-1"; /** * Saves the provided model in/out of the Eclipse workspace using the given relative/absolute path. * @param model The model to save. * @param path The workspace relative path (e.g. "/ProjectXXX/fileName.ecore") if the outputFileIsInWorkspace boolean is set to true, or the absolute path if not (e.g. "C:/FolderXXX/fileName.ecore"). * @param outputFileIsInWorkspace Indicates if the model output file is stored into the Eclipse workspace. * @author Hugo Bruneliere */ public void saveModel(final ASMModel model, String path, boolean outputFileIsInWorkspace) { URI uri = null; if( outputFileIsInWorkspace ) uri = URI.createURI(path); else uri = URI.createFileURI(path); Resource r = ((ASMEMFModel)model).getExtent(); r.setURI(uri); Map options = new HashMap(); options.put(XMIResource.OPTION_ENCODING, encoding); options.put(XMIResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.FALSE); if((useIDs || removeIDs) && (r instanceof XMIResource)) { XMIResource xr = ((XMIResource)r); int id = 1; Set alreadySet = new HashSet(); for(Iterator i = r.getAllContents() ; i.hasNext() ; ) { EObject eo = (EObject)i.next(); if(alreadySet.contains(eo)) continue; // because sometimes a single element gets processed twice xr.setID(eo, removeIDs ? null : ("a" + (id++))); alreadySet.add(eo); } } try { r.save(options); if( outputFileIsInWorkspace ) { IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(uri.path())); file.setDerived(true); } } catch (IOException e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); } catch (CoreException e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); } } protected void saveModel(final ASMModel model, URI uri, OutputStream out) { Resource r = ((ASMEMFModel)model).getExtent(); if (uri != null) { r.setURI(uri); } Map options = new HashMap(); options.put(XMIResource.OPTION_ENCODING, encoding); options.put(XMIResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.FALSE); if((useIDs || removeIDs) && (r instanceof XMIResource)) { XMIResource xr = ((XMIResource)r); int id = 1; Set alreadySet = new HashSet(); for(Iterator i = r.getAllContents() ; i.hasNext() ; ) { EObject eo = (EObject)i.next(); if(alreadySet.contains(eo)) continue; // because sometimes a single element gets processed twice xr.setID(eo, removeIDs ? null : ("a" + (id++))); alreadySet.add(eo); } } try { if (out != null) { r.save(out, options); } else { r.save(options); } - if(uri != null) { - IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(uri.path())); - file.setDerived(true); + try { + if (uri != null) { + IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(uri.path())); + if (file.exists()) { + file.setDerived(true); + } + } + } catch (IllegalStateException e) { + // workspace is closed + logger.log(Level.FINE, e.getLocalizedMessage(), e); } } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); // e1.printStackTrace(); } catch (CoreException e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); // e1.printStackTrace(); } } protected AtlEMFModelHandler() { URL atlurl = AtlEMFModelHandler.class.getResource("resources/ATL-0.2.ecore"); ml = new EMFModelLoader(); ml.addInjector("xml", XMLInjector.class); ml.addInjector("ebnf2", EBNFInjector2.class); if (Platform.isRunning()) { //no IExtensionRegistry supported outside Eclipse IExtensionRegistry registry = Platform.getExtensionRegistry(); if (registry != null) { IExtensionPoint point = registry.getExtensionPoint("org.eclipse.m2m.atl.engine.injector"); IExtension[] extensions = point.getExtensions(); for(int i = 0 ; i < extensions.length ; i++){ IConfigurationElement[] elements = extensions[i].getConfigurationElements(); for(int j = 0 ; j < elements.length ; j++){ try { ml.addInjector(elements[j].getAttribute("name"), elements[j].createExecutableExtension("class").getClass()); } catch (CoreException e){ logger.log(Level.SEVERE, e.getLocalizedMessage(), e); // e.printStackTrace(); } } } } } mofmm = (ASMEMFModel)ml.getMOF(); //org.eclipse.m2m.atl.drivers.emf4atl.ASMEMFModel.createMOF(ml); try { atlmm = ASMEMFModel.loadASMEMFModel("ATL", mofmm, atlurl, ml); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); // e.printStackTrace(); } } public ASMModel getMof() { return mofmm; } public ASMModel getAtl() { return atlmm; } public ASMModel loadModel(String name, ASMModel metamodel, InputStream in) { ASMModel ret = null; try { ret = ASMEMFModel.loadASMEMFModel(name, (ASMEMFModel)metamodel, in, ml); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); // e.printStackTrace(); } return ret; } public ASMModel loadModel(String name, ASMModel metamodel, URI uri) { ASMModel ret = null; try { ret = ASMEMFModel.loadASMEMFModel(name, (ASMEMFModel)metamodel, uri, ml); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); // e.printStackTrace(); } return ret; } public ASMModel loadModel(String name, ASMModel metamodel, String uri) { ASMModel ret = null; try { ret = ASMEMFModel.loadASMEMFModel(name, (ASMEMFModel)metamodel, uri, ml); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); // e.printStackTrace(); } return ret; } /** * @see ASMEMFModel#newASMEMFModel(String, ASMEMFModel, ModelLoader) * @deprecated */ public ASMModel newModel(String name, ASMModel metamodel) { ASMModel ret = null; try { ret = ASMEMFModel.newASMEMFModel(name, (ASMEMFModel)metamodel, ml); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); // e.printStackTrace(); } return ret; } /** * @see ASMEMFModel#newASMEMFModel(String, String, ASMEMFModel, ModelLoader) * @author Dennis Wagelaar <[email protected]> */ public ASMModel newModel(String name, String uri, ASMModel metamodel) { ASMModel ret = null; if(uri == null) uri = name; try { ret = ASMEMFModel.newASMEMFModel(name, uri, (ASMEMFModel)metamodel, ml); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); // e.printStackTrace(); } return ret; } private Map bimm = new HashMap(); public ASMModel getBuiltInMetaModel(String name) { ASMModel ret = (ASMModel)bimm.get(name); if(ret == null) { URL mmurl = AtlParser.class.getResource("resources/" + name + ".ecore"); try { ret = loadModel(name, mofmm, mmurl.openStream()); } catch (IOException e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); // e.printStackTrace(); } bimm.put(name, ret); } return ret; } public boolean isHandling(ASMModel model) { return model instanceof ASMEMFModel; } public void disposeOfModel(ASMModel model) { ((ASMEMFModel)model).dispose(); } public static ResourceSet getResourceSet() { return ASMEMFModel.getResourceSet(); } }
true
true
protected void saveModel(final ASMModel model, URI uri, OutputStream out) { Resource r = ((ASMEMFModel)model).getExtent(); if (uri != null) { r.setURI(uri); } Map options = new HashMap(); options.put(XMIResource.OPTION_ENCODING, encoding); options.put(XMIResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.FALSE); if((useIDs || removeIDs) && (r instanceof XMIResource)) { XMIResource xr = ((XMIResource)r); int id = 1; Set alreadySet = new HashSet(); for(Iterator i = r.getAllContents() ; i.hasNext() ; ) { EObject eo = (EObject)i.next(); if(alreadySet.contains(eo)) continue; // because sometimes a single element gets processed twice xr.setID(eo, removeIDs ? null : ("a" + (id++))); alreadySet.add(eo); } } try { if (out != null) { r.save(out, options); } else { r.save(options); } if(uri != null) { IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(uri.path())); file.setDerived(true); } } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); // e1.printStackTrace(); } catch (CoreException e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); // e1.printStackTrace(); } }
protected void saveModel(final ASMModel model, URI uri, OutputStream out) { Resource r = ((ASMEMFModel)model).getExtent(); if (uri != null) { r.setURI(uri); } Map options = new HashMap(); options.put(XMIResource.OPTION_ENCODING, encoding); options.put(XMIResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.FALSE); if((useIDs || removeIDs) && (r instanceof XMIResource)) { XMIResource xr = ((XMIResource)r); int id = 1; Set alreadySet = new HashSet(); for(Iterator i = r.getAllContents() ; i.hasNext() ; ) { EObject eo = (EObject)i.next(); if(alreadySet.contains(eo)) continue; // because sometimes a single element gets processed twice xr.setID(eo, removeIDs ? null : ("a" + (id++))); alreadySet.add(eo); } } try { if (out != null) { r.save(out, options); } else { r.save(options); } try { if (uri != null) { IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(uri.path())); if (file.exists()) { file.setDerived(true); } } } catch (IllegalStateException e) { // workspace is closed logger.log(Level.FINE, e.getLocalizedMessage(), e); } } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); // e1.printStackTrace(); } catch (CoreException e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); // e1.printStackTrace(); } }
diff --git a/src/de/olilo/euler/level1/Level1Runner.java b/src/de/olilo/euler/level1/Level1Runner.java index 53f7b60..6eb3d17 100644 --- a/src/de/olilo/euler/level1/Level1Runner.java +++ b/src/de/olilo/euler/level1/Level1Runner.java @@ -1,161 +1,162 @@ package de.olilo.euler.level1; import de.olilo.euler.GridReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; public class Level1Runner { private final List<Long> timestamps = new ArrayList<Long>(); private final Problem1Multiples problem1 = new Problem1Multiples(); private final Problem2Fibonacci problem2 = new Problem2Fibonacci(); private final Problem3LargestPrime problem3 = new Problem3LargestPrime(); private final Problem3PrimeFactorsAddendum problem3Addendum = new Problem3PrimeFactorsAddendum(); private final Problem4Palindrome problem4 = new Problem4Palindrome(); private final Problem5SmallestMultiple problem5 = new Problem5SmallestMultiple(); private final Problem6SumSquareDifference problem6 = new Problem6SumSquareDifference(); private final Problem7NthPrime problem7 = new Problem7NthPrime(); private final Problem8GreatestProduct problem8 = new Problem8GreatestProduct(); private final Problem9PythagoreanTriplet problem9 = new Problem9PythagoreanTriplet(); private final Problem10SumOfPrimes problem10 = new Problem10SumOfPrimes(); private final Problem11GridProduct problem11 = new Problem11GridProduct(); private final Problem12TriangularNumber problem12 = new Problem12TriangularNumber(); private final Problem13LargeSum problem13 = new Problem13LargeSum(); private final Problem14CollatzSequence problem14 = new Problem14CollatzSequence(); private final Problem15LatticePaths problem15 = new Problem15LatticePaths(); private final Problem16PowerDigitSum problem16 = new Problem16PowerDigitSum(); private final Problem17NumberLetterCounts problem17 = new Problem17NumberLetterCounts(); private final Problem18MaximumPathSum problem18 = new Problem18MaximumPathSum(); private final Problem19CountingSundays problem19 = new Problem19CountingSundays(); private final Problem20FactorialDigitSum problem20 = new Problem20FactorialDigitSum(); private FileReader file8Number; private FileReader file11Grid; private FileReader file13Numbers; private FileReader file18Triangle; public List<Long> runWith(final PrintStream out) throws IOException { file8Number = new FileReader("problem8number.txt"); file11Grid = new FileReader("problem11grid.txt"); file13Numbers = new FileReader("problem13numbers.txt"); file18Triangle = new FileReader("problem18triangle.txt"); problems1To5(out); problems6To10(out); problems11To15(out); problems16To20(out); // cleanup file8Number.close(); file11Grid.close(); file13Numbers.close(); file18Triangle.close(); return timestamps; } private void problems1To5(final PrintStream out) { out.println("Problem 1: Multiples of 3 and 5; result: " + problem1.solveIteratively(1000)); problemFinished(); out.println("Problem 2: Sum of even Fibonaccis to 4.000.000; result: " + problem2.solve(4000000)); problemFinished(); // problem 3 and the addendum are merged into same timestamp statistic out.println("Problem 3: Largest prime factor of 600.851.475.143: " + problem3.getLargestPrimeOf(600851475143L)); out.println("Addendum Problem 3: Smallest number with 100 unique prime factors: " + problem3Addendum.findSmallestNumberWithNDistinctPrimeFactors(100)); problemFinished(); out.println("Problem 4: Biggest palindrome that is the product of two 3-digit numbers: " + problem4.findBiggestPalindromeFromTwoNDigitedNumbers(3)); problemFinished(); out.println("Problem 5: Smallest multiple up to 20: " + problem5.findSmallestMultipleUpTo(20)); problemFinished(); } private void problems6To10(final PrintStream out) throws IOException { out.println("Problem 6: Difference between square of sum and sum of squares up to 100: " + problem6.getSumSquareDifference(100)); problemFinished(); out.println("Problem 7: 10001st prime number is: " + problem7.getNthPrime(10001)); problemFinished(); out.println("Problem 8: Greatest product of five consecutive digits in 1000-digit number: " + problem8.greatestProduct(problem8.readNumberFrom(file8Number), 5)); problemFinished(); out.println("Problem 9: Pythagorean triplet with sum of 1000: " + problem9.findPythagoreanTriplet(1000)); out.println("Problem 9 Addendum: with sum of 100000: " + problem9.findPythagoreanTriplet(100000)); problemFinished(); out.println("Problem 10: Sum of all primes up to 2.000.000: " + problem10.sumOfPrimesUpTo(2000000)); problemFinished(); } private void problems11To15(final PrintStream out) throws IOException { out.println("Problem 11: Greatest product in grid: " + problem11.findGreatestProductIn(new GridReader(file11Grid).readGrid(), new GridFactorCount(4))); problemFinished(); out.println("Problem 12: First Triangular number that has at least 500 divisors: " + problem12.findFirstTriangularNumberWithNDivisors(500)); problemFinished(); out.println("Problem 13: First ten digits of sum of numbers: " + problem13.firstTenDigitsOf(problem13.sumOf(problem13.readNumbersFrom(file13Numbers)))); problemFinished(); out.println("Problem 14: Longest Collatz sequence under 1 million: " + problem14.findLongestSequenceUnder(1000000)); problemFinished(); out.println("Problem 15: Number of lattice Paths through a 20x20 grid: " + problem15.latticePathsThroughGridWithLength(20)); problemFinished(); } private void problems16To20(final PrintStream out) throws IOException { out.println("Problem 16: Power digit sum - sum of digits of 2^1000: " + problem16.digitSumOfTwoToThePowerOf(1000)); problemFinished(); out.println("Problem 17: Number letter counts; letters in numbers from 1 to 1000: " + problem17.countLettersInNumberWordsFrom1To(1000)); problemFinished(); out.println("Problem 18: Maximum path sum in triangle: " + problem18.maximumPathSumOf(new GridReader(file18Triangle).readGrid())); problemFinished(); final Calendar calendar = Calendar.getInstance(); calendar.set(1901, Calendar.JANUARY, 1); final Date start = calendar.getTime(); calendar.set(2000, Calendar.DECEMBER, 31); final Date finish = calendar.getTime(); out.println("Problem 19: Counting sundays on first of month in twentieth century: " + problem19.countFirstOfMonthIsSundayBetween(start, finish)); problemFinished(); - out.println("Problem 20: Factorial digit sum of 100!: " + + out.println("Problem 20: Digit sum of 100!: " + problem20.getFactorialDigitSum(100)); + problemFinished(); } int countFinishedProblems() { return timestamps.size(); } void problemFinished() { timestamps.add(System.currentTimeMillis()); } }
false
true
private void problems16To20(final PrintStream out) throws IOException { out.println("Problem 16: Power digit sum - sum of digits of 2^1000: " + problem16.digitSumOfTwoToThePowerOf(1000)); problemFinished(); out.println("Problem 17: Number letter counts; letters in numbers from 1 to 1000: " + problem17.countLettersInNumberWordsFrom1To(1000)); problemFinished(); out.println("Problem 18: Maximum path sum in triangle: " + problem18.maximumPathSumOf(new GridReader(file18Triangle).readGrid())); problemFinished(); final Calendar calendar = Calendar.getInstance(); calendar.set(1901, Calendar.JANUARY, 1); final Date start = calendar.getTime(); calendar.set(2000, Calendar.DECEMBER, 31); final Date finish = calendar.getTime(); out.println("Problem 19: Counting sundays on first of month in twentieth century: " + problem19.countFirstOfMonthIsSundayBetween(start, finish)); problemFinished(); out.println("Problem 20: Factorial digit sum of 100!: " + problem20.getFactorialDigitSum(100)); }
private void problems16To20(final PrintStream out) throws IOException { out.println("Problem 16: Power digit sum - sum of digits of 2^1000: " + problem16.digitSumOfTwoToThePowerOf(1000)); problemFinished(); out.println("Problem 17: Number letter counts; letters in numbers from 1 to 1000: " + problem17.countLettersInNumberWordsFrom1To(1000)); problemFinished(); out.println("Problem 18: Maximum path sum in triangle: " + problem18.maximumPathSumOf(new GridReader(file18Triangle).readGrid())); problemFinished(); final Calendar calendar = Calendar.getInstance(); calendar.set(1901, Calendar.JANUARY, 1); final Date start = calendar.getTime(); calendar.set(2000, Calendar.DECEMBER, 31); final Date finish = calendar.getTime(); out.println("Problem 19: Counting sundays on first of month in twentieth century: " + problem19.countFirstOfMonthIsSundayBetween(start, finish)); problemFinished(); out.println("Problem 20: Digit sum of 100!: " + problem20.getFactorialDigitSum(100)); problemFinished(); }
diff --git a/wings2/src/java/org/wings/session/SessionServlet.java b/wings2/src/java/org/wings/session/SessionServlet.java index 14c4e74e..923d7f63 100644 --- a/wings2/src/java/org/wings/session/SessionServlet.java +++ b/wings2/src/java/org/wings/session/SessionServlet.java @@ -1,683 +1,683 @@ /* * $Id$ * Copyright 2000,2005 wingS development team. * * This file is part of wingS (http://www.j-wings.org). * * wingS 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. * * Please see COPYING for the complete licence. */ package org.wings.session; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wings.*; import org.wings.event.ExitVetoException; import org.wings.event.SRequestEvent; import org.wings.externalizer.ExternalizeManager; import org.wings.externalizer.ExternalizedResource; import org.wings.io.Device; import org.wings.io.DeviceFactory; import org.wings.io.ServletDevice; import org.wings.resource.DynamicCodeResource; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.*; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Enumeration; import java.util.Locale; import java.util.Arrays; /** * The servlet engine creates for each user a new HttpSession. This * HttpSession can be accessed by all Serlvets running in the engine. A * WingServlet creates one wings SessionServlet per HTTPSession and stores * it in its context. * <p>As the SessionServlets acts as Wrapper for the WingsServlet, you can * access from there as used the ServletContext and the HttpSession. * Additionally the SessionServlet containts also the wingS-Session with * all important services and the superordinated SFrame. To this SFrame all * wings-Components and hence the complete application state is attached. * The developer can access from any place via the SessionManager a * reference to the wingS-Session. Additionally the SessionServlet * provides access to the all containing HttpSession. * * @author <a href="mailto:[email protected]">Armin Haaf</a> * @version $Revision$ */ final class SessionServlet extends HttpServlet implements HttpSessionBindingListener { private final transient static Log log = LogFactory.getLog(SessionServlet.class); /** * The parent {@link WingServlet} */ protected transient HttpServlet parent = this; /** * This should be a resource .. */ protected String errorTemplateFile; /** * The session. */ private Session session; private boolean firstRequest = true; /** * Default constructor. */ protected SessionServlet() { } /** * Sets the parent servlet contianint this wings session * servlet (WingsServlet, delegating its requests to the SessionServlet). */ protected final void setParent(HttpServlet p) { if (p != null) parent = p; } public final Session getSession() { return session; } /** * Overrides the session set for setLocaleFromHeader by a request parameter. * Hence you can force the wings session to adopt the clients Locale. */ public final void setLocaleFromHeader(String[] args) { if (args == null) return; for (int i = 0; i < args.length; i++) { try { getSession().setLocaleFromHeader(Boolean.valueOf(args[i]).booleanValue()); } catch (Exception e) { log.error("setLocaleFromHeader", e); } } } /** * The Locale of the current wings session servlet is determined by * the locale transmitted by the browser. The request parameter * <PRE>LocaleFromHeader</PRE> can override the behaviour * of a wings session servlet to adopt the clients browsers Locale. * * @param req The request to determine the local from. */ protected final void handleLocale(HttpServletRequest req) { setLocaleFromHeader(req.getParameterValues("LocaleFromHeader")); if (getSession().getLocaleFromHeader()) { for (Enumeration en = req.getLocales(); en.hasMoreElements();) { Locale locale = (Locale) en.nextElement(); try { getSession().setLocale(locale); return; } catch (Exception ex) { log.warn("locale not supported " + locale); } // end of try-catch } // end of for () } } // jetzt kommen alle Servlet Methoden, die an den parent deligiert // werden public ServletContext getServletContext() { if (parent != this) return parent.getServletContext(); else return super.getServletContext(); } public String getInitParameter(String name) { if (parent != this) return parent.getInitParameter(name); else return super.getInitParameter(name); } public Enumeration getInitParameterNames() { if (parent != this) return parent.getInitParameterNames(); else return super.getInitParameterNames(); } /** * Delegates log messages to the according WingsServlet or alternativly * to the HttpServlet logger. * * @param msg The logmessage */ public void log(String msg) { if (parent != this) parent.log(msg); else super.log(msg); } public String getServletInfo() { if (parent != this) return parent.getServletInfo(); else return super.getServletInfo(); } public ServletConfig getServletConfig() { if (parent != this) return parent.getServletConfig(); else return super.getServletConfig(); } // bis hierhin /** * The error template which should be presented on any uncaught Exceptions can be set * via a property <code>wings.error.template</code> in the web.xml file. */ protected void initErrorTemplate(ServletConfig config) { if (errorTemplateFile == null) { errorTemplateFile = config.getInitParameter("wings.error.template"); } } /** * init */ public final void init(ServletConfig config, HttpServletRequest request, HttpServletResponse response) throws ServletException { try { initErrorTemplate(config); session = new Session(); SessionManager.setSession(session); // set request.url in session, if used in constructor of wings main classs if (request.isRequestedSessionIdValid()) { // this will fire an event, if the encoding has changed .. ((PropertyService) session).setProperty("request.url", new RequestURL("", getSessionEncoding(response))); } session.init(config, request); try { String mainClassName = config.getInitParameter("wings.mainclass"); Class mainClass = null; try { mainClass = Class.forName(mainClassName, true, Thread.currentThread() .getContextClassLoader()); } catch (ClassNotFoundException e) { // fallback, in case the servlet container fails to set the // context class loader. mainClass = Class.forName(mainClassName); } Object main = mainClass.newInstance(); } catch (Exception ex) { log.fatal("could not load wings.mainclass: " + config.getInitParameter("wings.mainclass"), ex); throw new ServletException(ex); } } finally { // The session was set by the constructor. After init we // expect that only doPost/doGet is called, which set the // session also. So remove it here. SessionManager.removeSession(); } } /** * this method references to * {@link #doGet(HttpServletRequest, HttpServletResponse)} */ public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { //value chosen to limit denial of service if (req.getContentLength() > getSession().getMaxContentLength() * 1024) { res.setContentType("text/html"); ServletOutputStream out = res.getOutputStream(); out.println("<html><head><title>Too big</title></head>"); out.println("<body><h1>Error - content length &gt; " + getSession().getMaxContentLength() + "k"); out.println("</h1></body></html>"); } else { doGet(req, res); } // sollte man den obigen Block nicht durch folgende Zeile ersetzen? //throw new RuntimeException("this method must never be called!"); // bsc: Wieso? } /** * Verarbeitet Informationen vom Browser: * <UL> * <LI> setzt Locale * <LI> Dispatch Get Parameter * <LI> feuert Form Events * </UL> * Ist synchronized, damit nur ein Frame gleichzeitig bearbeitet * werden kann. */ public final synchronized void doGet(HttpServletRequest req, HttpServletResponse response) { SessionManager.setSession(session); session.setServletRequest(req); session.setServletResponse(response); session.fireRequestEvent(SRequestEvent.REQUEST_START); // in case, the previous thread did not clean up. SForm.clearArmedComponents(); Device outputDevice = null; ReloadManager reloadManager = session.getReloadManager(); boolean isErrorHandling = false; try { /* * The tomcat 3.x has a bug, in that it does not encode the URL * sometimes. It does so, when there is a cookie, containing some * tomcat sessionid but that is invalid (because, for instance, * we restarted the tomcat in-between). * [I can't think of this being the correct behaviour, so I assume * it is a bug. ] * * So we have to workaround this here: if we actually got the * session id from a cookie, but it is not valid, we don't do * the encodeURL() here: we just leave the requestURL as it is * in the properties .. and this is url-encoded, since * we had set it up in the very beginning of this session * with URL-encoding on (see WingServlet::newSession()). * * Vice versa: if the requestedSessionId is valid, then we can * do the encoding (which then does URL-encoding or not, depending * whether the servlet engine detected a cookie). * (hen) */ RequestURL requestURL = null; if (req.isRequestedSessionIdValid()) { requestURL = new RequestURL("", getSessionEncoding(response)); // this will fire an event, if the encoding has changed .. ((PropertyService) session).setProperty("request.url", requestURL); } if (log.isDebugEnabled()) { log.debug("request URL: " + requestURL); log.debug("HTTP header:"); for (Enumeration en = req.getHeaderNames(); en.hasMoreElements();) { String header = (String) en.nextElement(); log.debug(" " + header + ": " + req.getHeader(header)); } } handleLocale(req); Enumeration en = req.getParameterNames(); Cookie[] cookies = req.getCookies(); // are there parameters/low level events to dispatch if (en.hasMoreElements()) { // only fire DISPATCH_START if we have parameters to dispatch session.fireRequestEvent(SRequestEvent.DISPATCH_START); if (cookies != null) { //dispatch cookies for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; String paramName = (String) cookie.getName(); String value = cookie.getValue(); if (log.isDebugEnabled()) log.debug("dispatching cookie " + paramName + " = " + value); session.getDispatcher().dispatch(paramName, new String[] { value }); } } while (en.hasMoreElements()) { String paramName = (String) en.nextElement(); String[] value = req.getParameterValues(paramName); if (log.isDebugEnabled()) log.debug("dispatching " + paramName + " = " + Arrays.asList(value)); session.getDispatcher().dispatch(paramName, value); } SForm.fireEvents(); // only fire DISPATCH DONE if we have parameters to dispatch session.fireRequestEvent(SRequestEvent.DISPATCH_DONE); } session.fireRequestEvent(SRequestEvent.PROCESS_REQUEST); // if the user chose to exit the session as a reaction on an // event, we got an URL to redirect after the session. /* * where is the right place? * The right place is * - _after_ we processed the events * (e.g. the 'Pressed Exit-Button'-event or gave * the user the chance to exit this session in the custom * processRequest()) * - but _before_ the rendering of the page, * because otherwise an redirect won't work, since we must * not have sent anything to the output stream). */ if (session.getExitAddress() != null) { try { session.firePrepareExit(); String redirectAddress; if (session.getExitAddress().length() > 0) { // redirect to user requested URL. redirectAddress = session.getExitAddress(); } else { // redirect to a fresh session. redirectAddress = req.getRequestURL().toString(); } req.getSession().invalidate(); // calls destroy implicitly response.sendRedirect(redirectAddress); return; } catch (ExitVetoException ex) { session.exit(null); } // end of try-catch } if (session.getRedirectAddress() != null) { // redirect to user requested URL. response.sendRedirect(session.getRedirectAddress()); session.setRedirectAddress(null); return; } // invalidate frames and resources reloadManager.invalidateResources(); reloadManager.notifyCGs(); // deliver resource. The // externalizer is able to handle static and dynamic resources ExternalizeManager extManager = getSession().getExternalizeManager(); String pathInfo = req.getPathInfo().substring(1); log.debug("pathInfo: " + pathInfo); /* * if we have no path info, or the special '_' path info * (that should be explained somewhere, Holger), then we * deliver the toplevel Frame of this application. */ String externalizeIdentifier = null; if (pathInfo == null || pathInfo.length() == 0 || "_".equals(pathInfo) || firstRequest) { log.debug("delivering default frame"); if (session.getFrames().size() == 0) throw new ServletException("no frame visible"); // get the first frame from the set and walk up the hierarchy. // this should work in most cases. if there are more than one // toplevel frames, the developer has to care about the resource // ids anyway .. SFrame defaultFrame = (SFrame) session.getFrames().iterator().next(); while (defaultFrame.getParent() != null) defaultFrame = (SFrame) defaultFrame.getParent(); Resource resource = defaultFrame.getDynamicResource(DynamicCodeResource.class); externalizeIdentifier = resource.getId(); firstRequest = false; } else { externalizeIdentifier = pathInfo; } // externalized this resource. ExternalizedResource extInfo = extManager .getExternalizedResource(externalizeIdentifier); if (extInfo != null) { outputDevice = DeviceFactory.createDevice(extInfo); //outputDevice = createOutputDevice(req, response, extInfo); session.fireRequestEvent(SRequestEvent.DELIVER_START, extInfo); extManager.deliver(extInfo, response, outputDevice); session.fireRequestEvent(SRequestEvent.DELIVER_DONE, extInfo); } else { handleUnknownResourceRequested(req, response); } } catch (Throwable e) { /* * error handling...implement it in SFrame */ SFrame defaultFrame = (SFrame) session.getFrames().iterator().next(); while (defaultFrame.getParent() != null) defaultFrame = (SFrame) defaultFrame.getParent(); if (defaultFrame != null && defaultFrame.handleError(e)) { doGet(req, response); isErrorHandling = true; return; } else { log.fatal("exception: ", e); handleException(response, e); } } finally { - if (session != null || !isErrorHandling) { + if (session != null && !isErrorHandling) { session.fireRequestEvent(SRequestEvent.REQUEST_END); } if (outputDevice != null) { try { outputDevice.close(); } catch (Exception e) { } } /* * the session might be null due to destroy(). */ - if (session != null || !isErrorHandling) { + if (session != null && !isErrorHandling) { reloadManager.clear(); session.setServletRequest(null); session.setServletResponse(null); } // make sure that the session association to the thread is removed // from the SessionManager SessionManager.removeSession(); SForm.clearArmedComponents(); } } /** * create a Device that is used to deliver the content, that is * session specific. * The default * implementation just creates a ServletDevice. You can override this * method to decide yourself what happens to the output. You might, for * instance, write some device, that logs the output for debugging * purposes, or one that creates a gziped output stream to transfer * data more efficiently. You get the request and response as well as * the ExternalizedResource to decide, what kind of device you want to create. * You can rely on the fact, that extInfo is not null. * Further, you can rely on the fact, that noting has been written yet * to the output, so that you can set you own set of Headers. * * @param request the HttpServletRequest that is answered * @param response the HttpServletResponse. * @param extInfo the externalized info of the resource about to be * delivered. */ protected Device createOutputDevice(HttpServletRequest request, HttpServletResponse response, ExternalizedResource extInfo) throws IOException { return new ServletDevice(response.getOutputStream()); } // Exception Handling private SFrame errorFrame; private SLabel errorStackTraceLabel; private SLabel errorMessageLabel; private SLabel versionLabel; /** * In case of an error, display an error page to the user. This is only * done when there is a property <code>wings.error.template</code> present * in the web.xml file. This property must contain a path relative to the * webapp which leads to a wingS template. In this template, placeholders * must be defined for wingS components named * <code>EXCEPTION_STACK_TRACE</code>, * <code>EXCEPTION_MESSAGE</code> and <code>WINGS_VERSION</code>. * @param res the HTTP Response to use * @param e the Exception to report */ protected void handleException(HttpServletResponse res, Throwable e) { try { if (errorFrame == null) { errorFrame = new SFrame(); /* * if we don't have an errorTemplateFile defined, then this * will throw an Exception, so the StackTrace is NOT exposed * to the user (may be security relevant) */ errorFrame.getContentPane().setLayout( new STemplateLayout(SessionManager.getSession() .getServletContext().getRealPath( errorTemplateFile))); errorStackTraceLabel = new SLabel(); errorFrame.getContentPane().add(errorStackTraceLabel, "EXCEPTION_STACK_TRACE"); errorMessageLabel = new SLabel(); errorFrame.getContentPane().add(errorMessageLabel, "EXCEPTION_MESSAGE"); versionLabel = new SLabel(); errorFrame.getContentPane().add(versionLabel, "WINGS_VERSION"); versionLabel.setText("wingS " + Version.getVersion() + " / " + Version.getCompileTime()); } res.setContentType("text/html"); ServletOutputStream out = res.getOutputStream(); errorStackTraceLabel.setText(getStackTraceString(e)); errorMessageLabel.setText(e.getMessage()!=null?e.getMessage():"none"); errorFrame.write(new ServletDevice(out)); } catch (Exception ex) { log.fatal("Exception handling failed.", ex); } } /** * This method is called, whenever a Resource is requested whose * name is not known within this session. * * @param req the causing HttpServletRequest * @param res the HttpServletResponse of this request */ protected void handleUnknownResourceRequested(HttpServletRequest req, HttpServletResponse res) throws IOException { res.setStatus(HttpServletResponse.SC_NOT_FOUND); res.setContentType("text/html"); res.getOutputStream().println("<h1>404 Not Found</h1>Unknown Resource Requested"); } /** * --- HttpSessionBindingListener --- * */ public void valueBound(HttpSessionBindingEvent event) { } public void valueUnbound(HttpSessionBindingEvent event) { destroy(); } /** * get the Session Encoding, that is appended to each URL. * Basically, this is response.encodeURL(""), but unfortuntatly, this * empty encoding isn't supported by Tomcat 4.x anymore. */ public static String getSessionEncoding(HttpServletResponse response) { if (response == null) return ""; // encode dummy non-empty URL. String enc = response.encodeURL("foo").substring(3); return enc; } public void destroy() { log.info("destroy called"); // Session is needed on destroying the session SessionManager.setSession(session); try { // hint the gc. setParent(null); session.destroy(); session = null; errorFrame = null; errorStackTraceLabel = null; errorMessageLabel = null; } catch (Exception ex) { log.error("destroy", ex); } finally { SessionManager.removeSession(); } } private String getStackTraceString(Throwable e) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); stringWriter.getBuffer().setLength(0); e.printStackTrace(printWriter); return stringWriter.toString(); } }
false
true
public final synchronized void doGet(HttpServletRequest req, HttpServletResponse response) { SessionManager.setSession(session); session.setServletRequest(req); session.setServletResponse(response); session.fireRequestEvent(SRequestEvent.REQUEST_START); // in case, the previous thread did not clean up. SForm.clearArmedComponents(); Device outputDevice = null; ReloadManager reloadManager = session.getReloadManager(); boolean isErrorHandling = false; try { /* * The tomcat 3.x has a bug, in that it does not encode the URL * sometimes. It does so, when there is a cookie, containing some * tomcat sessionid but that is invalid (because, for instance, * we restarted the tomcat in-between). * [I can't think of this being the correct behaviour, so I assume * it is a bug. ] * * So we have to workaround this here: if we actually got the * session id from a cookie, but it is not valid, we don't do * the encodeURL() here: we just leave the requestURL as it is * in the properties .. and this is url-encoded, since * we had set it up in the very beginning of this session * with URL-encoding on (see WingServlet::newSession()). * * Vice versa: if the requestedSessionId is valid, then we can * do the encoding (which then does URL-encoding or not, depending * whether the servlet engine detected a cookie). * (hen) */ RequestURL requestURL = null; if (req.isRequestedSessionIdValid()) { requestURL = new RequestURL("", getSessionEncoding(response)); // this will fire an event, if the encoding has changed .. ((PropertyService) session).setProperty("request.url", requestURL); } if (log.isDebugEnabled()) { log.debug("request URL: " + requestURL); log.debug("HTTP header:"); for (Enumeration en = req.getHeaderNames(); en.hasMoreElements();) { String header = (String) en.nextElement(); log.debug(" " + header + ": " + req.getHeader(header)); } } handleLocale(req); Enumeration en = req.getParameterNames(); Cookie[] cookies = req.getCookies(); // are there parameters/low level events to dispatch if (en.hasMoreElements()) { // only fire DISPATCH_START if we have parameters to dispatch session.fireRequestEvent(SRequestEvent.DISPATCH_START); if (cookies != null) { //dispatch cookies for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; String paramName = (String) cookie.getName(); String value = cookie.getValue(); if (log.isDebugEnabled()) log.debug("dispatching cookie " + paramName + " = " + value); session.getDispatcher().dispatch(paramName, new String[] { value }); } } while (en.hasMoreElements()) { String paramName = (String) en.nextElement(); String[] value = req.getParameterValues(paramName); if (log.isDebugEnabled()) log.debug("dispatching " + paramName + " = " + Arrays.asList(value)); session.getDispatcher().dispatch(paramName, value); } SForm.fireEvents(); // only fire DISPATCH DONE if we have parameters to dispatch session.fireRequestEvent(SRequestEvent.DISPATCH_DONE); } session.fireRequestEvent(SRequestEvent.PROCESS_REQUEST); // if the user chose to exit the session as a reaction on an // event, we got an URL to redirect after the session. /* * where is the right place? * The right place is * - _after_ we processed the events * (e.g. the 'Pressed Exit-Button'-event or gave * the user the chance to exit this session in the custom * processRequest()) * - but _before_ the rendering of the page, * because otherwise an redirect won't work, since we must * not have sent anything to the output stream). */ if (session.getExitAddress() != null) { try { session.firePrepareExit(); String redirectAddress; if (session.getExitAddress().length() > 0) { // redirect to user requested URL. redirectAddress = session.getExitAddress(); } else { // redirect to a fresh session. redirectAddress = req.getRequestURL().toString(); } req.getSession().invalidate(); // calls destroy implicitly response.sendRedirect(redirectAddress); return; } catch (ExitVetoException ex) { session.exit(null); } // end of try-catch } if (session.getRedirectAddress() != null) { // redirect to user requested URL. response.sendRedirect(session.getRedirectAddress()); session.setRedirectAddress(null); return; } // invalidate frames and resources reloadManager.invalidateResources(); reloadManager.notifyCGs(); // deliver resource. The // externalizer is able to handle static and dynamic resources ExternalizeManager extManager = getSession().getExternalizeManager(); String pathInfo = req.getPathInfo().substring(1); log.debug("pathInfo: " + pathInfo); /* * if we have no path info, or the special '_' path info * (that should be explained somewhere, Holger), then we * deliver the toplevel Frame of this application. */ String externalizeIdentifier = null; if (pathInfo == null || pathInfo.length() == 0 || "_".equals(pathInfo) || firstRequest) { log.debug("delivering default frame"); if (session.getFrames().size() == 0) throw new ServletException("no frame visible"); // get the first frame from the set and walk up the hierarchy. // this should work in most cases. if there are more than one // toplevel frames, the developer has to care about the resource // ids anyway .. SFrame defaultFrame = (SFrame) session.getFrames().iterator().next(); while (defaultFrame.getParent() != null) defaultFrame = (SFrame) defaultFrame.getParent(); Resource resource = defaultFrame.getDynamicResource(DynamicCodeResource.class); externalizeIdentifier = resource.getId(); firstRequest = false; } else { externalizeIdentifier = pathInfo; } // externalized this resource. ExternalizedResource extInfo = extManager .getExternalizedResource(externalizeIdentifier); if (extInfo != null) { outputDevice = DeviceFactory.createDevice(extInfo); //outputDevice = createOutputDevice(req, response, extInfo); session.fireRequestEvent(SRequestEvent.DELIVER_START, extInfo); extManager.deliver(extInfo, response, outputDevice); session.fireRequestEvent(SRequestEvent.DELIVER_DONE, extInfo); } else { handleUnknownResourceRequested(req, response); } } catch (Throwable e) { /* * error handling...implement it in SFrame */ SFrame defaultFrame = (SFrame) session.getFrames().iterator().next(); while (defaultFrame.getParent() != null) defaultFrame = (SFrame) defaultFrame.getParent(); if (defaultFrame != null && defaultFrame.handleError(e)) { doGet(req, response); isErrorHandling = true; return; } else { log.fatal("exception: ", e); handleException(response, e); } } finally { if (session != null || !isErrorHandling) { session.fireRequestEvent(SRequestEvent.REQUEST_END); } if (outputDevice != null) { try { outputDevice.close(); } catch (Exception e) { } } /* * the session might be null due to destroy(). */ if (session != null || !isErrorHandling) { reloadManager.clear(); session.setServletRequest(null); session.setServletResponse(null); } // make sure that the session association to the thread is removed // from the SessionManager SessionManager.removeSession(); SForm.clearArmedComponents(); } }
public final synchronized void doGet(HttpServletRequest req, HttpServletResponse response) { SessionManager.setSession(session); session.setServletRequest(req); session.setServletResponse(response); session.fireRequestEvent(SRequestEvent.REQUEST_START); // in case, the previous thread did not clean up. SForm.clearArmedComponents(); Device outputDevice = null; ReloadManager reloadManager = session.getReloadManager(); boolean isErrorHandling = false; try { /* * The tomcat 3.x has a bug, in that it does not encode the URL * sometimes. It does so, when there is a cookie, containing some * tomcat sessionid but that is invalid (because, for instance, * we restarted the tomcat in-between). * [I can't think of this being the correct behaviour, so I assume * it is a bug. ] * * So we have to workaround this here: if we actually got the * session id from a cookie, but it is not valid, we don't do * the encodeURL() here: we just leave the requestURL as it is * in the properties .. and this is url-encoded, since * we had set it up in the very beginning of this session * with URL-encoding on (see WingServlet::newSession()). * * Vice versa: if the requestedSessionId is valid, then we can * do the encoding (which then does URL-encoding or not, depending * whether the servlet engine detected a cookie). * (hen) */ RequestURL requestURL = null; if (req.isRequestedSessionIdValid()) { requestURL = new RequestURL("", getSessionEncoding(response)); // this will fire an event, if the encoding has changed .. ((PropertyService) session).setProperty("request.url", requestURL); } if (log.isDebugEnabled()) { log.debug("request URL: " + requestURL); log.debug("HTTP header:"); for (Enumeration en = req.getHeaderNames(); en.hasMoreElements();) { String header = (String) en.nextElement(); log.debug(" " + header + ": " + req.getHeader(header)); } } handleLocale(req); Enumeration en = req.getParameterNames(); Cookie[] cookies = req.getCookies(); // are there parameters/low level events to dispatch if (en.hasMoreElements()) { // only fire DISPATCH_START if we have parameters to dispatch session.fireRequestEvent(SRequestEvent.DISPATCH_START); if (cookies != null) { //dispatch cookies for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; String paramName = (String) cookie.getName(); String value = cookie.getValue(); if (log.isDebugEnabled()) log.debug("dispatching cookie " + paramName + " = " + value); session.getDispatcher().dispatch(paramName, new String[] { value }); } } while (en.hasMoreElements()) { String paramName = (String) en.nextElement(); String[] value = req.getParameterValues(paramName); if (log.isDebugEnabled()) log.debug("dispatching " + paramName + " = " + Arrays.asList(value)); session.getDispatcher().dispatch(paramName, value); } SForm.fireEvents(); // only fire DISPATCH DONE if we have parameters to dispatch session.fireRequestEvent(SRequestEvent.DISPATCH_DONE); } session.fireRequestEvent(SRequestEvent.PROCESS_REQUEST); // if the user chose to exit the session as a reaction on an // event, we got an URL to redirect after the session. /* * where is the right place? * The right place is * - _after_ we processed the events * (e.g. the 'Pressed Exit-Button'-event or gave * the user the chance to exit this session in the custom * processRequest()) * - but _before_ the rendering of the page, * because otherwise an redirect won't work, since we must * not have sent anything to the output stream). */ if (session.getExitAddress() != null) { try { session.firePrepareExit(); String redirectAddress; if (session.getExitAddress().length() > 0) { // redirect to user requested URL. redirectAddress = session.getExitAddress(); } else { // redirect to a fresh session. redirectAddress = req.getRequestURL().toString(); } req.getSession().invalidate(); // calls destroy implicitly response.sendRedirect(redirectAddress); return; } catch (ExitVetoException ex) { session.exit(null); } // end of try-catch } if (session.getRedirectAddress() != null) { // redirect to user requested URL. response.sendRedirect(session.getRedirectAddress()); session.setRedirectAddress(null); return; } // invalidate frames and resources reloadManager.invalidateResources(); reloadManager.notifyCGs(); // deliver resource. The // externalizer is able to handle static and dynamic resources ExternalizeManager extManager = getSession().getExternalizeManager(); String pathInfo = req.getPathInfo().substring(1); log.debug("pathInfo: " + pathInfo); /* * if we have no path info, or the special '_' path info * (that should be explained somewhere, Holger), then we * deliver the toplevel Frame of this application. */ String externalizeIdentifier = null; if (pathInfo == null || pathInfo.length() == 0 || "_".equals(pathInfo) || firstRequest) { log.debug("delivering default frame"); if (session.getFrames().size() == 0) throw new ServletException("no frame visible"); // get the first frame from the set and walk up the hierarchy. // this should work in most cases. if there are more than one // toplevel frames, the developer has to care about the resource // ids anyway .. SFrame defaultFrame = (SFrame) session.getFrames().iterator().next(); while (defaultFrame.getParent() != null) defaultFrame = (SFrame) defaultFrame.getParent(); Resource resource = defaultFrame.getDynamicResource(DynamicCodeResource.class); externalizeIdentifier = resource.getId(); firstRequest = false; } else { externalizeIdentifier = pathInfo; } // externalized this resource. ExternalizedResource extInfo = extManager .getExternalizedResource(externalizeIdentifier); if (extInfo != null) { outputDevice = DeviceFactory.createDevice(extInfo); //outputDevice = createOutputDevice(req, response, extInfo); session.fireRequestEvent(SRequestEvent.DELIVER_START, extInfo); extManager.deliver(extInfo, response, outputDevice); session.fireRequestEvent(SRequestEvent.DELIVER_DONE, extInfo); } else { handleUnknownResourceRequested(req, response); } } catch (Throwable e) { /* * error handling...implement it in SFrame */ SFrame defaultFrame = (SFrame) session.getFrames().iterator().next(); while (defaultFrame.getParent() != null) defaultFrame = (SFrame) defaultFrame.getParent(); if (defaultFrame != null && defaultFrame.handleError(e)) { doGet(req, response); isErrorHandling = true; return; } else { log.fatal("exception: ", e); handleException(response, e); } } finally { if (session != null && !isErrorHandling) { session.fireRequestEvent(SRequestEvent.REQUEST_END); } if (outputDevice != null) { try { outputDevice.close(); } catch (Exception e) { } } /* * the session might be null due to destroy(). */ if (session != null && !isErrorHandling) { reloadManager.clear(); session.setServletRequest(null); session.setServletResponse(null); } // make sure that the session association to the thread is removed // from the SessionManager SessionManager.removeSession(); SForm.clearArmedComponents(); } }
diff --git a/runtime/android/java/src/org/xwalk/core/XwViewContent.java b/runtime/android/java/src/org/xwalk/core/XwViewContent.java index c41b91be..b056600c 100644 --- a/runtime/android/java/src/org/xwalk/core/XwViewContent.java +++ b/runtime/android/java/src/org/xwalk/core/XwViewContent.java @@ -1,82 +1,82 @@ // Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.xwalk.core; import android.content.Context; import android.util.AttributeSet; import android.graphics.Rect; import android.view.ViewGroup; import android.widget.FrameLayout; import org.chromium.base.JNINamespace; import org.chromium.content.browser.ContentView; import org.chromium.content.browser.ContentViewCore; import org.chromium.content.browser.ContentViewRenderView; import org.chromium.content.browser.LoadUrlParams; import org.chromium.ui.WindowAndroid; @JNINamespace("xwalk") class XwViewContent extends FrameLayout { ContentViewCore mContentViewCore; ContentView mContentView; ContentViewRenderView mContentViewRenderView; WindowAndroid mWindow; int mXwViewContent; int mWebContents; boolean mReadyToLoad = false; public XwViewContent(Context context, AttributeSet attrs) { super(context, attrs); //TODO(yongsheng): initialize ContentVideoView // initialize ContentViewRenderView mContentViewRenderView = new ContentViewRenderView(context) { protected void onReadyToRender() { mReadyToLoad = true; } }; addView(mContentViewRenderView, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); //TODO(yongsheng): init native such as resource, content main, etc. mXwViewContent = nativeInit(); mWebContents = nativeGetWebContents(mXwViewContent); // initialize ContentView mContentView = ContentView.newInstance( - getContext(), mWebContents, mWindow, ContentView.PERSONALITY_VIEW); + getContext(), mWebContents, mWindow, ContentView.PERSONALITY_CHROME); addView(mContentView, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); mContentViewRenderView.setCurrentContentView(mContentView); // For addJavascriptInterface mContentViewCore = mContentView.getContentViewCore(); } public void loadUrl(String url) { if (mReadyToLoad) { //TODO(yongsheng): configure appropriate parameters here. LoadUrlParams params = new LoadUrlParams(url); mContentView.loadUrl(params); mContentView.clearFocus(); mContentView.requestFocus(); } } public void addJavascriptInterface(Object object, String name) { mContentViewCore.addJavascriptInterface(object, name); } private native int nativeInit(); private native int nativeGetWebContents(int nativeXwViewContent); }
true
true
public XwViewContent(Context context, AttributeSet attrs) { super(context, attrs); //TODO(yongsheng): initialize ContentVideoView // initialize ContentViewRenderView mContentViewRenderView = new ContentViewRenderView(context) { protected void onReadyToRender() { mReadyToLoad = true; } }; addView(mContentViewRenderView, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); //TODO(yongsheng): init native such as resource, content main, etc. mXwViewContent = nativeInit(); mWebContents = nativeGetWebContents(mXwViewContent); // initialize ContentView mContentView = ContentView.newInstance( getContext(), mWebContents, mWindow, ContentView.PERSONALITY_VIEW); addView(mContentView, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); mContentViewRenderView.setCurrentContentView(mContentView); // For addJavascriptInterface mContentViewCore = mContentView.getContentViewCore(); }
public XwViewContent(Context context, AttributeSet attrs) { super(context, attrs); //TODO(yongsheng): initialize ContentVideoView // initialize ContentViewRenderView mContentViewRenderView = new ContentViewRenderView(context) { protected void onReadyToRender() { mReadyToLoad = true; } }; addView(mContentViewRenderView, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); //TODO(yongsheng): init native such as resource, content main, etc. mXwViewContent = nativeInit(); mWebContents = nativeGetWebContents(mXwViewContent); // initialize ContentView mContentView = ContentView.newInstance( getContext(), mWebContents, mWindow, ContentView.PERSONALITY_CHROME); addView(mContentView, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); mContentViewRenderView.setCurrentContentView(mContentView); // For addJavascriptInterface mContentViewCore = mContentView.getContentViewCore(); }
diff --git a/src/main/java/eel/seprphase2/App.java b/src/main/java/eel/seprphase2/App.java index c8f4559..b18865b 100644 --- a/src/main/java/eel/seprphase2/App.java +++ b/src/main/java/eel/seprphase2/App.java @@ -1,13 +1,13 @@ package eel.seprphase2; /** * Hello world! * */ public class App { public static void main( String[] args ) { - System.out.println( "Hello World!" ); + System.out.println( "Hello, World!" ); } }
true
true
public static void main( String[] args ) { System.out.println( "Hello World!" ); }
public static void main( String[] args ) { System.out.println( "Hello, World!" ); }